RustFinance Terminal (rust-finance)

June 21, 2026 Β· View on GitHub

Rust Tokio Ratatui Anthropic WebSocket
Rayon Serde Petgraph Criterion Postcard
PostgreSQL Redis Docker GitHub Actions LaTeX
GitHub stars GitHub forks Buy Me a Coffee
Alpaca Binance Finnhub Polymarket
NASDAQ NYSE CME LSE NSE BSE CRYPTO
Windows macOS Linux
OpenSSF Scorecard Security & Supply Chain CI Tests dependency status License: MIT

At a Glance

RustFinance Terminal, also called RustForge, is an open-source Rust trading terminal for market-data ingestion, execution research, quantitative risk controls, compliance checks, and terminal dashboards.

Safety: this project is research and open-source infrastructure. It is not financial advice, not a broker, and not a guarantee of live-trading readiness. Use paper trading and independent review before connecting real capital.


Overview

https://github.com/user-attachments/assets/c769b2c2-cfa0-44bd-a261-99786ea653e1

RustForge is an institutional-grade AI trading terminal built in pure Rust. It combines real-time multi-exchange market data, Claude-powered AI analysis, quantitative risk management, prediction market trading, and a full TUI dashboard β€” all in a single binary with nanosecond-precision timestamps and sub-millisecond latency.

v0.4 β€” 2026 Quant Alpha Library: Multi-level Microprice (MLOFI), Adverse Selection Detection, Regime-Conditioned Quoting, Kelly+Bayesian Sizing, Alpha Health Monitor, IC-Weighted Composite Signals, Enhanced Avellaneda-Stoikov Quoting Engine, Almgren-Chriss Optimal Execution, Live Binance WebSocket Candlestick Feed, and WebSocket Gap Detection Engine. 82+ unit tests passing on Rust 1.95.0.

FeatureDetail
LanguagePure Rust
InterfaceFull TUI Dashboard (Ratatui, 6 screens)
AI IntegrationClaude-powered Dexter Analyst
Execution AlgorithmsTWAP, VWAP, Iceberg, POV, Almgren-Chriss Optimal Execution
Market MakingEnhanced Avellaneda-Stoikov with regime gating, VPIN toxicity, OFI skew
MicrostructureMulti-level MLOFI, OFI, Microprice, Kyle's Lambda, VPIN, Amihud, Lee-Ready
Smart Order RouterMulti-venue scoring (fill rate, latency, fees, impact)
Alpha SignalsToxicity detection, regime classifier, IC-weighted composite, alpha health
Position SizingQuarter-Kelly with Bayesian shrinkage, conviction scaling
Live DataBinance WebSocket candlestick feed with gap detection engine
Prediction MarketsPolymarket CLOB + cross-platform arbitrage engine
Agent Simulation100K-agent Rayon-parallel swarm
Knowledge Graphpetgraph-backed RAG engine
Risk ModelsGARCH(1,1) + VaR + Kill Switch + SMP + Regime Detection + Toxicity Gating
Timestamp PrecisionNanosecond (UnixNanos)
Deterministic ReplayDeterministicClock + SequenceId ordering
Regulatory ComplianceSEBI 2026 Algo-ID + OPS threshold + pre-trade checks
Fill SimulationAlmgren-Chriss √-impact model + fixed slippage
Alpha MonitoringRolling IC, Sharpe, hit rate with auto-decay detection
FIX ProtocolProduction FIX 4.4 parser with checksum validation
Market SourcesAlpaca, Binance, Finnhub, Polymarket, Mock
ExecutionAlpaca REST, Polymarket CLOB, Paper Trading
LicenseMIT

Rust Trading Terminal


Table of Contents


Architecture

34 modular crates, 250+ source files, strict dependency boundaries.

