A comprehensive look at the architecture, design decisions, and capabilities that make ttTrader a production-grade trading framework.
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.
Every tick, every order book update, every trade — captured, normalized, and delivered to your strategy through a zero-copy, lock-free pipeline.
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.
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.
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.
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.
| 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.
| 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.
Built-in technical indicators plus the ability to integrate custom ML models.
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.
Integrate CUDA or OpenCL kernels directly into your algo plugin. No separate infrastructure needed — the framework handles data transfer and kernel launch.
Record live market data, then replay it through the exact same event pipeline your strategy uses in production. No separate backtesting framework — no discrepancies.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
| Parameter | Purpose |
|---|---|
stopAtrMult | Initial stop distance in ATR multiples |
breakevenTriggerR | R-multiple to arm breakeven |
trailFrac | Fraction of peak R for trailing |
profitLockTriggerR | R-multiple to activate profit floor |
profitLockFrac | Guaranteed fraction of peak profit |
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.
| Guard | Behavior |
|---|---|
| Daily loss latch | No new entries until next session |
| Daily trade cap | Hard limit on fills per day |
| Loss-streak freeze | Timed pause after N losers |
| Flatten window | Reduce + block before session close |
| Weekly breaker | Cross-session drawdown halt |
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.
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.
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.
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.
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.
Run on your development machine or dedicated trading server. Full Windows and Linux support. Low barrier to entry for strategy development and testing.
Deploy on EC2 instances in regions close to exchange data centers. Auto-scaling not needed — a single well-provisioned instance handles all strategies.
For latency-sensitive strategies: deploy on bare metal in exchange colocation facilities. The lock-free architecture ensures predictable, minimum latency.