Crypto Strategy

Crypto Arbitrage Bot Setup: Complete Guide for 2026

LedgerMind Originals
Stream Now
A cinematic trading experience
Ready to trade?
Buy crypto with the best rates across 1,000+ tokens
Buy Crypto →

A single arbitrage opportunity on Binance-Coinbase lasted 47 seconds in December 2025 and offered a 2.3% spread on ETH/USDT. By the time most traders noticed it, the window closed. The bot that captured it executed in 180 milliseconds and generated $4,700 profit from a $200,000 position.

This is the reality of crypto arbitrage in 2026: opportunities exist, but human reaction time doesn’t cut it anymore. The average profitable arbitrage window now lasts under 12 seconds, according to data from Kaiko Research. If you’re not automated, you’re not competing.

This guide walks through complete crypto arbitrage bot setup—from exchange API integration to risk management systems that protect capital when spreads reverse. We’ll cover spatial arbitrage (cross-exchange), triangular arbitrage (single-exchange), and statistical arbitrage strategies, backed by real performance data and code examples you can deploy today.

What Is Crypto Arbitrage? (And Why Bots Dominate in 2026)

Crypto arbitrage exploits price differences for the same asset across different venues. When Bitcoin trades at $67,200 on Kraken and $67,450 on Binance, a $250 spread exists. Buy on Kraken, sell on Binance, pocket the difference minus fees.

Three primary arbitrage types:

  1. Spatial arbitrage (cross-exchange): Buy Asset X on Exchange A, sell on Exchange B
  2. Triangular arbitrage (single-exchange): Exploit rate discrepancies in trading pairs (BTC→ETH→USDT→BTC)
  3. Statistical arbitrage: Trade correlated assets when price relationships deviate from historical norms

Why bots are essential:

  • Average arbitrage opportunity duration: 8-15 seconds (Kaiko, Q4 2025)
  • Manual execution time: 20-45 seconds (including order placement, confirmation)
  • Bot execution time: 50-300 milliseconds (including API latency)
  • Profitable opportunities per day (major pairs): 12-47 (varies by volatility)

According to CoinGecko data, arbitrage spreads above 0.5% occur 23 times per day on average across BTC, ETH, and major stablecoins on top-10 exchanges. Without automation, you’ll miss 94% of them.

Bots also eliminate emotional decision-making. When a spread appears but fees eat most of the profit, human traders often force trades hoping for quick reversals. Bots follow programmed logic: if net profit < threshold, skip the trade.

For traders interested in broader algorithmic strategies, our best crypto trading bots 2026 guide covers platform comparisons and automation tools beyond arbitrage.

Prerequisites: What You Need Before Building

Technical requirements:

  • Programming knowledge: Python (preferred), JavaScript/Node.js, or Go
  • API familiarity: REST and WebSocket protocols
  • Exchange accounts: Minimum 2-3 major exchanges with API access enabled
  • Capital: $5,000-$50,000+ (higher capital captures more opportunities, reduces percentage impact of fees)
  • Server infrastructure: VPS or cloud instance near exchange data centers (latency matters)

Exchange selection criteria:

Exchange API Quality Maker/Taker Fees Withdrawal Limits Arbitrage-Friendly?
Binance Excellent 0.10%/0.10% High Yes (with volume)
Coinbase Pro Good 0.40%/0.60% Medium Moderate
Kraken Good 0.16%/0.26% Medium Yes
OKX Excellent 0.08%/0.10% High Yes
Bybit Excellent 0.10%/0.10% High Yes
KuCoin Good 0.10%/0.10% Medium Yes

Note: Fees shown are base rates; VIP tiers reduce costs significantly

Capital considerations:

  • Minimum viable: $5,000-$10,000 (for testing and small positions)
  • Recommended: $25,000-$50,000 (capture more opportunities, better fee tiers)
  • Professional: $100,000+ (access institutional fee rates, handle larger spreads)

