Trading Engine & Arbitrage System
Relevant source files
The following files were used as context for generating this wiki page:
- src/lib/trading-cache.ts
- src/lib/arbitrage-settings.ts
- src/app/api/arbitrage/polymarket-order/route.ts
- src/lib/orders/validation.ts
- src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx/event/[slug]/_components/EventOrderPanelForm.tsx)
- src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelArbitrage.tsx/event/[slug]/_components/EventOrderPanelArbitrage.tsx)
The Trading Engine & Arbitrage System provides the core logic for executing market and limit orders, validating user positions, and facilitating cross-platform arbitrage opportunities. It integrates directly with decentralized Central Limit Order Books (CLOBs) and leverages shared liquidity from external providers like Polymarket.
The system ensures that trades are validated against user balances and market states before execution, while the arbitrage module identifies and executes profitable price discrepancies between the local engine and external liquidity venues.
Order Lifecycle and Validation
The trading engine follows a strict validation pipeline before allowing a trade to be submitted to the order book. This includes checking user authentication, wallet connectivity, and sufficient liquidity.
Validation Logic
Orders are validated using the validateOrder function, which checks several constraints to prevent failed transactions.
| Constraint | Description | Source |
|---|---|---|
| Market Status | Checks if the market is active and accepting orders. | [src/lib/orders/validation.ts:47-51](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L47-L51) |
| Minimum Amount | Market buys must be at least $1. | [src/lib/orders/validation.ts:16-17](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L16-L17) |
| Limit Order Size | Limit orders require a minimum of 5 shares. | [src/lib/orders/validation.ts:15](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L15) |
| Balance Check | Verifies the user has enough USDC for the order and estimated fees. | [src/lib/orders/validation.ts:117-124](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L117-L124) |
| Share Availability | For sell orders, ensures the user holds the required tokens. | [src/lib/orders/validation.ts:109-115](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L109-L115) |
Order Execution Flow
The execution flow manages the transition from UI input to on-chain or relayer submission.
Citations: [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx:1065-1160](), [src/lib/orders/validation.ts:31-137](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L31-L137)
Arbitrage System Architecture
The arbitrage system identifies opportunities where the combined cost of "Yes" and "No" outcomes across two venues (the local platform and Polymarket) is less than the $1 payout.
Core Components
- Opportunity Detection: Calculates the "edge" (profit margin) by comparing local order book asks with external asks.
- Quote Scaling: Adjusts the arbitrage size based on the smaller of the two venue balances and available liquidity.
- Atomic-like Execution: Attempts to submit both orders simultaneously to minimize execution risk.
Arbitrage Execution Sequence
The following diagram illustrates the complex multi-step process of preparing and submitting an arbitrage trade across two different wallet sessions.
Citations: [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx:1435-1560](), [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelArbitrage.tsx:210-310]()
Arbitrage API Configuration
The system uses specific API routes to handle external order preparation and submission, ensuring compatibility with the Polymarket CLOB.
API Endpoint: /api/arbitrage/polymarket-order
This endpoint prepares order payloads for external venues.
| Parameter | Type | Description |
|---|---|---|
tokenId | String | The specific outcome token ID on the external venue. |
price | Number | The executable limit price. |
shares | Number | Quantity of shares to purchase. |
ownerAddress | Address | The user's wallet address on the external venue. |
Citations: [src/app/api/arbitrage/polymarket-order/route.ts](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/app/api/arbitrage/polymarket-order/route.ts)
Trading Cache Management
To maintain a responsive UI, the engine utilizes a sophisticated caching strategy that optimistically updates the interface before the blockchain confirms the transaction.
Invalidation Strategy
When a trade is successfully submitted, the system triggers targeted invalidations:
scheduleOrderBookRefresh: Triggers a background refresh of the order book summary.refreshTradingPositionsAfterMutation: Force-refetches user positions to reflect new balances.invalidateTradingClaimQueries: Clears caches related to claimable winnings.
Citations: [src/lib/trading-cache.ts:28-56](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/trading-cache.ts#L28-L56), [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx:1255-1270]()
Error Handling and Feedback
The engine maps low-level RPC or API errors into human-readable messages defined in the internationalization (i18n) files.
Common Error Mappings
MARKET_PAUSED: The market is not currently accepting orders.INSUFFICIENT_BALANCE: User lacks USDC for the trade.SLIPPAGE_WARNING: The expected fill price is >10% away from the best available price.
Citations: [src/lib/orders/validation.ts:140-160](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/orders/validation.ts#L140-L160), [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx:1020-1050]()
Summary
The Trading Engine & Arbitrage System acts as the primary interface between the user's strategic intent and the underlying decentralized liquidity. By combining rigorous validation with an automated arbitrage module, the system ensures both transaction safety and market efficiency across different prediction market protocols. Owners can configure arbitrage settings, such as multi-wallet support, via the arbitrage-settings module to customize the user experience.
Citations: [src/lib/arbitrage-settings.ts](https://github.com/kuest/prediction-market/blob/927a5c8fe56ae38a7e48ffea6be92b7f5e368d1a/src/lib/arbitrage-settings.ts), [src/app/[locale]/(platform)/event/[slug]/_components/EventOrderPanelForm.tsx:1350-1400]()