graph TD;
    subgraph "External Feeds"
        ALP(Alpaca WS) --> Ingest
        BIN(Binance WS) --> Ingest
        FH(Finnhub WS) --> Ingest
        PM(Polymarket WS) --> Ingest
        LLM(Anthropic Claude) <--> AI
    end

    subgraph "RustForge Engine"
        Ingest(Ingestion / Source Multiplexer) --> Bus(TCP Event Bus)
        Bus --> AI(AI Engine β€” Dexter / Mirofish)
        Bus --> Quant(Quant Features)
        Quant --> Swarm(Swarm Simulator β€” 100K Agents)
        Swarm --> KG(Knowledge Graph β€” petgraph RAG)
        KG --> AI

        AI --> Strategy(Strategy Dispatcher)
        Strategy --> Risk(Risk Gate β€” GARCH / VaR / Kill Switch)
        Risk --> Exec(Execution Gateway)

        Exec -.-> |Paper Mode| Mock(MockExecutor)
        Exec --> |Live Mode| AlpacaAPI(Alpaca REST)
        Exec --> |Prediction| PolyCLOB(Polymarket CLOB)
    end

    subgraph "Quantitative Models"
        Pricing(Pricing Engine) --> BSM(Black-Scholes-Merton)
        Pricing --> HESTON(Heston Stochastic Vol)
        Risk --> GARCH(GARCH 1,1 Volatility)
        Backtest(Backtest Engine) --> WF(Walk-Forward)
        Backtest --> MC(Monte Carlo)
    end

    subgraph "Persistence"
        Bus --> PG[(PostgreSQL)]
        Bus --> Redis[(Redis Hot-State)]
    end

    subgraph "Frontends"
        Bus --> TUI(Ratatui TUI Dashboard)
        Bus --> Web(REST API / Web Dashboard)
    end

Crate Map

common           Nanosecond timestamps, events, config, models
ingestion        Multi-source market data (Alpaca, Binance, Finnhub, Polymarket) + gap detector
execution        ExecutionGateway + TWAP/VWAP/Iceberg/POV + Almgren-Chriss optimal execution
strategy         Momentum, MeanReversion, Avellaneda-Stoikov (Welford O(1) variance)
risk             Kill switch, GARCH vol, VaR, risk interceptor chain, self-match prevention
pricing          Black-Scholes-Merton, Heston, GARCH(1,1) models
backtest         Walk-forward, Monte Carlo, backtesting engine, √-impact fill model
ai               Dexter AI analyst, Claude integration, signal routing
swarm_sim        100,000-agent market microstructure simulator
knowledge_graph  petgraph-backed RAG knowledge engine
polymarket       CLOB + EIP-712 signing + sum-to-one/cross-platform arb engine
daemon           Hybrid intelligence pipeline, engine orchestration
event_bus        Postcard-serialized TCP event bus (daemon <-> TUI)
tui              Ratatui TUI + live Binance candlestick feed + 500 msg/frame cap
oms              Order Management System (netting + hedging + SEBI 2026 Algo-ID)
alerts           Rule-based alert engine
signals          2026 Quant Alpha Library (see below) + indicators + microstructure
compliance       Pre-trade compliance, audit trail
persistence      PostgreSQL + SQLite persistence layer
metrics          Prometheus-compatible telemetry
ml               Machine learning model inference, alpha decay monitoring
model            Model registry and versioning
feature          Feature engineering pipeline
fix              FIX 4.4 protocol engine β€” production parser + session layer
cli              Command-line interface
web              REST API server
web-dashboard    Web-based dashboard
dashboard        Dashboard data models
tests            Integration test suite
benchmarks       Criterion performance benchmarks

Signals Crate β€” 2026 Quant Alpha Library

Based on 18 research papers (2025–2026). 55 unit tests.

Indicators       SMA, EMA, RSI, MACD, Bollinger Bands, VWAP
Microstructure   OFI (Cont 2014), Microprice, Kyle's Lambda, VPIN (Easley 2012),
                 Amihud Illiquidity, Lee-Ready Trade Classifier
