Lux Docs
Lux Skills Reference

Lux DEX (LX)

Ultra-High Performance Order Matching Engine

Overview

LX is an ultra-high performance Central Limit Order Book (CLOB) order matching engine with multi-backend acceleration (Go, C++, Rust, CUDA, MLX, FPGA). It is a standalone matching engine -- NOT an AMM. It integrates with luxfi/exchange for AMM routing but the core is a price-time priority CLOB with a full derivatives stack (perpetuals, margin, lending, vaults, clearing house).

The engine includes a pluggable gateway layer that aggregates liquidity from the native CLOB and external AMM providers (Uniswap V2/V3/V4, Lux AMM) across multiple chains, plus DAG-based consensus for multi-node orderbook synchronization.

Performance: 434M+ orders/sec (GPU/MLX), 2ns order latency (GPU), 487ns (CPU).

Quick Reference

ItemValue
Modulegithub.com/luxfi/dex
Go1.26.1
Binaryluxd (built to bin/luxd)
C++ Engineluxcpp/dex/ (CMake, C++17, -O3 -march=native -flto)
LicenseProprietary (Lux Industries Inc)
gRPC protoproto/lxdex.proto
ChainsLUX (96369), Zoo (200200), Ethereum (1), Arbitrum (42161), etc.

Architecture

                     +-----------------------------+
                     |  External Clients            |
                     |  FIX / REST / WS / gRPC / ZAP|
                     +------+----------------------+
                            |
              +-------------v------------------------+
              |         API Gateway (pkg/gateway)     |
              |  Router -> Registry -> Providers      |
              |  (Lux AMM, Uniswap V2/V3/V4, ...)    |
              +------+------------------+------------+
                     |                  |
          +----------v---------+  +----v-------------+
          |  CLOB Engine       |  |  AMM Providers    |
          |  (pkg/lx)          |  |  (pkg/gateway/)   |
          |  +------------+    |  |  lux/  uniswap/   |
          |  | OrderBook  |    |  +------------------+
          |  +------------+    |
          |  |ClearingHouse|   |
          |  +------------+    |
          |  | RiskEngine |    |
          |  +------------+    |
          |  |MarginEngine|    |
          |  +------------+    |
          |  |FundingEngine|   |
          |  +------------+    |
          |  |PriceOracle |    |
          |  +------------+    |
          +------+-------------+
                 |
    +------------v------------------------------------+
    |        Matching Backends (pkg/orderbook)        |
    |   +------+  +------+  +------+  +------+       |
    |   |  Go  |  | C++  |  | Rust |  | MLX  |       |
    |   | Pure |  | CGO  |  | FFI  |  | GPU  |       |
    |   +------+  +------+  +------+  +------+       |
    +----+----------------------------------------+---+
         |
    +----v--------------------------------------------+
    |     Infrastructure                              |
    |  DPDK/XDP   NATS   ZeroMQ   BadgerDB           |
    |  Consensus (DAG/Quasar/Ringtail)                |
    +-------------------------------------------------+

Matching Engines

EngineLanguagePerformanceBuild Tag
Pure GoGo830K orders/sec(default, CGO_ENABLED=0)
C++ (CGO)C++800K+ orders/seccpp (CGO_ENABLED=1)
RustRust585K+ orders/sec(ext/)
MLX GPUApple Metal434M+ orders/seccpp gpu mlx
CUDA GPUNVIDIA CUDA434M+ orders/seccpp gpu
FPGAAMD Alveo / AWS F2Sub-microsecondcgo fpga

Build Variants

make build-go           # Pure Go, CGO_ENABLED=0
make build-cpp          # C++ acceleration via CGO
make build-gpu          # GPU (MLX + CUDA), tags: cpp gpu mlx
make build-fpga         # Generic FPGA
make build-fpga-versal  # AMD Versal FPGA
make build-fpga-f2      # AWS F2 FPGA

Backend Auto-Detection

At init(), the engine detects the best available backend:

  1. CUDA_VISIBLE_DEVICES set -> BackendCUDA
  2. macOS arm64 + Metal.framework -> BackendMLX
  3. CGO_ENABLED=1 -> BackendCGO
  4. Default -> BackendGo

