SkillAgentSearch skills...

LLMTokenStreamQuantEngine

A low-latency, C++-based simulation engine that ingests token streams from an LLM in real-time, maps semantic token meaning to trade signals, and triggers micro-adjustments to a trading algorithm on a fractional-time (sub-second) scale.

Install / Use

/learn @Mattbusel/LLMTokenStreamQuantEngine
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

LLMTokenStreamQuantEngine

License: MIT C++20 Version Tests Dictionary Download

Windows users: grab the pre-built .exe from the v1.1.0 release — extract, edit config.yaml, and run. No build tools required.

A production-grade C++20 engine that ingests a live LLM token stream, maps each token to a quantitative semantic weight, accumulates directional bias and volatility signals with exponential decay, and fires risk-gated trade signals. The end-to-end token-to-signal P99 latency targets sub-10 microseconds in the hot path with zero managed I/O dependencies. As of v1.3.0 the engine also self-learns optimal token weights from labelled trade outcomes via Naive Bayes and correlates signals across multiple assets simultaneously through a rolling Pearson correlation matrix, enabling conviction amplification when correlated assets align and automatic hedge-ratio computation for pairs trading.


Round 7: Regime-Adaptive Position Sizer

Header: include/regime_sizer.hpp | Source: src/regime_sizer.cpp

Classifies the current market regime from LLM-derived sentiment features and maps each regime to a position-size fraction of account equity.

Data Structures

| Type | Description | |------|-------------| | MarketRegime | TRENDING_BULL, TRENDING_BEAR, MEAN_REVERTING, HIGH_VOL, LOW_VOL, UNKNOWN | | RegimeFeatures | avg_sentiment, sentiment_vol, cross_asset_correlation, alpha_decay_rate | | SizingConfig | base_size: double, regime_multipliers: map<MarketRegime, double> | | PositionSize | shares_or_contracts, notional_usd, risk_usd, regime, confidence |

Classes

| Class | Role | |-------|------| | RegimeClassifier | Priority-ordered decision tree: HIGH_VOL (sentiment_vol>0.4) → TRENDING (corr>0.7) → MEAN_REVERTING (corr<0.3) → LOW_VOL / UNKNOWN | | PositionSizer | size(regime, confidence, equity, price) -> PositionSize; notional = equity × base_size × regime_mult × confidence |

Tests: tests/unit/test_regime_sizer.cpp — 25 GTest cases.


Round 6: Signal Combiner

Header: include/signal_combiner.hpp | Source: src/signal_combiner.cpp

Combines multiple named trading signals (sentiment, alpha decay, execution timing) into a single actionable composite signal using three selectable combination methods.

Data Structures

| Type | Description | |------|-------------| | SignalInput | name: string, value: double [-1,1], confidence: double [0,1], timestamp_ms: int64_t | | CombinedSignal | action: double [-1,1], confidence: double, contributing_signals: vector<string>, regime: SignalRegime | | SignalRegime | TRENDING (|action|>0.4), MEAN_REVERTING (|action|<0.15), UNCERTAIN |

Combination Methods

| Method | Formula | |--------|---------| | WeightedAverage | action = Σ(c_i * v_i) / Σc_i where c_i = confidence_i | | Majority | action = (bull_conf - bear_conf) / (bull_conf + bear_conf) | | Ensemble | Kalman-style: K = c/(c+u), x = x + K*(v-x) per signal |

SignalHistory Ring Buffer

Fixed-capacity ring buffer of past CombinedSignals with:

  • trend_direction() — returns +1/−1/0 from mean of recent action values
  • volatility() — standard deviation of recent action values

Feature flag: LLMQUANT_ENABLE_SIGNAL_COMBINER (default ON) Tests: tests/unit/test_signal_combiner.cpp — 25+ GTest cases

#include "signal_combiner.hpp"
using namespace llmquant;

SignalCombiner sc;
sc.add_signal({"sentiment",    0.7, 0.85, ts_ms});
sc.add_signal({"alpha_decay",  0.4, 0.60, ts_ms});
sc.add_signal({"exec_timing", -0.1, 0.40, ts_ms});

auto result = sc.combine(CombineMethod::WEIGHTED_AVERAGE);
// result->action ~ 0.52, regime = TRENDING

SignalHistory history(64);
history.push(*result);
int dir = history.trend_direction();  // +1, -1, or 0
double vol = history.volatility();

Round 5: Cross-Asset Sentiment Correlation

Header: include/cross_asset_sentiment.hpp | Source: src/cross_asset_sentiment.cpp

Rolling Pearson correlation between asset sentiment streams, single-linkage clustering, and contagion regime detection.

| Class | Role | |---|---| | AssetSentiment | asset_id: string, sentiment_score: double [-1,1], timestamp_ms: int64_t | | SentimentCorrelationMatrix | Rolling Pearson r between any pair of registered assets; update(sentiments), correlation(a, b) -> optional<double>, leading_asset(target) -> optional<string> via lagged cross-correlation (lag 1..max_lag) | | SentimentCluster | build(matrix, threshold) — single-linkage Union-Find agglomerative clustering; assets linked if |rho| >= threshold | | SentimentRegimeDetector | update(matrix) — fires on_contagion_event(avg_corr) when average pairwise correlation spikes above spike_threshold; respects cooldown_steps between firings |