Higher capital doesn’t guarantee profit—it increases opportunity size. A 0.8% spread on $10,000 nets $80 before fees. The same spread on $100,000 nets $800. But risk scales proportionally.

Risk management essentials:

  • Never deploy more than 5-10% of total capital per arbitrage cycle
  • Maintain 30-50% in stablecoins for immediate deployment
  • Set maximum daily loss limits (2-5% of total capital)
  • Use separate API keys with withdrawal restrictions disabled

According to Glassnode data on institutional bot performance, accounts that maintain 40-60% stablecoin allocation capture 73% more arbitrage opportunities than fully-deployed portfolios.

Spatial Arbitrage Bot Setup (Cross-Exchange)

Spatial arbitrage is the simplest and most common strategy: buy low on Exchange A, sell high on Exchange B. Here’s how to build it.

Step 1: Exchange API Integration

First, establish connections to multiple exchanges. We’ll use Python with the CCXT library (a unified API wrapper supporting 100+ exchanges).

import ccxt import time

binance = ccxt.binance({ ‘apiKey’: ‘YOUR_BINANCE_KEY’, ‘secret’: ‘YOUR_BINANCE_SECRET’, ‘enableRateLimit’: True, })

kraken = ccxt.kraken({ ‘apiKey’: ‘YOUR_KRAKEN_KEY’, ‘secret’: ‘YOUR_KRAKEN_SECRET’, ‘enableRateLimit’: True, })

# Test connection print(binance.fetch_balance()) print(kraken.fetch_balance())

Key configuration points:

  • `enableRateLimit`: Prevents API rate limit violations (critical—exceeding limits gets your IP banned)
  • Store credentials in environment variables, never hardcode
  • Test with small amounts first (many exchanges offer testnet environments)

Step 2: Price Monitoring System

Build a real-time price comparison engine:

def fetch_prices(symbol=’BTC/USDT’): “””Fetch current bid/ask prices from multiple exchanges””” exchanges = [binance, kraken] prices = {}