Order Types

Defined in pkg/lx/types.go:

TypeConstantDescription
LimitLimitPrice-time priority limit order
MarketMarketImmediate execution at best available
StopStopTriggers at stop price
Stop-LimitStopLimitTriggers at stop price, places limit
IcebergIcebergHidden size with display quantity, auto-refill
PegPegPegged to BBO with offset
BracketBracketOCO with take-profit and stop-loss
HiddenHiddenDark pool order, fully hidden

Order Flags

const (
    FlagPostOnly   OrderFlags = 1 << iota  // Reject if would take liquidity
    FlagReduceOnly                          // Only reduce existing position
    FlagImmediate                           // IOC semantics
    FlagHidden                              // Dark pool order
)
const OrderFlagSTP OrderFlags = 1 << 2     // Self-trade prevention

Time-in-Force

TIFDescription
TIF_GTCGood Till Cancelled
TIF_IOCImmediate Or Cancel (partial fills ok)
TIF_FOKFill Or Kill (all or nothing)
TIF_DAYDay order (expires end of session)

OrderBook Internals (pkg/lx/orderbook.go)

The CLOB uses:

  • Integer prices: PriceInt (int64, 8 decimal precision via PriceMultiplier = 100_000_000) for fast map lookups
  • B-tree price index: IntBTree with configurable degree (default 32) for sorted price traversal
  • Lock-free order map: sync.Map for concurrent order lookups alongside map[uint64]*Order for API compat
  • Linked list per level: OrderLinkedList for O(1) order insertion/removal at each price
  • Circular trade buffer: Fixed-capacity ring buffer (initial 1000) for trade history
  • Atomic counters: Lock-free trade ID, order ID, update ID, sequence generation
  • Cache-line padding: _padding [64]byte to prevent false sharing
  • Optimized price levels: OptimizedPriceLevel with atomic size/count counters

OrderTree

Each side (bids/asks) is an OrderTree:

type OrderTree struct {
    side        Side
    priceLevels map[PriceInt]*OptimizedPriceLevel  // Integer keys for fast lookup
    priceTree   *IntBTree                          // B-tree for sorted iteration
    orders      map[uint64]*Order
    bestPrice   atomic.Int64                       // Lock-free best price
}

Package Structure

pkg/lx/ - Core Trading Engine (71 files)

FilePurpose
types.goCore types: Order, Trade, TradingEngine, PriceLevel, OrderBookSnapshot
orderbook.goOptimized CLOB: OrderBook, OrderTree, IntBTree, CircularTradeBuffer
orderbook_advanced.goIceberg, hidden, peg, bracket, conditional orders
orderbook_extended.goExtended order book features
clearinghouse.goClearingHouse: perps margin, spot balances, multi-source oracle, funding
margin.goMarginEngine: cross/isolated/portfolio margin
risk_engine.goRiskEngine: pre-trade risk checks, VaR, exposure limits
liquidation.goLiquidationEngine: forced position closes, ADL
funding.go8-hour funding rate mechanism for perpetuals
lending.goLendingPool: borrow/supply with utilization-based rates
vaults.goVaultManager: yield vaults
vault_strategy.goStrategy implementations (Sharpe ratio, max drawdown, profit factor)
staking.goToken staking with reward distribution
oracle.goPriceOracle: multi-source weighted median, TWAP/VWAP
pyth_source.goPyth Network oracle adapter
chainlink_source.goChainlink oracle adapter
alpaca_source.goAlpaca Markets oracle adapter
bridge.goCross-chain bridge: multi-validator consensus, daily limits, nonce tracking
x_chain_integration.goLux X-Chain integration
multisig.goMultisig governance
compliance.goKYC/AML compliance checking
reconciliation.goBalance reconciliation
funds.goFund management
fpga_accelerator.goFPGA acceleration: parser/risk/match/encoder pipelines, DMA channels
market_config.goPer-market configuration

pkg/api/ - API Servers

FilePurpose
jsonrpc.goJSON-RPC 2.0 server with IP rate limiting (100 req/s/IP)
websocket_server.goReal-time WebSocket: auth, subscriptions, per-client rate limit
zap_server.goZAP binary protocol for HFT (zero-copy, cache-aligned wire format)

