One Kernel, Every Strategy

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.

10+
Shared Kernel Classes
0
Heap Allocations in Hot Path
21
Production Algos Using Them
Fail-Closed by Default
Every kernel defaults to the safe outcome when misconfigured or starved of data. A sizing cap of zero rejects the order rather than inflating it. A stale feed suspends trading rather than trusting old quotes. A missing correlation sample blocks the entry. The system never trades blind.

Risk Kernel

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.

Configuration (algoKernelRiskLimits_s)

FieldTypeDefaultPurpose
decRiskPerTradePctdecimal_t0.01Per-trade risk fraction
decDailyBreakerPctdecimal_t0.03Daily circuit breaker threshold
decGrossCryptoMultipledecimal_t2.5Max crypto gross notional / equity
ui32GrossIbContractsuint32_t4Max IB open contracts
decPerAssetCapPctdecimal_t0.10Per-asset sleeve cap
decCorrelationCapdecimal_t0.60Pairwise EWMA correlation limit
decVolTargetDailyPctdecimal_t0.016Daily vol target for sizing

API Reference

MethodPurpose
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

Sizing Stack

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

FieldTypeDefaultPurpose
decProductCapdecimal_t1.5Hard cap on multiplier product
ui32MaxContractsuint32_tUINT32_MAXContract cap (sentinel = uncapped)
decMaxNotionalUsddecimal_tmaxNotional cap (sentinel = uncapped)
decMaxParticipationRatedecimal_t0Participation rate cap (0 = off)

algoSizerStack_c API

MethodPurpose
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.h

Header-only fail-closed helpers.

FunctionPurpose
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

Pipeline Flow

CalculatePositionSize() → base size
sizer.setBase(base, price)
sizer.multiply(regimeFactor)
sizer.multiply(confidenceFactor)
sizer.finalize(instrument)
  ├─ product cap clamp
  ├─ contract cap clamp
  ├─ notional cap clamp
  ├─ participation cap clamp
  └─ venue grid floor snap
result ≤ 0 ? → no order sent

Protection Policy

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.

Configuration (config_s)

FieldDefaultPurpose
decStopAtrMult1.6Initial stop distance in ATRs
decStopMinDistance0Absolute floor (0 = off)
decStopMaxBps0Cap in bps of entry (0 = uncapped)
decTpAtrMult2.2Target distance in ATRs
decBreakevenTriggerR0R-multiple to arm breakeven (0 = never)
decBreakevenOffsetR0Offset past entry in R
decTrailFrac0Trail distance in live ATRs (0 = off)
decTrailMinDistance0Absolute trail floor
decProfitLockTriggerR0Peak R to arm lock (0 = off)
decProfitLockFrac0.5Locked fraction of peak R

API Reference

MethodPurpose
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

Venue Protection

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.

Configuration (config_s)

FieldDefaultPurpose
fEnabledtrueMaster switch
decBufferBps5.0Distance behind internal stop
decAmendMinBps2.0Minimum amend delta
ui32AmendMinIntervalS2Amend throttle interval
ui32PlaceTimeoutS3Ack timeout → retry
fRequiredtrueNo protected stop → flatten

API Reference

MethodPurpose
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

Session Guard

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.

Configuration (algoSessionGuardConfig_s)

FieldDefaultPurpose
eModeDAILYCONTINUOUS skips time windows
ui32FlattenMinuteUtc1320 (22:00)Flatten deadline (0 = disabled)
ui32NoEntryMinutes30Pre-flatten entry block
ui32ReopenMinuteUtc0 (midnight)Venue reopen
ui32OpenQuietMinutes0Quiet window after reopen
ui32DailyMaxTrades0 (unlimited)Trade cap
decDailyMaxLossFraction0 (disabled)Loss latch fraction
ui32LossStreakTrades0 (disabled)Consecutive losses to freeze
ui32LossStreakFreezeMs300000Freeze duration

API Reference

MethodPurpose
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

Staleness Guard

Wall-clock-anchored quote-staleness watchdog. Returns PROCEED, LATCHED, or SUSPEND_ARMED. Includes per-instrument kill resolution and observed quote-cadence histogram.

Core Functions

FunctionPurpose
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

Quote Cadence (algoQuoteCadence_s)

MethodPurpose
observe(arrivalMs)Record quote arrival
ui32GapP99Ms()P99 inter-arrival gap

Cost Model

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.

Venue Latency Constants

ConstantValueVenue
ce_i32LatencyLighterMs300msLighter REST + signing path
ce_i32LatencyIbkrMs150msIB TWS order round trip
ce_i32LatencyDefaultMs50msCo-located crypto venues

Input Struct (algoCostInput_s)

FieldPurpose
decFeeMakerPerSideMaker fee fraction
decFeeTakerPerSideTaker fee fraction
decFeePerContractUsdPer-contract USD fee (IB)
decHalfSpreadBpsHalf quoted spread in bps
decLatencyDriftBpsVol-scaled latency drift
decMidPriceFor per-contract conversion
decContractSizeFor per-contract conversion

API Reference

MethodPurpose
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

Value Feedback

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.

Bounds (algoFeedbackBounds_s)

FieldDefaultPurpose
decKEdgeMin / Max1 / 5kEdge clamp range
decCaptureMin / Max0.2 / 1Capture fraction range
decPyramidMin / Max0.1 / 1Pyramid gate range
decMaxStep0.1Max adjustment per cycle
decReferenceEdgeBps5Reference edge for normalization

API Reference

MethodPurpose
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

Order Brackets & Helpers

Thin orchestration layers over algoOrderManager_c for placing protection brackets, managing per-leg user values, and preventing double-cancel bugs.

algoBracketOrders

Places stop-market + limit-target with per-leg user values, re-syncs sizes after partial fills, ratchets stops only when strictly tightening.

FunctionPurpose
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

algoOrderLegIds

Per-leg user-value scheme so findOrder can distinguish close, stop, target, and TP2 legs without collisions. Stride is 8.

ValueOffsetPurpose
CLOSE+0Flatten leg
STOP+8Resting native stop
TARGET+16Take-profit / graceful exit
TP2+24Second take-profit

algoCancelOrder

Cancels an order through the manager and nulls the caller's pointer. Prevents double-cancel and dangling-handle bugs.

FunctionPurpose
algoCancelOrder(algoOrderManager_c&, orderInfo_s*&)Cancel + null the handle
Lifecycle & Warmup
The support library also includes 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.