# How CloddsBot's Cross-Platform Arbitrage Detection Works: A Technical Deep Dive

> Discover how CloddsBot detects cross-platform arbitrage by analyzing normalized price quotes from Solana and EVM DEXs. Learn about its fee and latency calculations for optimal profit.

- Repository: [AL/CloddsBot](https://github.com/alsk1992/CloddsBot)
- Tags: deep-dive
- Published: 2026-09-11

---

**CloddsBot detects cross-platform arbitrage opportunities by aggregating normalized price quotes from Solana and EVM DEXs, then executing a pair-wise analysis to calculate net profit margins after accounting for fees, latency, and inventory constraints.**

The open-source CloddsBot repository (`alsk1992/CloddsBot`) implements a high-performance arbitrage engine designed to identify price discrepancies across decentralized exchanges in real-time. This analysis examines the precise mechanisms, source file architecture, and algorithmic implementation used to discover profitable cross-chain trading opportunities.

## The Three-Stage Arbitrage Detection Pipeline

The cross-platform arbitrage detection system operates through a structured three-stage pipeline that transforms raw market data into ranked, actionable trading plans.

### Stage 1: Multi-Venue Quote Collection

The scanning process begins in [`src/trading/venue-arbitrage-scanner.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage-scanner.ts) through the `collectSolanaQuotes` and `collectEvmQuotes` functions. For each requested token pair (`baseToken/quoteToken`), the system contacts multiple on-chain venues simultaneously.

The scanner integrates with **Solana DEXs** including Jupiter, Raydium, Orca, Meteora, and PumpSwap, alongside **EVM DEXs** such as Uniswap, 1inch, PancakeSwap, and Lighter. Venue-specific adapter functions—`quoteJupiterVenue()`, `quoteRaydiumVenue()`, `quoteUniswapVenue()`, and their counterparts—fetch both buy and sell quotes while measuring network latency.

Each venue returns a `ScannedVenueQuote` object containing the raw price quote, venue identifier, pool address, routing path, and latency metadata. This standardized collection layer abstracts protocol-specific differences, enabling uniform downstream processing regardless of whether the source is a Solana AMM or an Ethereum DEX aggregator.

### Stage 2: Result Normalization and Deduplication

Once quotes are collected, the `finalizeVenueArbitrageScan()` function assembles them into a `VenueArbitrageScanResult` structure. This normalization stage performs several critical operations:

- **Deduplication**: Removes duplicate platform entries that may appear across different routing paths
- **Categorization**: Identifies and labels skipped venues (e.g., pools with insufficient liquidity or temporary RPC failures)
- **Price Sorting**: Orders quotes by price level to facilitate efficient pair-wise comparison in the next stage

The normalization process ensures that the arbitrage planner receives a clean, consistent dataset representing the current state of liquidity across all configured markets.

### Stage 3: Arbitrage Planning and Profit Ranking

The core intelligence resides in [`src/trading/venue-arbitrage.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage.ts), specifically within the `findVenueArbitragePlans()` function. This stage implements the actual cross-platform arbitrage detection logic through the following algorithmic steps:

1. **Grouping**: Aggregates quotes by `instrumentId` (the normalized token pair identifier)
2. **Pair-wise Evaluation**: Iterates through every possible buy-sell combination across venues using the `buildPlan()` function
3. **Profit Calculation**: Computes gross spread, then subtracts **transaction fees**, **latency penalties**, **stale-data penalties**, and **inventory penalties** to derive the **net edge (basis points)** and **expected net USD profit**
4. **Threshold Filtering**: Discards plans failing to meet `minNetEdgeBps`, `minTargetProfitUsd`, or other configured constraints
5. **Ranking**: The `rankPlans()` function orders viable opportunities by a composite score balancing edge magnitude, trade size, and expected profit

Plans that survive this filtering process represent genuine arbitrage opportunities with positive expected value after accounting for all execution costs and risks.

## Key Source Files and Architecture

The arbitrage detection system spans several critical files within the repository structure:

| File | Role |
|------|------|
| [`src/trading/venue-arbitrage-scanner.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage-scanner.ts) | Orchestrates quote collection, venue coordination, and high-level execution flow |
| [`src/trading/venue-arbitrage.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage.ts) | Implements core planning logic including `buildPlan()`, `findVenueArbitragePlans()`, and `rankPlans()` |
| [`src/types.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/types.ts) | Defines shared TypeScript interfaces such as `VenueQuote`, `VenueArbitragePlan`, and `VenueArbitrageLiveScanRequest` |
| `src/solana/*.ts` | Venue-specific adapters for Solana DEXs (Jupiter, Raydium, Orca, Meteora, PumpSwap) |
| `src/evm/*.ts` | Venue-specific adapters for EVM chains (Uniswap, 1inch, PancakeSwap, Lighter) |

This modular architecture allows developers to extend support for new DEXs by implementing additional venue adapters without modifying the core planning engine.

## Implementing Cross-Chain Arbitrage Scans

The `scanVenueArbitrage()` function provides the primary entry point for executing a complete arbitrage detection cycle. The following example demonstrates a cross-chain scan between USDC on Solana and USDC on Ethereum:

```typescript
import { scanVenueArbitrage } from './trading/venue-arbitrage-scanner';

// Cross-chain arbitrage: USDC (Solana) vs USDC (Ethereum)
const request = {
  family: 'cross' as const,
  chain: 'ethereum' as const,          // EVM chain to scan
  baseToken: 'USDC',
  quoteToken: 'USDC',
  quoteSize: 10_000,                   // USD amount to trade
  slippageBps: 5,
  minNetEdgeBps: 10,                   // Require at least 10 bps edge
  minTargetProfitUsd: 1,               // Require $1 net profit
  requireCrossedMarket: true,
  onlyDirectRoutes: false,
  limitPlans: 5,
};

(async () => {
  const result = await scanVenueArbitrage(request);
  console.log(result.plans);          // Array of ranked arbitrage plans
})();

```

The function returns a formatted result containing ranked plans ready for execution or UI presentation, calculating all fees and latency penalties against the requested trade size.

## Direct Planner Access for Unit Testing

For testing or custom implementations, developers can instantiate the planner directly using `createVenueArbitragePlanner()`:

```typescript
import { createVenueArbitragePlanner } from './trading/venue-arbitrage';

const planner = createVenueArbitragePlanner({
  minNetEdgeBps: 5,
  minTargetProfitUsd: 0.5,
});

const plans = planner.findPlans(scannedQuotes);
console.log(planner.rankPlans(plans));

```

This lower-level access allows fine-grained control over the arbitrage detection parameters and facilitates unit testing with mock quote data.

## Configuration Parameters and Risk Controls

The arbitrage engine implements sophisticated risk controls through configurable thresholds:

- **`minNetEdgeBps`**: Minimum acceptable profit margin in basis points after all costs
- **`minTargetProfitUsd`**: Absolute minimum profit in USD terms to avoid dust trades
- **`slippageBps`**: Expected execution slippage deducted from gross spreads
- **`requireCrossedMarket`**: Boolean enforcing that bid prices must exceed ask prices before fee consideration

These parameters work in conjunction with the penalty functions in `buildPlan()` to filter out opportunities where latency or MEV extraction would likely eliminate theoretical profits.

## Summary

- **CloddsBot's cross-platform arbitrage detection** aggregates real-time quotes from Solana DEXs (Jupiter, Raydium, Orca, Meteora, PumpSwap) and EVM DEXs (Uniswap, 1inch, PancakeSwap, Lighter) through venue-specific adapters in [`venue-arbitrage-scanner.ts`](https://github.com/alsk1992/CloddsBot/blob/main/venue-arbitrage-scanner.ts).
- The **three-stage pipeline** normalizes heterogeneous quote formats into `ScannedVenueQuote` objects, deduplicates venues, and applies pair-wise analysis to identify profitable buy-sell combinations.
- The **planning engine** in [`venue-arbitrage.ts`](https://github.com/alsk1992/CloddsBot/blob/main/venue-arbitrage.ts) calculates net profitability by subtracting fees, latency penalties, stale-data penalties, and inventory costs from gross spreads, ranking only those plans exceeding configured `minNetEdgeBps` and `minTargetProfitUsd` thresholds.
- **Implementation flexibility** allows both high-level scanning via `scanVenueArbitrage()` and low-level planner access via `createVenueArbitragePlanner()` for testing and customization.

## Frequently Asked Questions

### Which decentralized exchanges does CloddsBot support for arbitrage detection?

CloddsBot integrates with nine major DEXs across two blockchain ecosystems. On **Solana**, it supports Jupiter, Raydium, Orca, Meteora, and PumpSwap. On **EVM chains**, it supports Uniswap, 1inch, PancakeSwap, and Lighter. The modular adapter pattern in `src/solana/*.ts` and `src/evm/*.ts` allows straightforward extension for additional venues.

### How does CloddsBot calculate net profit margins for arbitrage opportunities?

The system calculates net profit through the `buildPlan()` function in [`src/trading/venue-arbitrage.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage.ts). Starting with the gross spread between buy and sell prices, it sequentially deducts **transaction fees**, **latency penalties** (based on measured RPC response times), **stale-data penalties** (for aged quotes), and **inventory penalties** (for imbalanced holdings). The result is expressed as **net edge in basis points** and **expected net USD profit**.

### What configuration thresholds control which arbitrage plans get executed?

Primary thresholds include `minNetEdgeBps` (minimum profit margin in basis points after costs) and `minTargetProfitUsd` (absolute dollar minimum). Additional controls like `slippageBps`, `requireCrossedMarket`, and `onlyDirectRoutes` filter plans based on execution risk and routing complexity. These parameters are passed to `scanVenueArbitrage()` or configured in the planner instance.

### Can the arbitrage planner be used independently of the full scanner?

Yes. Developers can import `createVenueArbitragePlanner` from [`src/trading/venue-arbitrage.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/venue-arbitrage.ts) to instantiate the planning engine directly without invoking the network-dependent quote collection phase. This is useful for **backtesting strategies** against historical quote data or **unit testing** specific arbitrage scenarios in isolation from live DEX APIs.