pkg/orderbook/ - Pluggable OrderBook Backends

FilePurpose
factory.goPure Go orderbook factory
factory_cgo.goCGO factory (routes to C++ when available)
cpp_orderbook.goC++ orderbook binding

pkg/consensus/ - DEX Consensus

DAG-based ordering with Quasar certificate consensus and Ringtail post-quantum engine. Security levels: 128, 192, 256 bits.

pkg/gateway/ - API Gateway

Multi-provider aggregation supporting external DEX routing:

FilePurpose
gateway.goMain gateway: register/unregister providers, start HTTP server
router.goParallel quote aggregation with fallback
registry.goProvider registry
provider.goProvider interface: QuoteProvider, LiquidityProvider, PriceProvider
types.goToken, SwapQuote, PoolHop, chain IDs
lux/Native Lux AMM provider
uniswap/Uniswap V2/V3/V4 provider

pkg/fpga/ - FPGA Acceleration

FilePurpose
fpga_engine.goFPGA matching engine core
fpga_interface.goHardware abstraction layer
amd_versal.goAMD Versal FPGA target
aws_f2.goAWS F2 FPGA target
stubs.goBuild stubs when FPGA not available

Supported cards: AMD Alveo U50 (8GB HBM, 100GbE), Alveo U55C (16GB HBM, 100GbE), Intel Agilex-7 (400GbE). Pipeline stages: Parser -> Risk -> Match -> Encoder with DMA channels and memory pools in BRAM/URAM/HBM.

Wire Protocols

ZAP Binary Protocol (pkg/api/zap_server.go)

Ultra-low-latency zero-copy binary protocol via luxfi/rpc:

MessageIDWire SizeDescription
PlaceOrder164 bytessymbol(8)+id(8)+price(8)+size(8)+side(1)+type(1)+flags(2)+ts(8)+user(16)+pad(4)
CancelOrder232 bytesorder_id(8)+user(16)+pad(8)
ModifyOrder3-In-place order modification
OrderAck824 bytesorder_id(8)+status(1)+seq(8)+pad(7)
Trade1048 bytesid(8)+price(8)+size(8)+buyer(8)+seller(8)+ts(8)
Quote-24 bytesprice(8)+size(8)+count(4)+pad(4)

All messages are cache-line aligned. Pre-allocated 4KB response buffers via sync.Pool.

gRPC Service (proto/lxdex.proto)

RPCStreamingDescription
PlaceOrderNoPlace order (limit/market/stop/iceberg/peg)
CancelOrderNoCancel by order ID
GetOrder / GetOrdersNoQuery orders
GetOrderBookNoSnapshot with configurable depth
StreamOrderBookServerReal-time incremental updates
GetTradesNoQuery executed trades
StreamTradesServerReal-time trade feed
GetBalanceNoAccount balance (available/locked/total)
GetPositionsNoOpen positions with PnL
GetNodeInfoNoNode version, block height, markets, uptime
GetPeersNoP2P peer list
PingNoHealth check

FIX Protocol

Standard Financial Information eXchange:

FIX MessageTagPurpose
NewOrderSingleDOrder submission
OrderCancelRequestFCancel request
ExecutionReport8Fill/cancel/reject notifications
MarketDataSnapshotWFull order book snapshot
MarketDataIncRefreshXIncremental book updates

WebSocket API

Real-time trading with per-client authentication, symbol subscriptions, and rate limiting. Integrates with TradingEngine, MarginEngine, LendingPool, PriceOracle, VaultManager, XChainIntegration, and LiquidationEngine.

JSON-RPC 2.0

Methods: orderbook.getBestBid, orderbook.getBestAsk, orderbook.getStats. Rate-limited to 100 req/s per IP.

ClearingHouse (pkg/lx/clearinghouse.go)

Manages perpetual margin state and spot balances:

  • Cross margin: Shared balance across all positions
  • Isolated margin: Per-position margin allocation
  • Multi-source oracles: Weighted median from Chainlink, Pyth, Alpaca
  • 8-hour funding: Standard intervals (00:00, 08:00, 16:00 UTC)
  • Per-account locks: Parallel processing with per-account RWMutex
  • FPGA acceleration flags: Optional FPGA for order processing and risk checks

