Technology Stack

Core Language
C++23 CMake 3.31+
Libraries
C++ Standard Library Boost Eigen (ML) WebSocket REST APIs
Performance Engine
Lock-Free Queues Low-Latency Events Memory Pools Custom Decimal Multi-Threaded
Hardware Acceleration
SIMD / AVX CUDA / OpenCL GPU Acceleration
Deployment
Shared-Library Plugins (DLL / .so) MSVC / GCC / Clang Windows & Linux

System Architecture

ttTrader is built around a modular, event-driven architecture. Each component communicates through a central event dispatcher using lock-free queues — enabling true parallelism without synchronization overhead. Run multiple algos simultaneously, each watching instruments from different exchanges at the same time. Process market data from Binance to generate execution signals on Bitfinex, or arbitrage across Bybit and OKX — the unified event pipeline makes cross-exchange strategies as natural as single-exchange ones.

Binance
Bybit
OKX
Kraken
Hyperliquid
+8 more
▼   ▼   ▼   ▼   ▼   ▼
Exchange Manager
Market Data Mgr
Order ManagerLive / Sim
WebSocket ServerFrontend API
▼   ▼   ▼   ▼
Event Dispatcher Lock-Free · Multi-Producer · Multi-Consumer
▼       ▼       ▼       ▼
Indicators47 native indicator plugins
EMA · MACD · RSI · ATR …
Algo #1Shared-Lib Plugin
Algo #2Shared-Lib Plugin
PlaybackRecord / Replay
Each algo compiles independently and comes in a separate shared library

Market Data Pipeline

Every tick, every order book update, every trade — captured, normalized, and delivered to your strategy through a zero-copy, lock-free pipeline.

Trades (Tick Data)

Every trade: price, size, timestamp, and taker direction (buy/sell aggressor). Cumulative Volume Delta (CVD) is tracked on every tick for volume-pressure analysis. Circular buffer stores 16,384 most recent trades.

Best Bid & Offer

Real-time BBO with price, size, spread tracking, and microsecond timestamps. 16,384-entry circular buffer for short-term microstructure analysis. Spread history maintained for real-time spread percentile calculations.

Order Book (L2)

Full depth-of-book: up to 20 price levels per side in live trading, 5 levels during playback. Each level carries price + aggregated size. Book pressure and imbalance metrics computable at every update.

Algorithm Development

Strategies are implemented as independent shared-library plugins (.dll on Windows, .so on Linux). Derive from algoFramework_c, override the callbacks you need, and compile. No boilerplate, no ceremony.

Override What You Need

→
onMarketdataTick()
Every trade with price, size, CVD, taker direction
→
onMarketdataBbo()
Best bid/ask with integrated spread tracking
→
onMarketdataBook()
Full order book snapshot — 20 levels per side
→
onFinalizedCandle()
Finalized candle delivery with configurable timeframes
→
onOrderFill()
Execution confirmation with price, size, fee breakdown
→
onTimer()
Periodic callbacks for heartbeat, polling, or scheduled logic
// Your strategy — minimal boilerplate class MyAlgo : protected algoFramework_c { protected: void onMarketdataTick( instrumentInfo_s* instr, singleTradeInfo_s* trade ) override { // CVD divergence check if (detectDivergence(instr)) { m_orderManager.orderCreateLimit( instr, EOID_BUY_OPEN_LONG, size, limit, userId, "CVD entry" ); } } };

Order & Risk Management

Order Types

Type Description
Market Execute immediately at best available price
Limit Resting order at specified price level
Stop-Market Trigger → market execution
Stop-Limit Trigger → limit order placement

TIF: GTC, FOK, IOC, GTD — all supported.

Risk Controls

Method Usage
Fixed Risk Absolute USD risk per trade
Percent / BPS Risk as % of account or basis points
Min Size × Multiplier Scaled to instrument liquidity
Stop-Loss Engine OHLC-based, indicator-based, or ATR-multiplier stops

Pyramiding: Multiple concurrent positions per instrument with independent risk tracking.

Indicators & Machine Learning

Built-in technical indicators plus the ability to integrate custom ML models.

Built-in Indicators

SMA, EMA, WMA, HMA
MACD (line, signal, histogram)
RSI (Wilder smoothing)
Bollinger Bands (middle/upper/lower/width)
ATR, Stochastic (%K/%D), ROC, OBV

47 candle-driven native indicators, each an independent shared-library plugin computed in decimal_t with zero allocation on the update path. Custom indicators developed on request against the documented V2 SDK.

ML & Advanced Analytics

→
Eigen Integration
Linear algebra, PCA, regression, Kalman filters for signal processing and regime detection — all header-only, zero runtime dependency.
→
Online Learning & Parameter Feedback
Strategies run online gradient descent or REINFORCE-style controllers that adapt parameters from live P&L feedback — algos adjust to new market conditions instead of failing. No cloud, no restarts.
→
Regime Detection
Built-in regime detectors classify volatility, trend quality, and session state — strategies gate every entry on their statistical edge.
→
Local LLM Integration
Connect to local LLM inference (llama.cpp) via IPC for regime classification and meta-decision making — no cloud dependency.
→
Neural Networks
Implement simple feed-forward NNs using Eigen matrices for pattern recognition on market microstructure features.

