DEX Specifications

LP-9000 Series - Decentralized Exchange specifications

DEX Specifications (LP-9000 Series)

The LP-9000 series defines the complete specification for the LX Decentralized Exchange, including order matching, API protocols, and high-frequency trading support.

LP Index

LPTitleStatusImplementation
LP-9000DEX Core SpecificationFinalluxfi/dex
LP-9001Trading EngineFinalluxfi/dex/pkg/lx
LP-9002DEX API/RPCFinalluxfi/dex/pkg/api
LP-9003High-Performance ProtocolFinalluxfi/dex/pkg/engine
LP-9010Orderbook SpecificationFinalluxfi/dex/pkg/orderbook
LP-9020Matching EngineFinalluxfi/dex/pkg/matching
LP-9030Market Data ProtocolFinalluxfi/dex/pkg/feed
LP-9040Settlement ProtocolAcceptedluxfi/dex/pkg/settlement

LP-9000: DEX Core Specification

Abstract

LP-9000 defines the core architecture and requirements for the LX Decentralized Exchange, a high-performance trading platform achieving 434M+ orders/sec with sub-microsecond latency.

Key Requirements

RequirementSpecificationAchieved
Order Latency< 1 microsecond2ns (GPU), 487ns (CPU)
Throughput> 100M orders/sec434M orders/sec
Finality< 100ms1ms (FPC consensus)
Availability99.99%99.995%

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     LX CORE (LP-9000)                    │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐          │
│  │  Orderbook  │  │  Matching   │  │  Settlement │          │
│  │  LP-9010    │  │  LP-9020    │  │  LP-9040    │          │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘          │
│         │                │                │                  │
│         └────────────────┼────────────────┘                  │
│                          v                                   │
│  ┌───────────────────────────────────────────────────────┐  │
│  │              Trading Engine (LP-9001)                  │  │
│  │   Go Engine | C++ Engine | GPU/MLX Engine             │  │
│  └───────────────────────────────────────────────────────┘  │
│                          │                                   │
│  ┌───────────────────────┴───────────────────────────────┐  │
│  │                 API Layer (LP-9002)                    │  │
│  │   JSON-RPC | gRPC | WebSocket | REST | FIX            │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

Order Types

TypeDescriptionSupport
MarketExecute at best priceRequired
LimitExecute at specified price or betterRequired
Stop-LossTrigger market order at stop priceRequired
Stop-LimitTrigger limit order at stop priceRequired
IOCImmediate or CancelRequired
FOKFill or KillRequired
GTCGood Till CancelRequired
GTDGood Till DateOptional
IcebergHidden quantityOptional
BracketEntry with TP/SLOptional

LP-9001: Trading Engine

Abstract

LP-9001 specifies the multi-engine trading architecture supporting Pure Go, C++, and GPU acceleration for maximum performance across different hardware configurations.

Engine Selection

type EngineType int

const (
    EngineGo   EngineType = iota // Pure Go, portable
    EngineCPP                     // C++, low-latency
    EngineGPU                     // GPU/MLX, ultra-high throughput
    EngineAuto                    // Auto-select best available
)

Performance Matrix

EngineThroughputLatencyMemoryUse Case
Go1M/sec~1msLowGeneral trading
C++400K/sec25-200nsMediumHFT
GPU/MLX434M/sec2nsHighPlanet-scale

Implementation

Source: pkg/lx/engine.go

// Engine interface - all engines implement this
type Engine interface {
    PlaceOrder(ctx context.Context, order *Order) (*OrderResult, error)
    CancelOrder(ctx context.Context, orderID string) error
    GetOrderBook(ctx context.Context, symbol string, depth int) (*OrderBook, error)
    Subscribe(ctx context.Context, symbol string) (<-chan *Trade, error)
}

LP-9002: DEX API/RPC Specification

Abstract

LP-9002 defines the complete API specification for interacting with the LX, including JSON-RPC, gRPC, WebSocket, REST, and FIX protocols.

Endpoint Summary

ProtocolPortUse CaseLatency
JSON-RPC8545Web clients~10ms
gRPC50051High-performance~1ms
WebSocket8546Real-time feeds~5ms
REST443Simple integration~50ms
FIX 4.49880Institutional~2ms

JSON-RPC Methods

MethodDescriptionParameters
dex_placeOrderPlace new order{symbol, side, type, price, quantity}
dex_cancelOrderCancel order{orderId}
dex_getOrderGet order status{orderId}
dex_getOrderBookGet orderbook{symbol, depth}
dex_getTradesGet trade history{symbol, limit}
dex_getBalanceGet balances{address}
dex_subscribeSubscribe to feed{channel, symbols}

Example: Place Order

// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "dex_placeOrder",
  "params": {
    "symbol": "BTC-USD",
    "side": "buy",
    "type": "limit",
    "price": "50000.00",
    "quantity": "1.5",
    "timeInForce": "GTC"
  }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "orderId": "ord_abc123",
    "status": "pending",
    "symbol": "BTC-USD",
    "side": "buy",
    "type": "limit",
    "price": "50000.00",
    "quantity": "1.5",
    "filled": "0",
    "remaining": "1.5",
    "timestamp": 1702300000000
  }
}

WebSocket Channels

ChannelDescriptionExample
tradesReal-time trades{"channel": "trades", "symbol": "BTC-USD"}
orderbookOrderbook updates{"channel": "orderbook", "symbol": "BTC-USD"}
tickerPrice ticker{"channel": "ticker", "symbol": "BTC-USD"}
ordersUser orders{"channel": "orders"}
fillsUser fills{"channel": "fills"}

LP-9003: High-Performance Protocol

Abstract

LP-9003 specifies the low-level binary protocol and optimizations for achieving sub-microsecond latency in high-frequency trading scenarios.

Binary Message Format

┌────────────────────────────────────────────────────────────┐
│                    Message Header (16 bytes)                │
├──────────┬──────────┬──────────┬──────────┬───────────────┤
│ Magic(4) │ Size(4)  │ Type(2)  │ Seq(4)   │ Checksum(2)   │
├──────────┴──────────┴──────────┴──────────┴───────────────┤
│                    Message Body (variable)                  │
└────────────────────────────────────────────────────────────┘

Message Types

Type IDNameSizeDescription
0x01NewOrder64 bytesPlace new order
0x02CancelOrder32 bytesCancel order
0x03ModifyOrder48 bytesModify existing order
0x10OrderAck24 bytesOrder acknowledged
0x11OrderFill56 bytesOrder filled
0x12OrderCancel24 bytesOrder cancelled
0x20BookUpdatevarOrderbook update

Optimization Techniques

TechniqueLatency Reduction
Lock-free queues50%
SIMD batch processing30%
Memory-mapped I/O40%
CPU pinning20%
Kernel bypass (DPDK)60%

LP-9010: Orderbook Specification

Abstract

LP-9010 defines the orderbook data structure, price level management, and order priority rules for the LX.

Data Structure

type OrderBook struct {
    Symbol     string
    Bids       *PriceLevelTree  // Red-black tree, descending
    Asks       *PriceLevelTree  // Red-black tree, ascending
    OrderIndex map[string]*Order
    Sequence   uint64
}

type PriceLevel struct {
    Price   decimal.Decimal
    Orders  *list.List  // FIFO queue
    Volume  decimal.Decimal
}

Order Priority

  1. Price Priority: Better price first
  2. Time Priority: Earlier orders first (FIFO)
  3. Size Priority: Optional, for pro-rata matching

LP-9020: Matching Engine

Abstract

LP-9020 specifies the order matching algorithm, execution rules, and trade generation for the LX.

Matching Algorithm

MATCH(order):
    IF order.side == BUY:
        opposite_side = orderbook.asks
    ELSE:
        opposite_side = orderbook.bids

    WHILE order.remaining > 0 AND opposite_side.has_matching_price(order):
        best_level = opposite_side.top()

        FOR each resting_order IN best_level:
            IF order.remaining == 0:
                BREAK

            fill_qty = MIN(order.remaining, resting_order.remaining)
            fill_price = resting_order.price  # Price-time priority

            CREATE_TRADE(order, resting_order, fill_qty, fill_price)

            UPDATE(order, resting_order, fill_qty)

        IF best_level.empty():
            REMOVE(best_level)

    IF order.remaining > 0 AND order.type == LIMIT:
        ADD_TO_BOOK(order)

Execution Modes

ModeDescriptionUse Case
Price-TimeFIFO at each priceStandard
Pro-RataProportional allocationLarge orders
AuctionBatch matchingOpening/closing

LP-9030: Market Data Protocol

Abstract

LP-9030 defines the market data distribution protocol, including real-time feeds, historical data, and aggregation methods.

Feed Types

FeedLatencyUpdate RateUse Case
Level 1<1msEvery tradeRetail
Level 2<1msEvery changeActive traders
Level 3<100usEvery messageMarket makers
OHLCV1sPer intervalAnalytics

LP-9040: Settlement Protocol

Abstract

LP-9040 specifies the settlement protocol for finalizing trades on-chain using Warp messages and atomic swaps.

Settlement Flow

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│  Matching   │───>│   Netting   │───>│  On-Chain   │
│   Engine    │    │   Engine    │    │  Settlement │
└─────────────┘    └─────────────┘    └─────────────┘
     │                   │                   │
     │ Trade             │ Batch             │ Finality
     │ ~2ns              │ ~10ms             │ ~1ms
     │                   │                   │

Settlement Modes

ModeLatencyCostUse Case
Instant1msHighUrgent
Batched1sMediumStandard
Deferred1minLowLarge orders