RUST-FINANCE(1)

NAME

rust-financeA high-performance, ultra low-latency trading terminal and AI-infused daemon built completely in Rust.

SYNOPSIS

INFO

86 stars
22 forks
0 views

DESCRIPTION

A high-performance, ultra low-latency trading terminal and AI-infused daemon built completely in Rust.

README

RustForge Terminal (rust-finance)

Rust Tokio Ratatui Anthropic WebSocket
GitHub stars GitHub forks
Alpaca Binance Finnhub Polymarket
NASDAQ NYSE CME LSE NSE BSE CRYPTO
Windows macOS Linux
OpenSSF Scorecard Security Audit CI Tests dependency status License: MIT

Overview

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.

FeatureDetail
LanguagePure Rust
InterfaceFull TUI Dashboard (Ratatui, 6 screens)
AI IntegrationClaude-powered Dexter Analyst
Prediction MarketsPolymarket CLOB with EIP-712 signing
Agent Simulation100K-agent Rayon-parallel swarm
Knowledge Graphpetgraph-backed RAG engine
Risk ModelsGARCH(1,1) + VaR + Kill Switch + Interceptor Chain
Timestamp PrecisionNanosecond (UnixNanos)
Deterministic ReplayDeterministicClock + SequenceId ordering
Market SourcesAlpaca, Binance, Finnhub, Polymarket, Mock
ExecutionAlpaca REST, Polymarket CLOB, Paper Trading
LicenseMIT

Rust Trading Terminal


Table of Contents


Architecture

34 modular crates, 110+ 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 &quot;RustForge Engine&quot;
    Ingest(Ingestion / Source Multiplexer) --&gt; Bus(TCP Event Bus)
    Bus --&gt; AI(AI Engine — Dexter / Mirofish)
    Bus --&gt; Quant(Quant Features)
    Quant --&gt; Swarm(Swarm Simulator — 100K Agents)
    Swarm --&gt; KG(Knowledge Graph — petgraph RAG)
    KG --&gt; AI

    AI --&gt; Strategy(Strategy Dispatcher)
    Strategy --&gt; Risk(Risk Gate — GARCH / VaR / Kill Switch)
    Risk --&gt; Exec(Execution Gateway)

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

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

subgraph &quot;Persistence&quot;
    Bus --&gt; PG[(PostgreSQL)]
    Bus --&gt; Redis[(Redis Hot-State)]
end

subgraph &quot;Frontends&quot;
    Bus --&gt; TUI(Ratatui TUI Dashboard)
    Bus --&gt; Web(REST API / Web Dashboard)
end

Crate Map

common           Nanosecond timestamps, events, config, models
ingestion        Multi-source market data (Alpaca, Binance, Finnhub, Polymarket)
execution        Trait-based ExecutionGateway, AlpacaExecutor
strategy         Strategy trait, momentum, mean-reversion engines
risk             Kill switch, GARCH vol, VaR, risk interceptor chain
pricing          Black-Scholes-Merton, Heston, GARCH(1,1) models
backtest         Walk-forward, Monte Carlo, backtesting engine
ai               Dexter AI analyst, Claude integration, signal routing
swarm_sim        100,000-agent market microstructure simulator
knowledge_graph  petgraph-backed RAG knowledge engine
polymarket       Polymarket (3 APIs: Gamma, CLOB, Data) + EIP-712 signing
daemon           Hybrid intelligence pipeline, engine orchestration
event_bus        Postcard-serialized TCP event bus (daemon <-> TUI)
tui              Ratatui-powered 6-screen trading dashboard
oms              Order Management System (netting + hedging)
alerts           Rule-based alert engine
signals          Technical indicator signal generation
compliance       Pre-trade compliance, audit trail
persistence      PostgreSQL + SQLite persistence layer
metrics          Prometheus-compatible telemetry
ml               Machine learning model inference
model            Model registry and versioning
feature          Feature engineering pipeline
fix              FIX protocol adapter
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

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
  • 30-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, depth5) via combined WS endpoint
  • 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

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

  • ExecutionGateway trait — plug-and-play execution backends
  • 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 BTC 15-Min — Crypto prediction markets (BTC Up/Down, ETH, SOL, XRP, DOGE)
  • 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
  • Kill Switch — emergency circuit breaker (hotkey K in TUI)
  • GARCH(1,1) Volatility — real-time volatility estimation
  • Value at Risk (VaR) — parametric + historical VaR calculation
  • PnL Attribution — component-level profit/loss decomposition
  • Risk Interceptor Chain — composable pre-trade risk checks
  • Kelly Criterion Sizing — optimal position sizing
  • Max Drawdown and Daily Loss Limit trading guardrails

Quantitative Models

  • Black-Scholes-Merton — options pricing with Greeks
  • Heston Stochastic Volatility — smile-calibrated pricing
  • GARCH(1,1) — volatility forecasting (sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + beta * sigma_{t-1}^2)
  • Monte Carlo Engine — path simulation for derivative pricing
  • Walk-Forward Backtesting — out-of-sample validation
  • 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
  • Deterministic replay — reproduce any historical trading session

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

SEE ALSO

clihub3/23/2026RUST-FINANCE(1)