GPU Acceleration — CUDA & OpenCL

→
Deep Neural Networks
Train and run inference on large-scale NNs directly on GPU hardware for real-time market microstructure analysis.
→
Monte Carlo Simulations
Parallelize thousands of simulation paths for options pricing, risk analysis, and strategy stress-testing.
→
Portfolio Optimization
Solve large-scale portfolio allocation problems with GPU-accelerated linear algebra — orders-of-magnitude faster than CPU.
→
Real-Time Signal Processing
Offload compute-intensive signal transforms and filtering to GPU — keep your CPU free for order execution and event handling.

Integrate CUDA or OpenCL kernels directly into your algo plugin. No separate infrastructure needed — the framework handles data transfer and kernel launch.

Playback & Backtesting

Record live market data, then replay it through the exact same event pipeline your strategy uses in production. No separate backtesting framework — no discrepancies.

Binary Recording Format (.ttpb v3)

Compact, efficient binary format stores trades, BBO, order book snapshots (up to 5 levels), funding rate events, market stats, and an OHLC pre-roll section for indicator warm-up parity.

Replay at original speed, accelerated, or stepped — full control over the simulation timeline. Orders are answered by the built-in simulation venue, with per-exchange latency, depth-aware fills, and maker-tape execution (see below) for venue-realistic results.

Live Market → [.ttpb Record] → Disk

Disk → [Playback Engine] → Same Event Pipeline
                        → Your Algo (unchanged)
                        → Sim Venue fills orders

Simulated Execution Model

In simulation and playback mode, ttTrader itself is the venue: a dedicated sim order manager answers every create, cancel, and modify in-process — deterministically. An optional per-exchange simulation block makes the fills look like a real venue. Every field defaults off, so a plain config preserves the simple fill path exactly.

Venue-Like Latency

Per-exchange order and cancel latency with deterministic seeded jitter — a resting limit can still fill while its cancel is in flight, exactly like on a real venue. Latency is quantized to the sim tick for reproducible runs: identical config and seed produce identical fills.

Depth-Aware Fills

Market and crossing limit orders walk the published order book ladder — one execution per level, with partials and realistic VWAP. After the ladder ends, the remainder either fills at the last price or cancels (IOC-like), configurable per exchange.

Maker Tape Fills

Resting limits fill from printed taker volume at or through their price, with a configurable participation ratio. Your maker orders get filled only when real flow reaches them — queue position illusions included.

Measured Latency Profiles

Simulation can resolve latencies from your own live trading: the framework records every venue order round trip into a latency database, and the simulator takes the median of the freshest samples per instrument. Every live trading day makes the simulation more accurate — automatically. An active latency probe algo can supply profiles for venues you don't trade live yet.

Full Configuration Reference
The complete simulation block — latency, jitter, seed, depth-fill and book-exhaustion modes, maker fill ratio, and the measured-profile precedence — is documented in the ttTrader Manual. Market-data latency into your algos is intentionally not simulated: only the venue-side order lifecycle is modeled.

Production Hardening

Latest hardening pass: crash-safe durability, order-failure closure, self-healing market data, and a verified plugin ABI — the difference between a demo and something you leave running unattended with real money.

Crash-Safe Position Journaling

Positions are journaled with flush-before-snapshot ordering and atomic snapshot writes (write-then-rename, generation files with pruning). A degraded-storage state is surfaced to the dashboard and the risk gate — the system never trades blind on a bad disk.

Order Watchdog

Every create, cancel, and modify is acknowledged and resolved per venue; rejections surface as explicit failure events. Orders stuck in-flight beyond a configurable timeout are force-retired and reported — no order can silently disappear.

Self-Healing Order Books

Per-venue book sequence tracking detects gaps and stale frames; the adapter re-bootstraps from the venue's REST depth snapshot and resumes incrementals — the local book stays consistent even through feed hiccups.

Verified Plugin ABI

Every plugin DLL is validated at load with an ABI fingerprint over all boundary types and event ids — a stale or mismatched plugin is rejected at startup, never half-loaded. Core and plugins deploy as one unit, enforced.

Verification at Depth

100+ deterministic unit-test suites, per-adapter canned-frame parser tests, fuzz targets on parsers and journal replay, and a /W4 /WX warning-free build. Every exchange passes a certification suite before it trades.

Supervised, Observable Deployments

Health-check CLI mode, heartbeat logging, timestamped crash dumps with retention, and a build identity (git SHA + preset) stamped into every binary — deploy under any standard supervisor and know exactly what is running.

Shared Strategy Kernels

Battle-tested building blocks shared across every production algorithm — not per-strategy copies, but consolidated, tested kernels that enforce consistent risk behavior and protect capital automatically.

Adaptive Protection Engine

ATR/R-based stop placement with a monotone ratchet: stops only tighten, never loosen. Breakeven trigger moves the stop to entry + offset once price reaches N multiples of initial risk. Trailing stop follows peak R at a configurable fraction. Profit-lock floor guarantees a minimum realized gain once peak R exceeds the lock trigger — if price revisits the floor, the position exits with locked profit.

ParameterPurpose
stopAtrMultInitial stop distance in ATR multiples
breakevenTriggerRR-multiple to arm breakeven
trailFracFraction of peak R for trailing
profitLockTriggerRR-multiple to activate profit floor
profitLockFracGuaranteed fraction of peak profit

Account-Level Risk Guard

Session-wide circuit breakers that gate every entry across all strategies simultaneously. Daily-loss latch halts new entries when equity drops below a fraction of day-start balance. Daily trade cap limits total executions per session. Loss-streak freeze pauses trading after N consecutive losing trades for a configurable cooldown. Session flatten windows define pre-close dead zones where all positions are reduced and no new entries are accepted.

GuardBehavior
Daily loss latchNo new entries until next session
Daily trade capHard limit on fills per day
Loss-streak freezeTimed pause after N losers
Flatten windowReduce + block before session close
Weekly breakerCross-session drawdown halt

Fail-Closed Position Sizing

Every order size passes through a pipeline of hard caps before reaching the exchange. Notional cap limits USD exposure per trade. Contract cap bounds raw unit count. Participation cap prevents orders from exceeding a fraction of visible opposing depth. If any cap is violated or the venue grid reports stale BBO data, the sizer returns zero — no order is sent. Gross exposure and depth-aware headroom calculations prevent portfolio-level over-leverage.

→
Base × Multiplier Pipeline
Risk-derived base size scaled by signal confidence, then clamped
→
Venue Grid Validation
Cross-venue BBO sync with staleness tracking — dead feeds cannot contribute
→
Zero on Violation
Any cap breach or missing data returns size = 0, never a partial fill

Online Learning with Drift Freeze

In-process logistic regression models update via bounded SGD with Welford online standardization and L2 regularization — no Python bridge, no external services. A fast/slow EMA drift monitor tracks the ratio of recent loss to historical loss. When the ratio exceeds a threshold for N consecutive observations, the model freezes itself: predictions return neutral (0.5), preventing degraded signals from generating trades. Training continues while frozen so the model recovers autonomously when conditions normalize. Full state serializes to JSON for restart persistence.

HMM Regime Detection

A shared Hidden Markov Model forward filter classifies market state in real time — up to 4 regimes across 8 observation dimensions. Diagonal Gaussian emissions with online mean/variance learning from posterior responsibilities. EWMA transition matrix updates converge from uniform prior without a training corpus. Algos gate entries on regime: trade only when the current state matches your strategy's statistical edge. Per-algo specialized detectors layer volatility percentile classification, ADX confirmation, and hysteresis-based transitions on top of the shared HMM kernel.

One Kernel, Every Strategy
All shared kernels live in ttAlgoShared — every production algo links against the same tested implementation. No copy-paste divergence. Configuration is JSON-driven per algo instance, so the same protection engine behaves differently for a scalper vs. a swing strategy.

Exchange Integration

Each exchange implements a standardized protocol interface. Adding a new exchange means implementing exchangeProtocol.h — the rest of the framework doesn't change.

Exchange Data Execution Fee Note
Binance Trades, BBO, Book Market, Limit Standard maker/taker
Bybit Trades, BBO, Book Market, Limit Standard maker/taker
OKX Trades, BBO, Book Market, Limit Standard maker/taker
Bitfinex Trades, BBO, Book Market, Limit Standard maker/taker
Poloniex Trades, BBO, Book Market, Limit Standard maker/taker
Kraken Trades, BBO, Book Market, Limit Standard maker/taker
Bitstamp Trades, BBO, Book Market, Limit Standard maker/taker
Bitget Trades, BBO, Book Market, Limit Standard maker/taker
Hyperliquid Trades, BBO, Book Limit only Standard maker/taker
Paradex Trades, BBO, Book Market, Limit Standard maker/taker
Aster Trades, BBO, Book Market, Limit Standard maker/taker
Lighter DEX layer Reference Reference implementation
Phemex Trades, BBO, Book — Marketdata only
Interactive Brokers Trades, BBO (L1) Market, Limit, Stops IBKR commission schedule
dYdX Trades, BBO, Book Market, Limit Standard maker/taker
Aevo — Market, Limit Standard maker/taker

Crypto venues provide spot, perpetual, inverse, and vanilla futures where available; through Interactive Brokers, ttTrader also trades stocks, options, forex, and traditional futures on the same normalized pipeline. Capabilities vary per venue — Hyperliquid supports limit-only trading, Lighter is a reference DEX-layer implementation, Phemex is marketdata-only, and Aevo has no kline endpoint.

Deployment Flexibility

Local System

Run on your development machine or dedicated trading server. Full Windows and Linux support. Low barrier to entry for strategy development and testing.

AWS / Cloud

Deploy on EC2 instances in regions close to exchange data centers. Auto-scaling not needed — a single well-provisioned instance handles all strategies.

Collocated

For latency-sensitive strategies: deploy on bare metal in exchange colocation facilities. The lock-free architecture ensures predictable, minimum latency.