Microprice ML    Multi-level microprice MLOFI (Oxford 2019, arXiv 2602.00776)
Adverse Select.  Toxicity detection + halt/widen (Barzykin 2025, Crypto 2026)
Regime           Fast/slow EMA vol ratio β†’ LowVol/Normal/HighVol/Crisis (RegimeFolio 2025)
Kelly            Quarter-Kelly + Bayesian shrinkage sizing (PolySwarm Apr 2026)
Alpha Health     IC decay + hit rate monitor β†’ Healthy/Degraded/Decayed (AlphaForgeBench 2026)
Composite        IC-weighted signal combiner with regime + toxicity gating (Chain-of-Alpha 2025)
Quoting Engine   Enhanced Avellaneda-Stoikov: regime Ξ³, VPIN widening, OFI skew, Kelly sizing

Execution Crate β€” Almgren-Chriss Optimal Execution

$ \text{Almgren}-\text{Chriss} \text{Optimal} \text{trajectory}: \text{x}β±Ό = \text{X} \times \text{sinh}(ΞΊ(\text{N}-\text{j})) / \text{sinh}(ΞΊ\text{N}) \text{Urgency} \text{parameter} ΞΊ = √(λσ²/Ξ·), \text{square}-\text{root} \text{impact} \text{model} \text{Presets}: \text{liquid\_default}, \text{aggressive}, \text{passive} 7 \text{unit} \text{tests} (\text{TWAP} \text{convergence}, \text{front}-\text{loading}, \text{quantity} \text{conservation}) $


Quick Start

# 1. Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 2. Clone
git clone https://github.com/Ashutosh0x/rust-finance.git
cd rust-finance

# 3. Configure
cp .env.example .env
# Edit .env β€” add your API keys (see Configuration below)

# 4. Build
cargo build --release

# 5. Run (mock mode β€” no API keys required)
USE_MOCK=1 cargo run -p daemon --release

# 6. Run TUI (separate terminal)
cargo run -p tui --release

Features

Core Engine

  • Hybrid Intelligence Pipeline β€” Quant, Swarm, Knowledge Graph, Dexter AI, Risk Gate, Execution
  • Nanosecond-precision timestamps (UnixNanos) with monotonic SequenceId ordering
  • Swappable clock β€” RealtimeClock for live trading, DeterministicClock for backtesting
  • Event-driven architecture with typed Envelope<T> wrapping every system event
  • Deterministic Safety Gate β€” zero-AI verification layer preventing agent confirmation bias
  • 34-crate workspace compiling in ~17s

Market Data

  • Alpaca β€” Real-time US equities via WebSocket (5 feeds: IEX, SIP, BOATS, Delayed, Overnight)
  • Binance β€” Crypto streams (trades, bookTicker, kline, depth5) via combined WS endpoint
    • Live Candlestick Feed β€” Direct WebSocket kline_1m stream β†’ real-time OHLCV candlestick rendering in TUI
    • Gap Detection Engine β€” Sequence-based WebSocket gap detector with configurable thresholds (small gap: retransmit, medium: snapshot, large: failover)
  • Finnhub β€” Global market data (incl. NSE/BSE) and live trades via WebSocket
  • Polymarket β€” Prediction market data via 3 APIs:
    • Gamma API β€” Events, markets, tags, search, profiles (gamma-api.polymarket.com)
    • CLOB API β€” Orderbook, midpoint, spread, prices-history, tick-size, fee-rate (clob.polymarket.com)
    • Data API β€” Positions, trades, leaderboards, open interest (data-api.polymarket.com)
  • Mock source β€” Deterministic replay for backtesting
  • Auto-reconnect with exponential backoff on all sources
  • Source Multiplexer β€” unified SelectAll stream from any combination of sources
  • 500 msg/frame cap β€” Prevents TUI freeze during high-volume market activity (e.g., BTC flash crashes)