Risk Engine (pkg/lx/risk_engine.go)

Pre-trade risk with VaR, max drawdown, concentration limits. Default max leverage: BTC-USDT/ETH-USDT 100x, BNB-USDT 50x, default 20x.

Bridge (pkg/lx/bridge.go)

Cross-chain asset bridging with multi-validator signatures, daily volume limits, nonce tracking, confirmation requirements, and expiry times. Status flow: Pending -> Validating -> Confirmed -> Executing -> Completed.

C++ Engine (luxcpp/dex/)

Standalone C++17 matching engine:

SourcePurpose
src/orderbook.cppCore CLOB
src/matching.cppMatching algorithm
src/engine.cppEngine orchestration
src/oracle.cppPrice oracle
src/book.cppBook management
src/pool.cppLiquidity pool
src/vault.cppVault operations
src/feed.cppMarket data feed
src/lx.cppMain entry point

Build: cmake -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build

SDKs

Multi-language SDKs in sdk/ and ext/:

LanguagePath
Gosdk/go/, sdk/lx-trading-go/
TypeScriptsdk/typescript/, sdk/lx-trading-ts/
Pythonsdk/python/, sdk/lx-trading-py/
Rustsdk/rust/, sdk/lx-trading-rust/
Csdk/c/, sdk/lx-trading-c/
C++sdk/cpp/, sdk/lx-trading-cpp/
Coresdk/lx-trading-core/

External integrations: Hummingbot market maker connector (ext/hummingbot/, ext/hummingbot-gateway/).

Key Dependencies (from go.mod)

PackageVersionPurpose
github.com/luxfi/accelv1.0.1GPU/FPGA acceleration
github.com/luxfi/czmq/v4v4.2.2ZeroMQ messaging (C binding)
github.com/luxfi/databasev1.2.15State storage
github.com/luxfi/gethv1.16.64Ethereum types
github.com/luxfi/logv1.2.5Structured logging
github.com/luxfi/rpcv1.0.0Zero-copy RPC (ZAP protocol)
github.com/luxfi/cryptov1.17.26Cryptographic primitives
github.com/luxfi/idsv1.2.5ID types (base58)
github.com/nats-io/nats.gov1.48.0NATS messaging
github.com/shopspring/decimalv1.4.0Decimal arithmetic
google.golang.org/grpcv1.79.1gRPC framework
github.com/gorilla/websocketv1.5.4WebSocket server

Build and Run

# Build
make build          # Build luxd + tools
make build-go       # Pure Go (CGO_ENABLED=0)
make build-cpp      # C++ acceleration (CGO_ENABLED=1, -tags cpp)
make build-gpu      # GPU/MLX (-tags "cpp gpu mlx")

# Test
make test           # Unit tests (pkg/lx, pkg/api)
make test-all       # Full test suite
make test-race      # With race detector
make bench          # Standard benchmarks (10s)
make bench-all      # Comprehensive benchmarks

# Run
make run            # Single node (port 8080)
make run-cluster    # 3-node cluster
make run-local      # Local network
make run-fpc        # FPC consensus network

# Docker
make docker-build   # Standard image
make docker-cuda    # CUDA-enabled image
make up / make down # Docker Compose

# CI/CD
make ci             # clean + fmt + vet + test + build
make verify-all     # deps + fmt + vet + lint + test-100 + bench
make prod           # clean + verify-all + build + docker-build
make proto          # Generate gRPC code from proto/
make sdk-all        # Build all language SDKs

EVM Precompile Integration

The DEX engine integrates with github.com/luxfi/exchange via precompiles:

PrecompileAddressPurpose
PoolManager0x0400AMM pool management
SwapRouter0x0401Swap routing (AMM + CLOB)
HooksRegistry0x0402Custom swap hooks
FlashLoan0x0403Flash loan facility
  • lux/lux-exchange.md -- AMM frontend (routes orders to DEX)
  • lux/lux-evm.md -- EVM with DEX precompiles
  • lux/lux-accel.md -- GPU/FPGA acceleration library
  • lux/lux-consensus.md -- Quasar consensus integration

On this page