Feature flag: LLMQUANT_ENABLE_CROSS_ASSET_SENTIMENT (default ON) Tests: tests/unit/test_cross_asset_sentiment.cpp (25+ GTest tests)

#include "cross_asset_sentiment.hpp"
using namespace llmquant;

SentimentCorrelationMatrix::Config cfg;
cfg.window_size = 60; cfg.min_samples = 10; cfg.max_lag = 5;
SentimentCorrelationMatrix matrix(cfg);
matrix.register_asset("BTC");
matrix.register_asset("ETH");

matrix.update(AssetSentiment{"BTC",  0.7, now_ms});
matrix.update(AssetSentiment{"ETH",  0.6, now_ms});

auto rho    = matrix.correlation("BTC", "ETH");   // optional<double>
auto leader = matrix.leading_asset("ETH");          // optional<string>

auto clusters = SentimentCluster::build(matrix, 0.5);

SentimentRegimeDetector::Config rcfg;
rcfg.spike_threshold = 0.7;
rcfg.on_contagion_event = [](double avg) { /* hedge */ };
SentimentRegimeDetector detector(rcfg);
detector.update(matrix);

Alpha Decay Model

Header: include/alpha_decay.hpp | Source: src/alpha_decay.cpp

Models how a trading signal's alpha (predictive strength) decays over time, supporting four decay profiles and a multi-symbol portfolio aggregator.

Decay Models (DecayModel variant):

| Model | Formula | Half-life | |---|---|---| | Exponential { half_life_ms } | s(t) = exp(−λΔt), λ = ln(2)/half_life_ms | Analytical: half_life_ms | | Linear { duration_ms } | s(t) = max(0, 1 − Δt/duration_ms) | Analytical: duration_ms / 2 | | PowerLaw { exponent, scale_ms } | s(t) = (scale / (scale + Δt))^exp | Analytical: scale × (2^(1/exp) − 1) | | StepFunction { levels } | Piecewise constant by threshold | Newton-Raphson / bisection |

API:

| Class | Method | Description | |---|---|---| | AlphaDecay | current_strength(signal, now_ms) | Decayed alpha at now_ms | | AlphaDecay | half_life_ms(signal) | Time for strength to halve | | AlphaPortfolio | add_signal(symbol, signal) | Register a signal | | AlphaPortfolio | net_alpha(symbol, now_ms) | Sum of active signal strengths | | AlphaPortfolio | prune(now_ms, threshold=0.01) | Remove signals below threshold |

#include "alpha_decay.hpp"
using namespace llmquant;

AlphaSignal sig{
    .strength        = 1.0,
    .generated_at_ms = 1000,
    .decay_model     = DecayModel{ Exponential{500.0} },
};

double s  = AlphaDecay::current_strength(sig, 1500);  // 0.5
double hl = AlphaDecay::half_life_ms(sig);             // 500.0

AlphaPortfolio portfolio;
portfolio.add_signal("AAPL", sig);
double net = portfolio.net_alpha("AAPL", 2000);  // ~0.25
portfolio.prune(2000, 0.01);

Tests: tests/unit/test_alpha_decay.cpp (25+ GTest cases covering all four decay models and AlphaPortfolio)


Architecture

  LLM API / WebSocket feed
          |
          v
   LLMStreamClient          (TLS WebSocket, reconnect, backpressure)
          |
          v
    LLMAdapter              (token -> SemanticWeight, SIMD map_sequence, ~130-entry static dict)
          |             \
          |              DynamicTokenDictionary  (hot-reload YAML/JSON, EMA self-learning)
          |              DictionaryLearner        (Naive Bayes, labelled outcome training)
          v
  TradeSignalEngine         (bias/vol accumulation, exponential decay, signal emission)
          |
          v
  CrossAssetEngine  <-----> [SPY, QQQ, GLD, BTC, ...]
  (rolling Pearson matrix, conviction multiplier, hedge ratio)
          |
          v
  EnsembleSignalVoter       (weighted vote across sub-models)
          |
          v
  RiskManager               (bias/confidence/rate/drawdown gates, position limits)
          |
      pass | block
          |
          v
  OMS Adapter               (FIX 4.2 / REST / Mock)
          |
   [trade execution]

  Side channels (always running):
    MetricsLogger  -->  Prometheus /metrics
    HealthServer   -->  /health (K8s liveness/readiness)
    SignalAuditLog -->  NDJSON append-only audit trail
    BacktestRunner -->  offline token-sequence replay + PnL stats

  v1.4.0 additions:
    RegimeDetectorHMM  -->  3-state HMM (TokenRegime: BULL/BEAR/UNCERTAINTY/CONSOLIDATION/BREAKOUT)
    RegimeFilter       -->  gates trade signals by regime alignment + confidence
    ExecutionQualityTracker --> lock-free 10K ring: p99 latency, fill rate, realised alpha
    TokenBacktester    -->  OHLCV bar matching, per-signal PnL, Sharpe, max drawdown

  Round 3 additions:
    MarketImpactModel  -->  Almgren-Chriss impact: linear + sqrt 

Related Skills

View on GitHub
GitHub Stars4
CategoryFinance
Updated13d ago
Forks0

Languages

C++

Security Score

75/100

Audited on Mar 23, 2026

No findings