Battle-tested building blocks shared across every production algorithm — risk gating, position sizing,
protection geometry, session circuit breakers, cost modeling, and self-tuning parameter feedback.
All kernels live in ttAlgoShared: one tested implementation, JSON-configured per algo instance.
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. All financial math uses decimal_t. All hot paths
are allocation-free.
Pre-trade gate enforcing circuit breakers, funding window guards, gross exposure caps, per-asset sleeve limits,
EWMA pairwise correlation bounds, and vol-targeted fixed-fraction sizing. Route every entry order through
approve() before calling orderCreate.
algoKernelRiskLimits_s)| Field | Type | Default | Purpose |
|---|---|---|---|
decRiskPerTradePct | decimal_t | 0.01 | Per-trade risk fraction |
decDailyBreakerPct | decimal_t | 0.03 | Daily circuit breaker threshold |
decGrossCryptoMultiple | decimal_t | 2.5 | Max crypto gross notional / equity |
ui32GrossIbContracts | uint32_t | 4 | Max IB open contracts |
decPerAssetCapPct | decimal_t | 0.10 | Per-asset sleeve cap |
decCorrelationCap | decimal_t | 0.60 | Pairwise EWMA correlation limit |
decVolTargetDailyPct | decimal_t | 0.016 | Daily vol target for sizing |
| Method | Purpose |
|---|---|
init(limits) | Configure limits from struct |
approve(request, outSize, outReason) | Full pre-trade gate; reason string on rejection |
circuitBreakerTripped(equity, sodEquity) | Daily hard stop check |
inFundingWindow(minuteUtc) | Settlement no-entry guard |
grossCapBreached(gross, ibContracts, equity, isCrypto) | Exposure cap check |
perAssetCapBreached(existing, proposed, equity) | Sleeve cap check |
correlationCapBreached(assetA, assetB) | Pairwise correlation gate |
volScaledSize(request) | Fixed-fraction vol-targeted size |
updateCorrelation(assetA, assetB, sample) | EWMA correlation update |
Base-size multiplied by bounded regime/confidence multipliers, then clamped through contract, notional, and participation rate caps. Consolidates the pattern previously duplicated across MIRE, HUB, QIS, DELEV, and RANGE. A multiplier of 0 collapses to 0. Negative multipliers assert. Caps are fail-closed.
algoSizerStack_c Configuration| Field | Type | Default | Purpose |
|---|---|---|---|
decProductCap | decimal_t | 1.5 | Hard cap on multiplier product |
ui32MaxContracts | uint32_t | UINT32_MAX | Contract cap (sentinel = uncapped) |
decMaxNotionalUsd | decimal_t | max | Notional cap (sentinel = uncapped) |
decMaxParticipationRate | decimal_t | 0 | Participation rate cap (0 = off) |
algoSizerStack_c API| Method | Purpose |
|---|---|
configure(config_s) | Set caps |
reset() | Clear accumulator |
setBase(baseSize, referencePrice) | Validated base + price for notional |
setParticipationVolume(volume) | Volume for participation cap |
multiply(multiplier) | Chain regime/confidence/win-rate factors |
finalize(instrumentPtr) | Apply caps + venue grid snap |
product() | Raw accumulated product |
sizingGuards.hHeader-only fail-closed helpers.
| Function | Purpose |
|---|---|
contractSizeOrOne(contractSize) | Sentinel-safe multiplier; venues without contract size behave per-unit |
makeSizeOrZero(instrument, rawSize) | Grid snap or reject; sizes below venue minimum return 0, never inflated |
Pure-state TP/SL geometry with breakeven ratchet, trailing stop, and profit lock. Owns no order-manager coupling — computes prices only. Geometry expressed in ATR multiples and R units. Stop is monotone ratchet-only: tightens, never loosens. Replaced twelve-plus hand-rolled copies across algos.
config_s)| Field | Default | Purpose |
|---|---|---|
decStopAtrMult | 1.6 | Initial stop distance in ATRs |
decStopMinDistance | 0 | Absolute floor (0 = off) |
decStopMaxBps | 0 | Cap in bps of entry (0 = uncapped) |
decTpAtrMult | 2.2 | Target distance in ATRs |
decBreakevenTriggerR | 0 | R-multiple to arm breakeven (0 = never) |
decBreakevenOffsetR | 0 | Offset past entry in R |
decTrailFrac | 0 | Trail distance in live ATRs (0 = off) |
decTrailMinDistance | 0 | Absolute trail floor |
decProfitLockTriggerR | 0 | Peak R to arm lock (0 = off) |
decProfitLockFrac | 0.5 | Locked fraction of peak R |
| Method | Purpose |
|---|---|
configure(config_s) | Set geometry parameters |
reset(entry, isLong, initialAtr) | Arm for one position |
stopPrice(mark, liveAtr) | Monotone ratchet stop |
targetPrice() | Entry-latched take-profit |
initialRisk() | |entry - stop| |
profitLockFloor(mark) | Peak-R lock floor price |
breached(mark) | True once mark crosses lock floor |
isArmed() | Armed state |
peakR() | Best favorable excursion in R |
Resting venue-side stop as a safety net behind the algo's internal stop. Only fires when the process is not acting (crash, frozen feed). State machine: FLAT → PROTECTING → PROTECTED → AMENDING → CANCELING. Never widens after placement.
config_s)| Field | Default | Purpose |
|---|---|---|
fEnabled | true | Master switch |
decBufferBps | 5.0 | Distance behind internal stop |
decAmendMinBps | 2.0 | Minimum amend delta |
ui32AmendMinIntervalS | 2 | Amend throttle interval |
ui32PlaceTimeoutS | 3 | Ack timeout → retry |
fRequired | true | No protected stop → flatten |
| Method | Purpose |
|---|---|
configure(config_s) | Set parameters |
reconcile(...) | Keep venue stop in step; call on every fill and heartbeat |
beginClose(...) | Cancel before internal close |
onFlat(...) | Tear down when flat |
venueTrigger(internalStop, isLong) | Compute behind-internal trigger price |
Deterministic daily/continuous session guard consolidating eight near-identical private copies. Covers trade caps, net + gross daily-loss latches, loss-streak freeze, pre-flatten/dead-zone/open-quiet windows. All time inputs are explicit for testability.
algoSessionGuardConfig_s)| Field | Default | Purpose |
|---|---|---|
eMode | DAILY | CONTINUOUS skips time windows |
ui32FlattenMinuteUtc | 1320 (22:00) | Flatten deadline (0 = disabled) |
ui32NoEntryMinutes | 30 | Pre-flatten entry block |
ui32ReopenMinuteUtc | 0 (midnight) | Venue reopen |
ui32OpenQuietMinutes | 0 | Quiet window after reopen |
ui32DailyMaxTrades | 0 (unlimited) | Trade cap |
decDailyMaxLossFraction | 0 (disabled) | Loss latch fraction |
ui32LossStreakTrades | 0 (disabled) | Consecutive losses to freeze |
ui32LossStreakFreezeMs | 300000 | Freeze duration |
| Method | Purpose |
|---|---|
configure(config_s) | Set parameters |
reset() | Clear counters |
onEquitySnapshot(equity, nowMs) | Anchor day-start equity |
onTradeClosed(netResult, nowMs, equityFallback) | Update counters/latches |
canEnter(minuteUtc, nowMs) | False when any gate blocks |
shouldFlatten(minuteUtc) | True inside dead zone |
parseJsonConfig(params) | Read standard keys from JSON |
toJson() / fromJson() | State persistence |
sessionIndex(nowMs) | Advances on rollover |
Wall-clock-anchored quote-staleness watchdog. Returns PROCEED, LATCHED, or
SUSPEND_ARMED. Includes per-instrument kill resolution and observed quote-cadence histogram.
| Function | Purpose |
|---|---|
algoEvaluateStaleness(lastBboMs, suspendUntilMs, wallMs, killMs, suspendMs) | Core verdict decision |
algoResolveStalenessKillMs(fallback, instrumentOverride) | Per-instrument clamped kill timeout |
algoEvaluateCadenceConfig(cadence, killMs) | Warn when kill < p99 cadence |
algoQuoteCadence_s)| Method | Purpose |
|---|---|
observe(arrivalMs) | Record quote arrival |
ui32GapP99Ms() | P99 inter-arrival gap |
Round-trip execution cost model and strategy admission gate. Computes fees (notional-rate or per-contract), spread, latency drift, variance break-even hold time, and full admission check. All static methods — no instance state, no allocation.
| Constant | Value | Venue |
|---|---|---|
ce_i32LatencyLighterMs | 300ms | Lighter REST + signing path |
ce_i32LatencyIbkrMs | 150ms | IB TWS order round trip |
ce_i32LatencyDefaultMs | 50ms | Co-located crypto venues |
algoCostInput_s)| Field | Purpose |
|---|---|
decFeeMakerPerSide | Maker fee fraction |
decFeeTakerPerSide | Taker fee fraction |
decFeePerContractUsd | Per-contract USD fee (IB) |
decHalfSpreadBps | Half quoted spread in bps |
decLatencyDriftBps | Vol-scaled latency drift |
decMidPrice | For per-contract conversion |
decContractSize | For per-contract conversion |
| Method | Purpose |
|---|---|
venueLatencyMs(exchange) | Default RTT by venue name |
latencyDriftBps(latencyMs, volBpsPerSec) | Expected movement over latency |
feePerSideBps(input, isTaker) | Fee in bps per side |
roundTripBps(input, isTaker) | 2×fee + 2×spread + drift |
minHoldMs(rtBps, sigmaPerGridBps, gridMs) | Variance break-even hold time |
targetBps(rtBps, kEdge) | Required move to clear cost |
admit(input, sigma, gridMs, maxHoldMs, isTaker) | Full admission gate |
Realised-edge learner nudging kEdge, captureFrac, and pyramidGate toward observed outcomes. Bounded per-cycle step, clamped to configured bounds. Self-tunes strategy admission thresholds from closed-trade P&L without manual intervention.
algoFeedbackBounds_s)| Field | Default | Purpose |
|---|---|---|
decKEdgeMin / Max | 1 / 5 | kEdge clamp range |
decCaptureMin / Max | 0.2 / 1 | Capture fraction range |
decPyramidMin / Max | 0.1 / 1 | Pyramid gate range |
decMaxStep | 0.1 | Max adjustment per cycle |
decReferenceEdgeBps | 5 | Reference edge for normalization |
| Method | Purpose |
|---|---|
init(kEdge, captureFrac, pyramidGate, bounds, minTrades) | Configure |
recordTrade(netEdgeBps, isWin) | Feed one closed trade |
endSession() | Apply adjustment cycle |
kEdge() / captureFrac() / pyramidGate() | Current gate values |
hitRate() / meanEdgeBps() | Session statistics |
Thin orchestration layers over algoOrderManager_c for placing protection brackets,
managing per-leg user values, and preventing double-cancel bugs.
algoBracketOrdersPlaces stop-market + limit-target with per-leg user values, re-syncs sizes after partial fills, ratchets stops only when strictly tightening.
| Function | Purpose |
|---|---|
algoPlaceProtection(mgr, pos, closeId, stopPrice, targetPrice) | Place both legs |
algoPlaceProtectionTicks(mgr, pos, closeId, stopPrice, targetTicks) | Target as tick distance |
algoSyncProtectionSizes(mgr, pos, closeId) | Re-sync after partial fills |
algoRatchetStopTrigger(mgr, order, newTrigger) | Tighten-only modify |
algoOrderLegIdsPer-leg user-value scheme so findOrder can distinguish close, stop, target, and TP2 legs without collisions. Stride is 8.
| Value | Offset | Purpose |
|---|---|---|
CLOSE | +0 | Flatten leg |
STOP | +8 | Resting native stop |
TARGET | +16 | Take-profit / graceful exit |
TP2 | +24 | Second take-profit |
algoCancelOrderCancels an order through the manager and nulls the caller's pointer. Prevents double-cancel and dangling-handle bugs.
| Function | Purpose |
|---|---|
algoCancelOrder(algoOrderManager_c&, orderInfo_s*&) | Cancel + null the handle |
algoWarmupGate_s — a bitmask gate preventing an algo from acting
until dependent subsystems (HMM steps, history replay, book kinetics) are warm. Conditions: BOOK_KINETICS,
HMM_STEPS, HISTORY, CUSTOM. One-shot consumeOpen fires exactly
once on the closed-to-open transition. Combined with algoHistoryReplay which walks the newest contiguous
run of closed candles oldest-first so bar-driven algos rebuild state before the live stream resumes.