Arbitrage

From Oceantica Documentation
Arbitrage
Type
Trading Engine
Language
Rust
Status
Production Ready
Exchanges
Binance, Kraken, Coinbase, Deribit, Kucoin, Bybit
Runtime
Tokio async

Arbitrage is a high-performance, multi-exchange cryptocurrency arbitrage trading system built entirely in Rust. The system provides real-time monitoring, risk management, and automated execution capabilities for identifying and exploiting price discrepancies across multiple cryptocurrency exchanges.

Contents

Overview [edit]

The Arbitrage system continuously monitors price feeds across multiple exchanges and automatically identifies profitable trading opportunities. When a price discrepancy exceeds the configured threshold, the system can execute simultaneous buy and sell orders to capture the spread.

Key capabilities

Architecture [edit]

The system follows a modular architecture with clear separation of concerns:

src/
├── main.rs              # Application entry point
├── lib.rs               # Library interface (module exports)
├── config.rs            # Configuration management
├── arbitrage.rs         # Core arbitrage engine
├── data.rs              # Market data collection and normalization
├── exchange.rs          # Exchange API integrations
├── risk.rs              # Risk management and position sizing
├── execution.rs         # Trade execution engine
├── monitoring.rs        # Real-time monitoring and alerting
└── backtest.rs          # Backtesting framework

Component relationships

Component Responsibility Dependencies
ArbitrageEngine Main orchestrator for opportunity detection and execution All components
MarketDataManager Aggregates and normalizes price data from exchanges ExchangeManager
ExchangeManager Handles API connections to all supported exchanges Config
RiskManager Validates opportunities against risk parameters Config
ExecutionEngine Routes and executes arbitrage trades ExchangeManager, RiskManager
MonitoringSystem Tracks performance and sends alerts Config

Core components [edit]

ArbitrageEngine

The central orchestrator that coordinates all system components:

pub struct ArbitrageEngine {
    config: Config,
    market_data: Arc<MarketDataManager>,
    exchanges: Arc<ExchangeManager>,
    risk_manager: Arc<RiskManager>,
    execution_engine: Arc<ExecutionEngine>,
    monitoring: Arc<MonitoringSystem>,
    shutdown_tx: Option<mpsc::Sender<()>>,
}

ArbitrageOpportunity

Represents a detected arbitrage opportunity:

pub struct ArbitrageOpportunity {
    pub id: String,
    pub symbol: String,
    pub buy_exchange: String,
    pub sell_exchange: String,
    pub buy_price: Decimal,
    pub sell_price: Decimal,
    pub profit_margin: Decimal,
    pub max_volume: Decimal,
    pub timestamp: DateTime<Utc>,
}

Detection algorithm

The system continuously monitors price feeds and calculates arbitrage opportunities by:

  1. Maintaining a price cache for all symbols across exchanges
  2. Comparing prices between all exchange pairs
  3. Calculating effective prices including fees
  4. Filtering opportunities above minimum profit threshold
  5. Validating against risk parameters

Features [edit]

Backtesting framework

Real-time monitoring

Risk management

Position Sizing
Kelly Criterion-based optimal position sizing
Exposure Limits
Per-exchange and total exposure caps
Drawdown Protection
Automatic trading halt on excessive losses
Timeout Protection
Automatic position closure on execution delays
Slippage Controls
Maximum acceptable slippage thresholds

Configuration [edit]

The system uses TOML configuration files:

[trading]
min_profit_threshold = 0.01      # Minimum 1% profit
max_position_size = 1000.0       # Maximum position size
execution_timeout_seconds = 30

[risk_management]
max_total_exposure = 10000.0     # Maximum total exposure
stop_loss_threshold = 0.05       # 5% stop loss
max_slippage_tolerance = 0.01    # 1% slippage tolerance

[exchanges.binance]
name = "Binance"
api_endpoint = "https://api.binance.com"
fee_rate = 0.001

[exchanges.coinbase]
name = "Coinbase Pro"
api_endpoint = "https://api.pro.coinbase.com"
fee_rate = 0.0015

API reference [edit]

ArbitrageEngine methods

Method Description Signature
new Create new engine instance async fn new(config: Config) -> Result<Self>
start Start the arbitrage engine async fn start(&mut self) -> Result<()>
shutdown Gracefully shutdown async fn shutdown(&self) -> Result<()>

Data models [edit]

PriceUpdate

struct PriceUpdate {
    symbol: String,
    exchange: String,
    price: Decimal,
    timestamp: DateTime<Utc>,
}

BacktestResults

struct BacktestResults {
    performance: PerformanceMetrics,
    trades: Vec<Trade>,
    equity_curve: Vec<(DateTime<Utc>, Decimal)>,
}

struct PerformanceMetrics {
    total_return: f64,
    sharpe_ratio: f64,
    sortino_ratio: f64,
    max_drawdown: f64,
    win_rate: f64,
}

Usage [edit]

Installation

# Clone the repository
git clone <repository-url>
cd arbitrage

# Build the project
cargo build --release

# Configure
cp config.toml.example config.toml

# Run
cargo run --release

Basic example

use arbitrage::{Config, ArbitrageEngine};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load()?;
    let mut engine = ArbitrageEngine::new(config).await?;
    engine.start().await?;
    Ok(())
}

See also [edit]