← Back to Portfolio

Crypto Arbitrage Detection

FinTech

Real-time crypto arbitrage detection with advanced risk assessment and network visualization of 120+ pairs.

TypeScript React D3.js WebSocket Bellman-Ford

title: Crypto Arbitrage Detection slug: crypto-arbitrage-detection description: Real-time crypto arbitrage detection with advanced risk assessment and network visualization of 120+ pairs. featured: true hero: false status: Product published: published category: AI & Machine Learning technologies: - TypeScript - React - D3.js - WebSocket - Bellman-Ford date: 2025-01-15

Crypto Arbitrage Detection

Real-time cryptocurrency arbitrage detection system with parallel Bellman-Ford algorithm, Kelly Criterion position sizing, and multidimensional risk assessment.

Overview

A sophisticated arbitrage detection platform that monitors 120+ cryptocurrency trading pairs across multiple exchanges in real-time, identifying profitable triangular arbitrage opportunities while accounting for trading fees, slippage, and market depth.

The system uses graph-theory algorithms to detect negative-weight cycles in the exchange rate graph, representing opportunities where buying and selling across three pairs yields a profit. Advanced risk assessment across 7 dimensions ensures that only viable opportunities with acceptable risk profiles are surfaced to traders.

Architecture Overview

graph TB
    subgraph "Data Ingestion Layer"
        WS[WebSocket Feeds<br/>Multiple Exchanges]
        NORM[Data Normalizer<br/>Unified Format]
    end

    subgraph "Graph Processing"
        GRAPH[Exchange Rate Graph<br/>120+ Pairs]
        BF[Parallel Bellman-Ford<br/>Cycle Detection]
    end

    subgraph "Risk Engine"
        KELLY[Kelly Criterion<br/>Position Sizing]
        RISK[7D Risk Assessment<br/>Multidimensional]
    end

    subgraph "Frontend"
        VIZ[D3.js Network Graph<br/>Real-time Visualization]
        DASH[React Dashboard<br/>Opportunity Feed]
    end

    WS --> NORM
    NORM --> GRAPH
    GRAPH --> BF
    BF --> KELLY
    KELLY --> RISK
    RISK --> VIZ
    RISK --> DASH

    style BF fill:#4f46e5
    style RISK fill:#dc2626
    style VIZ fill:#059669

Core Components

1. Real-Time Data Pipeline

WebSocket Integration:

Exchange Rate Graph:

interface ExchangeRateGraph {
  nodes: Currency[];
  edges: TradingPair[];

  // Update edge weight with new price data
  updateEdge(pair: TradingPair, price: number): void;

  // Find all cycles starting from base currency
  findArbitrageCycles(base: Currency): ArbitrageOpportunity[];
}

2. Parallel Bellman-Ford Algorithm

Cycle Detection: The system implements a parallel version of the Bellman-Ford algorithm optimized for arbitrage detection:

function detectArbitrage(graph: ExchangeRateGraph): Cycle[] {
  // Convert prices to log-space for additive cycle detection
  const logGraph = graph.toLogSpace();

  // Run Bellman-Ford to detect negative cycles
  const cycles = parallelBellmanFord(logGraph, {
    maxCycles: 10,
    minProfit: 0.005, // 0.5% minimum after fees
    timeout: 100 // ms
  });

  return cycles.filter(cycle =>
    isViable(cycle) && hasLiquidity(cycle)
  );
}

Key Features:

3. Kelly Criterion Position Sizing

Optimal Capital Allocation:

interface KellyCalculator {
  // Calculate optimal position size
  calculatePosition(
    opportunity: ArbitrageOpportunity,
    capital: number,
    confidence: number
  ): PositionSize;

  // Fractional Kelly for risk management
  fractionalKelly: number; // 0.25 = quarter Kelly
}

// Example calculation
const position = kellyCalc.calculatePosition(
  {
    expectedReturn: 0.012,  // 1.2% profit
    winProbability: 0.85,   // 85% success rate
    maxLoss: 0.003          // 0.3% max loss
  },
  10000,  // $10k capital
  0.8     // 80% confidence
);
// Returns: $2,100 position size (21% of capital)

Features:

4. Multidimensional Risk Engine

7 Risk Dimensions:

  1. Execution Risk - Probability of all three legs executing at expected prices
  2. Liquidity Risk - Available volume at each step vs required size
  3. Slippage Risk - Expected price impact from trading
  4. Fee Risk - Total transaction costs including maker/taker fees
  5. Timing Risk - Latency between detection and execution
  6. Counterparty Risk - Exchange reliability and withdrawal limits
  7. Volatility Risk - Price movement during execution window
interface RiskAssessment {
  overall: RiskScore;      // Composite risk score 0-100
  dimensions: {
    execution: number;
    liquidity: number;
    slippage: number;
    fees: number;
    timing: number;
    counterparty: number;
    volatility: number;
  };
  recommendation: 'Execute' | 'Caution' | 'Avoid';
}

5. Network Visualization

D3.js Interactive Graph:

Visualization Features:

const visualization = {
  // Real-time updates
  updateRate: 60, // FPS

  // Visual encoding
  nodeSize: (node) => Math.log(node.volume24h),
  edgeColor: (edge) => profitColorScale(edge.spread),

  // Interaction
  onClick: (node) => showDetailPanel(node),
  onHover: (edge) => highlightCycle(edge)
};

Key Features

Triangular Arbitrage Detection

Example: BTC/USD → ETH/BTC → ETH/USD → Profit

1. Buy ETH with BTC at 0.065 BTC/ETH
2. Buy USD with ETH at $1,550/ETH
3. Buy BTC with USD at $24,000/BTC
4. Net: Started with 1 BTC, end with 1.012 BTC (1.2% profit)

Real-Time Monitoring

Risk-Adjusted Recommendations

Position Sizing Automation

Performance Metrics

Technical Stack

Backend Processing

{
  "language": "TypeScript",
  "runtime": "Node.js",
  "algorithms": ["Bellman-Ford", "Floyd-Warshall"],
  "optimization": "Parallel processing with worker threads"
}

Frontend Dashboard

{
  "framework": "React",
  "visualization": "D3.js",
  "state": "Redux",
  "websocket": "Socket.io client"
}

Data Layer

{
  "streaming": "WebSocket",
  "exchanges": ["Binance", "Coinbase", "Kraken", "Bybit", "OKX"],
  "caching": "Redis for order book snapshots"
}

Use Cases

1. Automated Trading

Connect to trading APIs for automatic execution of detected opportunities with configurable risk limits.

2. Market Research

Analyze exchange rate efficiency and identify persistent inefficiencies across different market conditions.

3. Risk Management

Use risk engine for portfolio analysis and exposure monitoring across multiple exchanges.

4. Education

Visualize arbitrage concepts and market microstructure with interactive network graphs.

Technical Highlights

Limitations & Considerations

Execution Challenges:

Market Conditions:

Technical Requirements:

Status

Production-ready arbitrage detection system with proven algorithm and comprehensive risk modeling. Successfully identifies profitable opportunities in real-time crypto markets.


Part of MacLeod Labs FinTech Portfolio