AI Intelligence

  • Dexter AI Analyst β€” Claude-powered market analysis with structured signal output
  • 100K Agent Swarm Simulation β€” Rayon-parallel microstructure Monte Carlo
  • Knowledge Graph β€” petgraph RAG with entity linking and context fusion
  • Fused Context β€” Quant + Swarm + Graph consensus fed into Dexter prompt
  • Impact Analysis Engine β€” AI-driven market impact estimation
  • Mirofish β€” 5,000-agent scenario simulator (rally/sideways/dip probabilities)

Execution & Algorithmic Trading

  • ExecutionGateway trait β€” plug-and-play execution backends
  • Almgren-Chriss Optimal Execution β€” closed-form trajectory minimizing E[cost] + λ×Var[cost], with urgency parameter ΞΊ = √(λσ²/Ξ·), square-root impact model, and adaptive Οƒ/Ξ» updates from GARCH + regime detector
  • TWAP β€” Time-weighted slicing with configurable horizon_secs / interval_secs
  • VWAP β€” Volume-weighted execution with U-shape intraday profile
  • Iceberg β€” Hidden liquidity: only display_qty visible, auto-replenish on fill
  • POV (Percentage of Volume) β€” Adaptive participation tracking real-time market volume
  • Smart Order Router (SOR) β€” Multi-venue scoring (fill rate, latency, fees, liquidity, market impact), dark pool preference for large orders, spray routing, MiFID II best execution reporting
  • Alpaca Executor β€” Full REST integration (25+ endpoints: orders, positions, assets, historical data)
  • Polymarket CLOB β€” full order lifecycle (limit/market/FOK/GTC/GTD), EIP-712 signed orders
  • Polymarket Arbitrage β€” Sum-to-one (YES+NO < $1), cross-market, and cross-platform (Polymarket vs Kalshi) spread detection with fee-aware P&L
  • Paper trading β€” MockExecutor for risk-free strategy testing
  • Bracket orders β€” OCO/OTO stop-loss + take-profit combos
  • Trailing stops β€” dynamic stop-loss that follows price

Risk Management

  • Deterministic Safety Gate β€” zero-AI verification layer detecting agent confirmation bias (>85% agreement), concentration, drawdown, and correlation exposure
  • Self-Match Prevention (SMP) β€” wash trade prevention for market makers with 3 exchange-standard modes: CancelResting (CME), CancelAggressive (NASDAQ), CancelBoth (safest)
  • Kill Switch β€” emergency circuit breaker (hotkey K in TUI)
  • GARCH(1,1) + EGARCH β€” real-time symmetric and asymmetric volatility estimation
  • Value at Risk (VaR) β€” Historical, Parametric (Delta-Normal), and Student-t fat-tail VaR at 95%/99% confidence with CVaR (Expected Shortfall)
  • Component VaR β€” per-position marginal contribution to portfolio risk
  • 10-Day Basel VaR β€” √10 scaling for regulatory compliance
  • PnL Attribution β€” component-level profit/loss decomposition
  • Risk Interceptor Chain β€” composable pre-trade risk checks (MaxPositionSize, MaxDrawdown, MaxOpenOrders, DailyLossLimit, SMP)
  • Kelly Criterion Sizing β€” quarter-Kelly position sizing with conviction scaling
  • Cross-Asset Correlation β€” rolling pairwise correlation and concentration penalty
  • Regime Detection β€” GARCH-based volatility regime classification with position scaling
  • Alpha Decay Monitor β€” rolling Information Coefficient (Spearman IC), Sharpe ratio, and hit rate tracking; auto-flags Healthy β†’ Degraded β†’ Decayed health states for strategy auto-pause
  • Max Drawdown and Daily Loss Limit trading guardrails
  • SEBI 2026 Compliance β€” Algo-ID tagging (mandatory since April 1, 2026), OPS threshold monitoring, order variety classification, price band checks, uptick rule, squareoff time enforcement

