Skip to content

Adxell/triangular-arbitrage-bot

Repository files navigation

Triangular Arbitrage Bot

Real-time triangular arbitrage bot for Binance. It discovers cyclic trading paths (e.g. USDT -> ETH -> BTC -> USDT), monitors live order book prices via WebSocket, and executes three sequential market orders when a profitable opportunity is detected.

How It Works

                        Binance WebSocket (bookTicker)
                                   |
                                   v
                  +-------------------------------+
                  |      OrderBookManager         |
                  |  (in-memory best bid/ask cache)|
                  +-------------------------------+
                                   |
                           price update
                                   v
                  +-------------------------------+
                  |       ArbitrageScanner        |
                  |  (inverted index: symbol ->   |
                  |   affected triangles)         |
                  +-------------------------------+
                                   |
                      profit > threshold?
                                   v
                  +-------------------------------+
                  |        TradeExecutor          |
                  |  (3 sequential market orders) |
                  +-------------------------------+
                                   |
                                   v
                            Log & Stats
  1. Triangle Discovery - On startup, loads all Binance spot markets and builds an adjacency graph to find valid 3-leg cycles starting and ending with the base currency.
  2. Order Book Streaming - Subscribes to bookTicker WebSocket streams for all symbols involved in discovered triangles. Updates an in-memory cache of best bid/ask prices.
  3. Opportunity Detection - When a price updates, only the triangles that use that symbol are re-evaluated. The scanner simulates the full 3-leg trade including fees and slippage.
  4. Trade Execution - If net profit exceeds the configured threshold, three sequential market orders are placed. Balance is verified before each leg.

Prerequisites

  • Python 3.12+
  • Binance account with API keys (Testnet or Production)
  • Docker (optional, for containerized deployment)

Quick Start

Local

# Clone the repository
git clone https://github.com/your-user/triangular-arbitrage-bot.git
cd triangular-arbitrage-bot

# Create virtual environment and install dependencies
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Configure environment
cp .env.example .env
# Edit .env with your Binance API keys

# Run the bot
python main.py

Docker

# Configure environment
cp .env.example .env
# Edit .env with your Binance API keys

# Build and run
docker compose up -d

# View logs
docker compose logs -f

Run Modes

Mode Command Description
Live python main.py Full execution - detects and trades opportunities
Dry Run python main.py --dry-run Detects opportunities but does not place orders
Scan Only python main.py --scan-only Discovers triangles and exits (no WebSocket connection)

With Docker, pass arguments after the service name:

docker compose run --rm bot --dry-run

Configuration

All configuration is done via environment variables in the .env file. See .env.example for a complete template.

API Keys

Variable Description Default
BINANCE_API_KEY Binance API key required
BINANCE_API_SECRET Binance API secret required

Bot Settings

Variable Description Default
USE_TESTNET Connect to Binance Testnet true
BASE_CURRENCY Base currency for arbitrage cycles USDT
TRADE_AMOUNT_USDT Amount in base currency per trade 100
MIN_PROFIT_PERCENTAGE Minimum net profit % to trigger execution 0.2
USE_BNB_FEE Use BNB to pay fees (0.075% instead of 0.1%) false
FEE_PERCENTAGE Fee per trade in % 0.1

Advanced Settings

Variable Description Default
ORDERBOOK_DEPTH Order book depth to request 5
MAX_SLIPPAGE_PERCENTAGE Maximum allowed slippage % before aborting 0.5
MAX_TRIANGLES Maximum triangles to monitor (0 = all) 50
EXECUTION_COOLDOWN_SECONDS Cooldown between executions in seconds 2
LOG_LEVEL Log level: DEBUG, INFO, WARNING, ERROR INFO
LOG_DIR Directory for log files logs

Project Structure

triangular-arbitrage-bot/
├── main.py                # Entry point and orchestrator
├── config.py              # Centralized configuration from .env
├── models.py              # Data structures and type definitions
├── triangle_finder.py     # Discovery of valid triangular arbitrage paths
├── orderbook_manager.py   # WebSocket order book manager
├── arbitrage_engine.py    # Arbitrage calculation and opportunity detection
├── trade_executor.py      # Order execution on Binance
├── requirements.txt       # Python dependencies
├── Dockerfile             # Container image definition
├── docker-compose.yml     # Container orchestration
├── .env.example           # Environment variable template
└── logs/                  # Runtime log files

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Commit your changes
  4. Push to the branch and open a Pull Request

License

This project is licensed under the MIT License.

Disclaimer

This software is provided for educational and experimental purposes only. Cryptocurrency trading involves significant risk. The authors are not responsible for any financial losses incurred from using this bot. Always test on Binance Testnet before using real funds. Use at your own risk.

About

An automated arbitrage trading bot for Binance. ⚠️ Disclaimer: Crypto trading involves significant risk. Always test on the Binance Testnet before using real funds. Use at your own risk.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors