Everything you need to build sophisticated trading strategies — market data callbacks, order lifecycle, position management, risk controls, timers, and ML integration.
.dll / .so).
Entry points: createPlugin(), destroyPlugin(),
getPluginConstInfo().
Your strategy derives from algoFramework_c and overrides only the callbacks you need.
The core engine handles exchange connectivity, market data normalization, and order routing —
your code stays clean, isolated, and focused on strategy logic.
The same plugin source builds on both platforms. On Windows the entry points are exported
with __declspec(dllexport) into a .dll; on Linux the identical
source compiles with GCC/Clang into a .so using visibility attributes —
no #ifdef changes in your strategy code.
Override any of these virtual methods in your derived class. The framework dispatches events from a lock-free pipeline — your callbacks receive pointers directly into the circular buffers. No copying, no allocation in the hot path.
onInitAlgo()Called once when the algo is loaded. Register positions, start timers, initialize state. Return from this and the algo goes live.
onExitAlgo()Graceful shutdown. Kill timers, cancel open orders (if
fCancelOpenOrdersOnExit is set), clean up resources.
onSetParams()Receives algo-specific JSON parameters from the config file. Hot-reloadable — called whenever params change.
onMarketdataTick()
Every trade. Receives instrumentInfo_s* and
singleTradeInfo_s*.
Fields: decPrice, decSize, decSizeCvd (cumulative volume
delta),
fTakerIsSell (aggressor direction), dtTimestamp.
onMarketdataBbo()
Best bid/offer update. Access via
instrumentPtr->marketdataInfo.bbo.back().
Fields: bid.decPrice, bid.decSize, ask.decPrice,
ask.decSize,
getMid(), integrated spread tracking.
onMarketdataBook()
Order book snapshot. Up to MARKET_DATA_BOOK_SIZE (20) levels per
side.
bid[0..19] and ask[0..19] with singlePriceSize_s (price +
aggregated size).
onFinalizedCandle()
Fires when a candle is finalized. Receives instrumentInfo_s*,
ohlcInfo_s*, and the finalized candle_s — indicators are already
updated at this point. Configurable timeframes per instrument via the config file.
onInstrumentNew()
A new instrument was registered for this algo. Inspect runtimeInfo for symbol,
base/quote currency, instrument type (future, perpetual, spot, option), min/max size, leverage
limits, fees.
onInstrumentHistoricalOk()Historical OHLC data has been loaded and is ready. Start indicator calculations or run initial analysis before trading begins.
onOrderCreated()Order has been accepted by the system and is being routed to the exchange. The
orderInfo_s is now live.
onOrderFill()
Execution! Receives executionInfo_s* with decPrice,
decSize, decFee, strFeeCur, and a link back to the
originating order and position.
onOrderUpdate()Order state changed: partial fill, modification confirmed, stop triggered.
Inspect infoState.eState and eProcessingState.
onOrderCanceled()Order was successfully cancelled. Clean up any tracking state.
onOrderFailed()Order was rejected or failed. Check infoState.eErrorState and
strInfo for the reason.
onPositionRegister()A new position was registered for your algo. Track it via the position manager.
onAssetUpdate()Account balance or asset value changed. Monitor equity, available margin, and P&L in real-time.
The algoOrderManager_c (accessible as m_orderManager) handles the full order
lifecycle.
No raw exchange API calls — use the manager and it routes correctly whether you're live, simulating, or
replaying.
| Enum | Type | Description |
|---|---|---|
EOIT_MARKET |
Market | Execute immediately at best available price |
EOIT_LIMIT |
Limit | Resting order at a specified price level |
EOIT_STOP_MARKET |
Stop-Market | Price trigger → market execution |
EOIT_STOP_LIMIT |
Stop-Limit | Price trigger → limit order placement |
| Enum | Meaning |
|---|---|
EOID_BUY_OPEN_LONG |
Buy to open a long position |
EOID_SELL_CLOSE_LONG |
Sell to close a long position |
EOID_SELL_OPEN_SHORT |
Sell to open a short position |
EOID_BUY_CLOSE_SHORT |
Buy to close a short position |
EOID_BUY / EOID_SELL |
Generic buy/sell (direction only) |
| TIF | Behavior |
|---|---|
ETIF_GTC |
Good-Till-Cancelled — rests until filled or cancelled |
ETIF_FOK |
Fill-Or-Kill — all or nothing, immediately |
ETIF_IOC |
Immediate-Or-Cancel — fill what you can, cancel the rest |
ETIF_GTD |
Good-Till-Date — active until dtGTD timestamp |
Orders can be linked via orderInfo_s::sync() with sync types like
EOST_CANCEL (cancel the other when this fills) or EOST_REDUCE
(reduce the other's size). This enables OCO (One-Cancels-Other) pairs and bracket orders.
Additional flags: fPostOnly (maker-only orders),
fEnableExtTradingHours,
i32Leverage (set leverage per order).
EOS_IDLE → EOS_ACTIVE →
EOS_COMPLETED
(or EOS_FAILED / EOS_CANCELED). The processing state
(EOPS_ALGO_CREATE → EOPS_MANAGER_CREATE → EOPS_EXCHG_CREATE)
lets you trace exactly where in the pipeline your order is. Location tracking
(EOL_LOCAL / EOL_BROKER / EOL_EXCHANGE) confirms
whether the exchange has acknowledged it.
The algoPositionManager_c (m_positionManager) tracks every position.
Positions are instrument-specific and direction-aware (long/short tracked independently).
Each positionInfo_s contains two independent value trackers:
pvLong and pvShort. Each tracks:
| Field | Description |
|---|---|
decSize |
Total position size |
decValue |
Total notional value |
decAvgPrice |
Volume-weighted average entry price |
decFee |
Total fees paid |
stExecutionCount |
Number of fills |
The framework fully supports pyramiding — multiple concurrent positions on the same
instrument. Each position has a unique ui64User identifier. The position
manager's findPosition() method lets you query by instrument, user value,
or direction.
Use the algoClosePositionManager_c (m_closePositionManager) to
close positions with market orders, limit orders, or stop-market triggers — each with
independent user values for tracking.
The algoTimerManager_c (m_timerManager) provides three timer types
for scheduling recurring logic, one-shot actions, and time-based alerts.
timerStart()
Recurring timer. timerStart(intervalMs, timerId, userPtr).
Fires onTimer(timerId, userPtr) every intervalMs milliseconds.
Use for periodic health checks, polling, or scheduled rebalancing.
timerFireOnce()
One-shot timer. Fires exactly once after the specified delay.
Callback: onTimerFireOnce(timerId, userPtr).
Use for delayed actions like order timeout handling.
timerAlert()
Alert timer. Fires at a specific wall-clock time.
Callback: onTimerAlert(timerId, userPtr).
Use for session-open/close actions or scheduled events.
instrumentInfo_s* as the user pointer to get context in the callback.
Kill all timers in onExitAlgo() with m_timerManager.timerKillAll().
Timer IDs are arbitrary int32_t values — use an enum to keep them organized.
algoRiskCalculator_c (m_riskCalculator) — configured via JSON:
| Risk Type | JSON Key | Calculation |
|---|---|---|
| Fixed | "FIXED" |
Absolute USD value per trade |
| Percent | "PERCENT" |
% of account equity |
| Basis Points | "BPS" |
BPS of account ÷ 100 |
| Min Size × Factor | "MIN" |
Min market size × multiplier |
Methods: getRiskFixedSize(), getRiskPercent(),
getRiskMinSize().
Each takes an instrumentInfo_s* for instrument-specific calculations.
algoStopLossCalculator_c (m_stopLossCalculator):
| Method | Configuration |
|---|---|
| OHLC-based | Stop at a specific OHLC bar's high/low |
| Indicator-based | Stop at an indicator value (e.g., ATR × N) |
| Multiplier | setStopLossMultiplier() — scale the stop distance |
| Max BPS Cap | setMaxStopLossBPS() — hard limit in basis points |
Order types for stops: EOTSL_MARKET (trigger → market) or EOTSL_BBO
(trigger → limit at current BBO). Use setStopLossOrderType() to choose.
Every instrument exposes runtimeInfo.mmsSize (min/max/step) and
runtimeInfo.mmsLeverage (min/max/step for derivatives).
Use getMinOrderSize(), getMaxOrderSize(), and
makeSize() to ensure your order sizes are exchange-valid.
Each instrument carries runtimeInfo.decFeeMaker and decFeeTaker.
These are exchange-specific and automatically applied to fills. Your strategy can query
them to decide whether to use limit orders (maker) or market orders (taker).
Bitfinex and Poloniex report competitive fees.
All ttTrader strategies link against the shared ttAlgoShared static library — a comprehensive collection of production-tested ML components, statistical primitives, and regime detectors. Every algo gains immediate access to online logistic regression, ensemble methods, contextual bandits, HMMs, conformal prediction, and deterministic offline training. Built for C++ with decimal_t end-to-end, fixed-capacity allocation, and zero heap traffic in update paths.
algoOnlineLogistic_cDecimal online logistic regression: Welford standardization, bounded SGD, L2 regularization, weight clipping. Up to 32 features. Optional drift-freeze monitor (fast/slow loss-EMA latch) and win-rate EMA tracker. JSON-serializable for restart persistence.
algoOnlineLogisticEnsemble_cBagged ensemble of online logistic kernels. Each member trains on a deterministic subsample (splitmix64 hash). Serves member predictions' mean and population std as uncertainty readout: disagreement approximates prediction confidence without a held-out set.
algoLinUcbBandit_cDisjoint LinUCB contextual bandit. One independent ridge model per arm. Selection maximizes theta_a' x + alpha * sqrt( x' A_a^-1 x ). Caller decides which arm acts and trains it through update() — usable as shadow policy or served one. Feature counts stay small (<= 16).
algoHmm_cOnline hidden Markov forward filter. Up to 4 states, 8 observation dimensions. Diagonal Gaussian emissions learned online from posterior responsibilities. EWMA transition matrix updates converge from uniform prior — no training corpus needed.
conformalGate_cSplit/Mondrian conformal abstention gate. Per-bucket residual rings calibrate a quantile. Entry admitted only when finite-sample lower bound on edge clears round-trip cost. Fixed double[6][400] rings.
changePoint_cBayesian online change-point detection (BOCPD). Run-length posterior over Normal predictive model with constant hazard. Truncated at 600 run lengths. Fixed double[600] arrays.
valueHead_cRecursive least squares with ridge regularization and exponential forgetting. Up to 32 features. Fixed double[32] + double[32×32].
tailIndex_cExtreme-value fragility via peaks-over-threshold. Hill tail index, GPD scale, expected shortfall ES_99, z-scored fragility score against slow EWMA baseline. Fixed double[1800] ring.
algoPromotionPolicy_cEvidence gate every learned layer passes before acting. Considers realized edge of executed action and whether challenger's suggestion agreed. Returns verdict: COLD, INSUFFICIENT_EVIDENCE, HOLD, PROMOTE, DEMOTE. Measures performance over N labelled outcomes.
double used only inside numerical solvers (eigensolver, BOCPD, path signatures) where explicitly documented; values convert back to decimal_t at API boundary.std::array, constexpr arrays) or allocated once via st_malloc in a configure() call.No hardcoded instruments. No hardcoded parameters. Everything is controlled by a single JSON configuration file passed via the command line.
Launch with: ttTrader.exe config.json. The config defines:
Exchange API keys are never stored in the main config. They reside in a separate, protected credentials store managed by the exchange subsystem. The config only references which exchange profile to use — the keys themselves are loaded securely at runtime.
Each exchange connection supports independent API credentials, rate limit tracking, and automatic reconnection with configurable backoff.
storeInstrument_c singleton holds all
instruments from all configured exchanges. Your algo receives them via
onInstrumentNew().
You can filter by instrument type (perpetual, future, spot, option), base/quote currency,
or any runtime property. Add a new instrument to the config, restart — no recompilation needed.
We don't just provide the framework — we build on it for you. Our team implements custom trading algorithms on request, analyzes existing strategies, and provides technical support through development and deployment. Describe your requirements and request a quote.
Full-cycle algo development on request: from idea to production. We implement, backtest, and optimize strategies based on your specification — or build them from scratch. Every strategy ships as a native C++ shared-library plugin (.dll / .so) with deterministic test coverage.
We review existing strategies for correctness, latency characteristics, and risk behavior: playback-based verification against recorded market data, code review against the framework SDK, and concrete recommendations before anything goes live.
Hands-on support during development and deployment: architecture walkthroughs, code reviews, colocation and latency tuning, and go-live assistance. Post-deployment monitoring and strategy adjustments included in support agreements.