Market Making & Microstructure (2026 Enhanced)

  • Enhanced Avellaneda-Stoikov Quoting Engine β€” Reservation pricing r = FV - q·γ·σ²·τ with:
    • Regime-conditioned Ξ³ β€” auto-adjusts risk aversion per volatility regime (RegimeFolio 2025)
    • VPIN spread widening β€” widens quotes when informed trading probability exceeds 0.5 (Easley 2012)
    • Toxicity halt β€” stops passive quoting at toxicity > 0.65 (Barzykin 2025)
    • OFI skew β€” shifts quotes by Ξ»_ofi Γ— OFI for order flow anticipation (Cont 2014)
    • Kelly-scaled sizing β€” position size = quarter-Kelly Γ— conviction Γ— regime_mult Γ— (1 - toxicity)
  • Adverse Selection Detector β€” EMA-smoothed post-fill price move analysis; classifies fills as toxic/safe and recommends Normal/Widen/HaltPassive actions
  • Multi-Level Microprice (MLOFI) β€” Oxford 2019 depth-decayed fair value across 5+ LOB levels; ~50-tick predictive lead over arithmetic mid
  • Two-State Regime Classifier β€” Fast/slow EMA vol ratio β†’ LowVol/Normal/HighVol/Crisis with debounce; each regime maps to concrete Ξ³, spread_mult, size_mult parameters
  • Order Flow Imbalance (OFI) β€” Cont et al. (2014) β€” net bid/ask volume change for short-term direction
  • VPIN Toxicity β€” Volume-synchronized Probability of Informed Trading (Easley et al. 2012)
  • Kyle's Lambda β€” Price impact coefficient per unit signed order flow (Kyle 1985)
  • Amihud Illiquidity β€” |return| / dollar_volume for position sizing in thin names
  • Lee-Ready Classifier β€” Buyer/seller-initiated trade classification
  • EWMA Volatility β€” Real-time annualized vol estimation (RiskMetrics Ξ»=0.94)

Alpha Signal Pipeline (2026 Quant Library)

  • Alpha Health Monitor β€” Tracks IC (information coefficient) and hit rate per signal; classifies Healthy (weight=1.0) / Degraded (0.4) / Decayed (0.0) with automatic disabling of decayed signals
  • Composite Signal Generator β€” IC-proportional weighting (Chain-of-Alpha 2025) with regime scaling and toxicity discounting; outputs (score, conviction) for downstream Kelly sizing
  • Kelly Criterion + Bayesian Shrinkage β€” Quarter-Kelly (industry standard per PolySwarm Apr 2026) with n/(n+30) Bayesian shrinkage for small sample sizes
  • Bayesian Fair Value β€” Weighted combination of microprice, fast EMA, and slow EMA with configurable alpha weights

Quantitative Models

  • Black-Scholes-Merton β€” options pricing with full Greeks (Delta, Gamma, Theta, Vega, Rho)
  • Heston Stochastic Volatility β€” smile-calibrated pricing via Monte Carlo
  • SABR Model β€” stochastic alpha-beta-rho for FX/rates vol surface
  • Hull-White β€” short-rate model for fixed income
  • Bond Pricer β€” yield-to-maturity, duration, convexity
  • GARCH(1,1) + EGARCH β€” volatility forecasting with leverage effects
  • Fundamental Analysis β€” DCF, Graham, and PEG valuation models
  • Monte Carlo Engine β€” path simulation for derivative pricing
  • Walk-Forward Backtesting β€” out-of-sample validation with Sharpe, Sortino, CAGR, profit factor
  • Pluggable Fill Model β€” FillModel trait with two implementations:
    • FixedSlippage β€” constant basis-point slippage (backward compat)
    • SquareRootImpact β€” Almgren-Chriss institutional model: impact = Οƒ Γ— Ξ· Γ— √(q/ADV) with presets for liquid (Ξ·=0.1), mid-cap (Ξ·=0.25), and illiquid (Ξ·=0.5) instruments
  • Transaction Cost Analysis (TCA) β€” Implementation Shortfall, VWAP/TWAP slippage, market impact, per-strategy breakdown
  • Gamma Exposure (GEX) β€” dealer gamma surface, flip points, pin risk zones, vol regime detection
  • Latency Queue β€” priority-queue latency simulation for realistic fills