for exchange in exchanges: try: ticker = exchange.fetch_ticker(symbol) prices[exchange.id] = { ‘bid’: ticker[‘bid’], # Highest buy price ‘ask’: ticker[‘ask’], # Lowest sell price ‘timestamp’: ticker[‘timestamp’] } except Exception as e: print(f”Error fetching {exchange.id}: {e}”)

return prices

def calculate_arbitrage_opportunity(prices, symbol=’BTC/USDT’): “””Identify profitable arbitrage spreads””” opportunities = []

exchange_ids = list(prices.keys()) for i in range(len(exchange_ids)): for j in range(i+1, len(exchange_ids)): buy_exchange = exchange_ids[i] sell_exchange = exchange_ids[j]

# Scenario 1: Buy on exchange i, sell on exchange j buy_price = prices[buy_exchange][‘ask’] sell_price = prices[sell_exchange][‘bid’] spread = (sell_price – buy_price) / buy_price * 100

if spread > 0: opportunities.append({ ‘buy_exchange’: buy_exchange, ‘sell_exchange’: sell_exchange, ‘buy_price’: buy_price, ‘sell_price’: sell_price, ‘spread_percent’: spread })

# Scenario 2: Buy on exchange j, sell on exchange i buy_price = prices[sell_exchange][‘ask’] sell_price = prices[buy_exchange][‘bid’] spread = (sell_price – buy_price) / buy_price * 100

if spread > 0: opportunities.append({ ‘buy_exchange’: sell_exchange, ‘sell_exchange’: buy_exchange, ‘buy_price’: buy_price, ‘sell_price’: sell_price, ‘spread_percent’: spread })

return opportunities

# Main monitoring loop while True: prices = fetch_prices(‘BTC/USDT’) opportunities = calculate_arbitrage_opportunity(prices)

if opportunities: print(f”Found {len(opportunities)} opportunities:”) for opp in opportunities: print(f” {opp[‘buy_exchange’]} → {opp[‘sell_exchange’]}: {opp[‘spread_percent’]:.2f}%”)

time.sleep(5) # Poll every 5 seconds

Step 3: Fee Calculation & Profitability Filter

Raw spreads mean nothing without fee accounting. Every arbitrage trade incurs:

  • Trading fees (both exchanges, buy and sell)
  • Withdrawal fees (moving funds between exchanges)
  • Network fees (blockchain transaction costs)
  • Slippage (price movement during order execution)

def calculate_net_profit(opportunity, trade_amount_usd=10000): “””Calculate actual profit after all fees”””

# Exchange fee structures (example—update with real rates) fees = { ‘binance’: {‘maker’: 0.001, ‘taker’: 0.001, ‘withdrawal’: 0.0005}, # 0.1%, 0.1%, 0.05% ‘kraken’: {‘maker’: 0.0016, ‘taker’: 0.0026, ‘withdrawal’: 0.0005}, }

buy_exchange = opportunity[‘buy_exchange’] sell_exchange = opportunity[‘sell_exchange’]

# Calculate position size in BTC btc_amount = trade_amount_usd / opportunity[‘buy_price’]

# Buy side costs buy_fee = btc_amount * fees[buy_exchange][‘taker’] buy_total = btc_amount + buy_fee

# Sell side costs sell_fee = btc_amount * fees[sell_exchange][‘taker’] sell_received = btc_amount – sell_fee

# Withdrawal cost (moving BTC from buy exchange to sell exchange) withdrawal_fee = fees[buy_exchange][‘withdrawal’]

# Net position after fees net_btc = sell_received – withdrawal_fee

# Calculate profit/loss sell_value_usd = net_btc * opportunity[‘sell_price’] profit_usd = sell_value_usd – trade_amount_usd profit_percent = (profit_usd / trade_amount_usd) * 100

return { ‘gross_spread’: opportunity[‘spread_percent’], ‘net_profit_usd’: profit_usd, ‘net_profit_percent’: profit_percent, ‘executable’: profit_percent > 0.3 # Minimum 0.3% profit threshold }

# Enhanced opportunity scanner while True: prices = fetch_prices(‘BTC/USDT’) opportunities = calculate_arbitrage_opportunity(prices)

for opp in opportunities: profit_analysis = calculate_net_profit(opp, trade_amount_usd=10000)

if profit_analysis[‘executable’]: print(f”\n🎯 EXECUTABLE OPPORTUNITY:”) print(f” Route: {opp[‘buy_exchange’]} → {opp[‘sell_exchange’]}”) print(f” Gross Spread: {opp[‘spread_percent’]:.2f}%”) print(f” Net Profit: ${profit_analysis[‘net_profit_usd’]:.2f} ({profit_analysis[‘net_profit_percent’]:.2f}%)”)

time.sleep(3)

Critical profitability thresholds (based on 2026 fee structures):

  • BTC/USDT: Minimum 0.4-0.6% spread required
  • ETH/USDT: Minimum 0.5-0.7% spread required
  • Altcoins: Minimum 0.8-1.2% spread (higher withdrawal fees, more slippage)

Step 4: Automated Order Execution

Once a profitable opportunity is detected, execute simultaneously on both exchanges:

def execute_arbitrage(opportunity, trade_amount_usd=10000): “””Execute arbitrage trade across two exchanges”””

buy_exchange = opportunity[‘buy_exchange’] sell_exchange = opportunity[‘sell_exchange’] symbol = ‘BTC/USDT’

# Calculate amounts btc_amount = trade_amount_usd / opportunity[‘buy_price’] btc_amount = round(btc_amount, 6) # Round to 6 decimals (BTC precision)

try: # Execute buy order buy_order = exchanges[buy_exchange].create_market_buy_order( symbol, btc_amount ) print(f”✅ Buy executed on {buy_exchange}: {btc_amount} BTC at ~${opportunity[‘buy_price’]}”)

# Execute sell order (assumes BTC already available—see transfer logic below) sell_order = exchanges[sell_exchange].create_market_sell_order( symbol, btc_amount ) print(f”✅ Sell executed on {sell_exchange}: {btc_amount} BTC at ~${opportunity[‘sell_price’]}”)

return { ‘success’: True, ‘buy_order’: buy_order, ‘sell_order’: sell_order }

except Exception as e: print(f”❌ Execution failed: {e}”) return {‘success’: False, ‘error’: str(e)}

Important execution considerations:

  1. Order type: Market orders guarantee execution but incur higher fees. Limit orders reduce fees but risk missing the opportunity.
  2. Simultaneous execution: Use threading/async to place both orders at once (reduces timing risk).
  3. Partial fills: Some exchanges partially fill large orders. Handle this in your logic.
  4. Balance checks: Always verify sufficient balance before attempting trades.

Step 5: Cross-Exchange Fund Transfer Management

The biggest challenge in spatial arbitrage: moving funds between exchanges fast enough to capture opportunities.

Two approaches:

Option A: Pre-positioned capital (recommended)

  • Maintain equal balances on all exchanges (50% USDT, 50% BTC)
  • No transfer delays—always ready to execute
  • Requires more total capital
  • Rebalance weekly as positions drift

Option B: Dynamic transfers

  • Transfer funds only when opportunities arise
  • Lower capital requirements
  • 10-60 minute transfer delays (kills most opportunities)
  • Only viable for persistent, large spreads

For serious arbitrage, pre-positioned capital is non-negotiable. Here’s a basic rebalancing function:

def rebalance_exchanges(exchanges, target_usdt=25000, target_btc=0.5): “””Rebalance funds across exchanges to maintain equal positioning”””

for exchange_name, exchange in exchanges.items(): balance = exchange.fetch_balance()

usdt_balance = balance[‘USDT’][‘free’] btc_balance = balance[‘BTC’][‘free’]

# Calculate required transfers usdt_diff = target_usdt – usdt_balance btc_diff = target_btc – btc_balance

print(f”\n{exchange_name} rebalancing needed:”) print(f” USDT: {usdt_balance:.2f} (target: {target_usdt}) → {usdt_diff:+.2f}”) print(f” BTC: {btc_balance:.6f} (target: {target_btc}) → {btc_diff:+.6f}”)

# Execute transfers (implement actual withdrawal/deposit logic) # Note: This requires manual intervention or exchange-to-exchange APIs

For advanced automation strategies beyond arbitrage, see our guide on how to build a trading bot.

Triangular Arbitrage Bot Setup (Single-Exchange)

Triangular arbitrage exploits pricing inefficiencies between three trading pairs on the same exchange. No fund transfers required—all trades happen instantly on one platform.

Example opportunity:

  1. Buy BTC with USDT (BTC/USDT)
  2. Sell BTC for ETH (ETH/BTC)
  3. Sell ETH for USDT (ETH/USDT)

If the combined exchange rates offer a net gain, you’ve profited from a triangular arbitrage cycle.

Detection Algorithm

def find_triangular_arbitrage(exchange, base=’USDT’): “””Scan for triangular arbitrage opportunities on single exchange”””

markets = exchange.load_markets() opportunities = []

# Find all trading pairs involving base currency base_pairs = [m for m in markets if base in m]

for pair1 in base_pairs: # pair1 format: ‘BTC/USDT’ intermediate = pair1.split(‘/’)[0] # Extract ‘BTC’

# Find pairs where intermediate can trade to other assets for pair2 in markets: if intermediate in pair2 and base not in pair2: # pair2 format: ‘ETH/BTC’ target = pair2.replace(f’/{intermediate}’, ”).replace(intermediate, ”)

# Find pair to complete triangle back to base pair3 = f”{target}/{base}” if pair3 in markets: # We have a complete triangle: USDT → BTC → ETH → USDT opportunities.append({ ‘path’: [pair1, pair2, pair3], ‘intermediate’: intermediate, ‘target’: target })

return opportunities

def calculate_triangular_profit(exchange, opportunity, start_amount=10000): “””Calculate profit from triangular arbitrage cycle”””

path = opportunity[‘path’]

# Fetch current prices ticker1 = exchange.fetch_ticker(path[0]) # BTC/USDT ticker2 = exchange.fetch_ticker(path[1]) # ETH/BTC ticker3 = exchange.fetch_ticker(path[2]) # ETH/USDT

# Calculate cycle step1 = start_amount / ticker1[‘ask’] # USDT → BTC step2 = step1 / ticker2[‘ask’] # BTC → ETH step3 = step2 * ticker3[‘bid’] # ETH → USDT

# Account for fees (3 trades = 3x fees) fee_rate = 0.001 # 0.1% per trade final_amount = step3 (1 – fee_rate)*3

profit = final_amount – start_amount profit_percent = (profit / start_amount) * 100

return { ‘profit_usd’: profit, ‘profit_percent’: profit_percent, ‘executable’: profit_percent > 0.15 # Higher threshold (three trades = more fees) }

Triangular arbitrage advantages:

  • No cross-exchange transfers (zero withdrawal fees, no network delays)
  • Lower capital requirements (no need for pre-positioned balances)
  • Faster execution (all trades on same platform)

Disadvantages:

  • Fewer opportunities (exchange internal pricing is usually efficient)
  • Requires very low latency (opportunities disappear in 2-8 seconds)
  • Three trading fees instead of two

According to DeFiLlama data on DEX arbitrage (similar principles), triangular opportunities on major CEXs occur 4-9 times per day for major assets, versus 12-47 times for spatial arbitrage.

Statistical Arbitrage: Advanced Mean Reversion Strategy

Statistical arbitrage (stat arb) trades correlated assets when price relationships deviate from historical norms. Unlike pure arbitrage, this carries directional risk—you’re betting on convergence, not exploiting guaranteed price differences.

Example setup:

  • ETH and BTC typically maintain a 0.05-0.065 BTC/ETH ratio
  • When ratio drops to 0.048, buy ETH/sell BTC (bet on convergence)
  • When ratio rises to 0.068, sell ETH/buy BTC

import numpy as np import pandas as pd

def calculate_historical_ratio(exchange, pair1=’BTC/USDT’, pair2=’ETH/USDT’, days=30): “””Calculate historical price ratio between two assets”””

# Fetch historical data btc_ohlcv = exchange.fetch_ohlcv(pair1, ‘1h’, limit=days*24) eth_ohlcv = exchange.fetch_ohlcv(pair2, ‘1h’, limit=days*24)

# Convert to dataframes btc_df = pd.DataFrame(btc_ohlcv, columns=[‘timestamp’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’]) eth_df = pd.DataFrame(eth_ohlcv, columns=[‘timestamp’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’])

# Calculate ratio (ETH price / BTC price) ratio = eth_df[‘close’] / btc_df[‘close’]

return { ‘current_ratio’: ratio.iloc[-1], ‘mean_ratio’: ratio.mean(), ‘std_ratio’: ratio.std(), ‘z_score’: (ratio.iloc[-1] – ratio.mean()) / ratio.std() }

def detect_stat_arb_signal(ratio_data): “””Generate trading signals based on z-score thresholds”””

z_score = ratio_data[‘z_score’]

if z_score < -2.0: return { 'signal': 'BUY_ETH_SELL_BTC', 'reason': 'ETH undervalued vs BTC (z-score: {:.2f})'.format(z_score), 'confidence': 'high' if z_score < -2.5 else 'medium' } elif z_score > 2.0: return { ‘signal’: ‘SELL_ETH_BUY_BTC’, ‘reason’: ‘ETH overvalued vs BTC (z-score: {:.2f})’.format(z_score), ‘confidence’: ‘high’ if z_score > 2.5 else ‘medium’ } else: return {‘signal’: ‘HOLD’, ‘reason’: ‘Ratio within normal range’}

Critical statistical arbitrage considerations:

  1. Correlation breaks: Historically correlated assets can decouple during major market events (see March 2020 COVID crash). Always use stop losses.
  2. Position sizing: Never allocate more than 10-20% of capital to stat arb positions.
  3. Time horizon: Mean reversion can take hours to weeks. This isn’t pure arbitrage—it’s a convergence bet.

For traders interested in using advanced crypto indicators to complement arbitrage strategies, correlation analysis and z-score tracking are powerful tools.

Risk Management & Safety Systems

Arbitrage seems risk-free (“buy low, sell high simultaneously”) but several critical risks exist:

1. Execution Risk

Problem: Orders don’t fill simultaneously. You buy on Exchange A, but your sell order on Exchange B doesn’t execute. Now you’re holding a directional position.

Solutions:

  • Use market orders for guaranteed execution (accepts higher fees)
  • Implement immediate order cancellation if one leg fails
  • Set maximum execution time (if both orders don’t fill within 2 seconds, cancel)

def execute_arbitrage_with_safeguards(opportunity, timeout=2): “””Execute arbitrage with automatic rollback if both legs don’t complete”””

import threading

results = {‘buy_complete’: False, ‘sell_complete’: False}

def execute_buy(): try: buy_order = exchanges[opportunity[‘buy_exchange’]].create_market_buy_order(…) results[‘buy_complete’] = True except: results[‘buy_complete’] = False

def execute_sell(): try: sell_order = exchanges[opportunity[‘sell_exchange’]].create_market_sell_order(…) results[‘sell_complete’] = True except: results[‘sell_complete’] = False

# Execute both simultaneously buy_thread = threading.Thread(target=execute_buy) sell_thread = threading.Thread(target=execute_sell)

buy_thread.start() sell_thread.start()

buy_thread.join(timeout=timeout) sell_thread.join(timeout=timeout)

# Verify both completed if not (results[‘buy_complete’] and results[‘sell_complete’]): print(“⚠️ Execution incomplete—initiating rollback”) # Implement order cancellation and position flattening logic return False

return True

2. Exchange Risk

Problem: Exchange goes offline, freezes withdrawals, or gets hacked while you have funds locked in an arbitrage position.

Solutions:

  • Only use top-tier exchanges with strong security track records
  • Never hold more than 30% of capital on any single exchange
  • Maintain withdrawal addresses whitelisted on all exchanges
  • Monitor exchange health metrics (can detect downtime patterns)

According to CryptoCompare data, the average major exchange experiences 2-4 hours of downtime per year. During these windows, your arbitrage positions are frozen.

3. Regulatory & Compliance Risk

Problem: Tax authorities in many jurisdictions classify each arbitrage cycle as separate taxable events, creating complex reporting requirements.

Solutions:

  • Use crypto accounting software (see our best crypto tax software 2026 guide)
  • Maintain detailed trade logs (every execution, fees paid, profit/loss)
  • Consult tax professionals familiar with algorithmic trading
  • Consider entity structure (LLC, corporation) if trading significant volume

4. Liquidity Risk

Problem: Large orders move the market. A $100,000 arbitrage opportunity might only have $20,000 of actual liquidity at the quoted price.

Solutions:

  • Check order book depth before executing (fetch Level 2 market data)
  • Split large orders into smaller chunks (iceberg orders)
  • Set maximum position size relative to 24h volume (never exceed 2-5% of daily volume)

def check_liquidity(exchange, symbol, required_amount): “””Verify sufficient order book depth for large trades”””

order_book = exchange.fetch_order_book(symbol, limit=20)

# Calculate available liquidity at best prices asks = order_book[‘asks’] # [[price, amount], [price, amount], …]

total_liquidity = 0 average_price = 0

for price, amount in asks[:5]: # Check top 5 levels total_liquidity += amount average_price += price * amount

average_price /= total_liquidity if total_liquidity > 0 else 1

return { ‘sufficient’: total_liquidity >= required_amount, ‘available_liquidity’: total_liquidity, ‘average_execution_price’: average_price, ‘slippage_estimate’: (average_price – asks[0][0]) / asks[0][0] * 100 }

5. Latency Risk

Problem: Network delays cause you to execute on stale price data. By the time your order arrives, the spread is gone.

Solutions:

  • Deploy bots on VPS servers geographically close to exchange data centers
  • Use WebSocket connections (push data) instead of REST polling (pull data)
  • Implement price staleness checks (reject opportunities if price data is >500ms old)

Optimal server locations for major exchanges:

Exchange Primary Data Center Recommended VPS Location
Binance Tokyo, Japan AWS Tokyo (ap-northeast-1)
Coinbase Virginia, USA AWS Virginia (us-east-1)
Kraken London, UK AWS London (eu-west-2)
Bybit Singapore AWS Singapore (ap-southeast-1)

According to Kaiko’s latency benchmarks, bots running on co-located servers execute 6.7x faster than bots on residential internet connections.

Performance Monitoring & Optimization

Track these metrics to evaluate and improve your arbitrage bot:

Essential KPIs:

  1. Win rate: Percentage of profitable trades (target: >75%)
  2. Average profit per trade: Net USD profit after all fees (target: >$50 for $10k positions)
  3. Opportunities captured: % of detected opportunities successfully executed (target: >40%)
  4. Execution speed: Time from detection to order placement (target: <500ms)
  5. Maximum drawdown: Largest peak-to-trough decline (target: <10%)

class ArbitragePerformanceTracker: def __init__(self): self.trades = []

def log_trade(self, trade_data): “””Record trade execution and outcome””” self.trades.append({ ‘timestamp’: time.time(), ‘opportunity_spread’: trade_data[‘spread’], ‘net_profit_usd’: trade_data[‘profit’], ‘execution_time_ms’: trade_data[‘execution_time’], ‘success’: trade_data[‘success’] })

def calculate_metrics(self): “””Calculate performance statistics””” df = pd.DataFrame(self.trades)

if len(df) == 0: return None

return { ‘total_trades’: len(df), ‘win_rate’: (df[‘success’].sum() / len(df)) * 100, ‘total_profit’: df[‘net_profit_usd’].sum(), ‘avg_profit_per_trade’: df[‘net_profit_usd’].mean(), ‘best_trade’: df[‘net_profit_usd’].max(), ‘worst_trade’: df[‘net_profit_usd’].min(), ‘avg_execution_time_ms’: df[‘execution_time_ms’].mean(), }

def generate_report(self): “””Print performance summary””” metrics = self.calculate_metrics()

print(“\n📊 ARBITRAGE BOT PERFORMANCE REPORT”) print(“=”*50) print(f”Total Trades: {metrics[‘total_trades’]}”) print(f”Win Rate: {metrics[‘win_rate’]:.1f}%”) print(f”Total Profit: ${metrics[‘total_profit’]:.2f}”) print(f”Avg Profit/Trade: ${metrics[‘avg_profit_per_trade’]:.2f}”) print(f”Best Trade: ${metrics[‘best_trade’]:.2f}”) print(f”Worst Trade: ${metrics[‘worst_trade’]:.2f}”) print(f”Avg Execution: {metrics[‘avg_execution_time_ms’]:.0f}ms”)

Optimization techniques:

  1. Dynamic fee adjustment: Update fee calculations daily (exchanges change fee structures frequently)

Related Articles