TUI Dashboard

  • 6-screen navigation β€” Dashboard, Charts, Orderbook, Positions, AI, Settings
  • Real-time sparkline charts with zoom, scroll, and time range cycling
  • Live order book visualization β€” L2 depth with cumulative volume
  • 13-symbol watchlist auto-updating from market data feed
  • Exchange heartbeat monitor β€” NYSE, NASDAQ, CME, CBOE, LSE, CRYPTO, NSE, BSE
  • Dexter AI panel with live analysis output and BUY/SELL/HOLD recommendation
  • Mirofish simulation widget β€” rally/sideways/dip probability bars
  • Buy/Sell order entry dialogs with quantity and price inputs
  • Emergency controls β€” kill switch, paper/live toggle, risk adjustment

Compliance and Audit

  • Full audit trail β€” every state transition logged with AuditTick
  • Pre-trade compliance β€” rule-based order validation
  • SEBI 2026 Algo Framework β€” Algo-ID tagging on every order to NSE/BSE, static IP whitelisting, OPS threshold monitoring (>10 OPS requires registration), order value caps, MIS squareoff time enforcement, uptick rule, price band circuit filters
  • Deterministic replay β€” reproduce any historical trading session

FIX Protocol (v0.3)

  • Production FIX 4.4 Parser β€” length-delimited (BodyLength tag 9) message framing with checksum validation
  • Tag-Value Extraction β€” full field parsing into HashMap<u32, String> with MsgType derivation from tag 35
  • Streaming Parser β€” push_bytes() + next_message() pattern for TCP stream processing
  • Session Layer β€” Logon/Logout/Heartbeat/TestRequest/ResendRequest/SequenceReset handling
  • Supported Messages β€” Logon, Logout, Heartbeat, TestRequest, ResendRequest, SequenceReset, ExecutionReport, OrderCancelReject, NewOrderSingle, OrderCancelRequest
  • Zero external dependencies β€” hand-rolled for maximum control and auditability

Security & Supply Chain (CI/CD)

  • 8-job Security pipeline β€” cargo-audit (CVE), cargo-deny (licenses/bans/advisories), cargo-vet (supply chain verification), Clippy (pedantic + cargo lints), rustfmt, SHA-pin enforcement, CodeQL SAST, OpenSSF Scorecard
  • All GitHub Actions SHA-pinned to full 40-character commit hashes
  • Cross-platform CI β€” tests on Ubuntu, macOS, and Windows
  • MSRV verification β€” Minimum Supported Rust Version enforced
  • Benchmark compilation checks β€” Criterion benchmarks verified on every push

News Feed Sources

  • Finnhub News API β€” general market news, company-specific news, sector news
  • Alpaca News API β€” US equities breaking news, earnings, SEC filings
  • NewsAPI.org β€” aggregates Reuters, Bloomberg, CNBC, WSJ, Financial Times, BBC Business
  • Polygon.io β€” SEC filings, earnings reports, company reference data
  • BSE/NSE RSS β€” Indian market news from Bombay and National Stock Exchanges
  • CoinGecko β€” cryptocurrency market news and sentiment
  • SEC EDGAR β€” real-time regulatory filings (10-K, 10-Q, 8-K)

TUI Hotkeys

HotkeyAction
Tab / Shift+TabCycle between panels
BOpen BUY dialog
SOpen SELL dialog
EnterConfirm order
EscDismiss dialog
KKILL SWITCH β€” emergency halt all trading
MToggle paper/live mode
+ / -Adjust risk threshold
DTrigger Dexter AI analysis
FRun Mirofish simulation
Z / XChart zoom in/out
Left / RightChart scroll
TCycle chart time range
EExport data to CSV
RRefresh portfolio
?Toggle help overlay
QQuit

Performance

ComponentBenchmarkExecution Time
Tick PipelineOrder book mutation~40 ns
Pricing ModelsBSM European Call~34 ns
Risk ConstraintsGARCH(1,1) Update~2.3 ns
Risk ConstraintsBranchless Safety Check~1.6 ns
Event BusPostcard serializationZero-copy binary
Swarm Sim100K agentsRayon parallel
TimestampsUnixNanos precisionNanosecond
Event OrderingAtomicU64 sequenceLock-free

Release profile: opt-level=3, lto=fat, codegen-units=1, strip=true


Configuration

API Keys Required

ServiceEnvironment VariablePurposeFree Tier
AlpacaALPACA_API_KEY, ALPACA_API_SECRETUS equities market data + executionYes (paper trading)
FinnhubFINNHUB_API_KEYMarket data + news APIYes (60 calls/min)
AnthropicANTHROPIC_API_KEYDexter AI analyst (Claude)No (pay-per-token)
NewsAPI.orgNEWSAPI_KEYAggregated news (Reuters, Bloomberg, WSJ)Yes (100 req/day)
Polygon.ioPOLYGON_API_KEYOptions chains (GEX), reference data, newsYes (5 calls/min)
PolymarketPOLYMARKET_PRIVATE_KEY, POLYMARKET_FUNDER_ADDRESSPrediction market trading (EIP-712)N/A (needs ETH wallet)
TelegramTELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_IDAlert notificationsYes
DiscordDISCORD_WEBHOOK_URLAlert notificationsYes

Setup

  1. Copy the example environment file:

    cp .env.example .env
    
  2. Edit .env and add your API keys (see table above).

  3. Quick test with no API keys required:

    USE_MOCK=1 cargo run -p daemon --release
    

See docs/SETUP.md for step-by-step key creation instructions. See docs/CONFIGURATION.md for the full configuration reference.


Strategy Development

Strategies are implemented in the strategy crate using the PluggableStrategy async trait:

  1. Define your strategy struct and internal state
  2. Implement on_market_event() to process live tick data
  3. Emit TradeSignal objects with desired positions and dynamic confidences
  4. Register in the daemon's strategy registry for hot-swapping

For examples, see AiGatedMomentum in crates/daemon/src/strategy_registry.rs.


API Reference

EndpointPortProtocol
Market Data Ingestion4310WebSocket
Event Bus (daemon to TUI)7001TCP + Postcard
Prometheus Metrics3000HTTP GET /metrics
Tracing Export (Jaeger)4318OTLP UDP

Alpaca Broker Integration

  • POST /v2/orders β€” order submission via AlpacaBroker::submit_order, rate-limited to 150 req/min
  • GET /v2/positions β€” periodic position reconciliation into TUI

Polymarket CLOB Integration

  • POST /order β€” EIP-712 signed order placement
  • DELETE /order/{id} β€” cancel specific order
  • DELETE /cancel-all β€” cancel all open orders
  • GET /orders β€” list open orders
  • GET /book β€” order book snapshot
  • GET /midpoint β€” midpoint price
  • GET /balance-allowance β€” USDC balance

Troubleshooting

  • Build errors on Solana crates: The legacy parser, executor, signer, and relay crates are excluded from the workspace due to a yanked solana_rbpf dependency. They are replaced by crates/ingestion and crates/execution in the v2 architecture.
  • WebSocket timeout: Ensure your Finnhub/Alpaca API keys are correct. reconnect.rs will log warnings on exponential backoff attempts.
  • Missing API keys: Run in mock mode with USE_MOCK=1 to test without any API keys.
  • TUI not connecting: Start the daemon first (cargo run -p daemon), then the TUI (cargo run -p tui) in a separate terminal. The TUI connects via TCP to 127.0.0.1:7001.

License and Disclaimer

WARNING This software is provided for educational and research purposes only. The authors are not responsible for any financial losses incurred from running autonomous code on live capital.

MIT License (c) 2026 Ashutosh0x