craaraju-ctrl/Cotrader

Cotrader - Autonomous Trading System

Rust

1

0 commits

updated Jul 10, 2026

See the code

README

CoTrader — Autonomous Trading System

Rust License

A production-grade autonomous trading system with 4-layer parallel validation, Cornish-Fisher VaR risk management, FinBERT sentiment analysis, and ML-driven signal arbitration — all in pure Rust.

Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                        4-LAYER VALIDATION PIPELINE                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  Layer 1: RULES (35%)              Layer 2: ML/SIGNAL (25%)                │
│  ├─ 22 Hard Rules                  ├─ Confluence scoring                   │
│  ├─ Pivot points (Classic/Woodie)  ├─ Technical indicators                 │
│  ├─ Regime-adaptive thresholds     └─ Deterministic signal                 │
│  └─ VaR Emergency Gate ★                                                   │
│                                                                             │
│  Layer 3: CHRONOS (25%)            Layer 4: SENTIMENT (15%) ★ NEW          │
│  ├─ T5-based forecasting           ├─ FinBERT (BGE-small-en-v1.5)         │
│  ├─ 2048 context window            ├─ 768-dim embeddings                   │
│  └─ 64-step predictions            └─ Directional modifier [-1, +1]        │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                    2-of-4 Agreement Gate → LLM Arbitration                  │
│                         (Llama-3.2-3B via Candle/Ollama)                    │
└─────────────────────────────────────────────────────────────────────────────┘

4-Layer Parallel Validation

LayerWeightSourcePurpose
Rules35%hard_rules_gate.rs22 deterministic risk rules + pivot/confluence signal
ML/Signal25%check_llm_layer()Confluence + trend analysis for deterministic signal
Chronos25%chronos_bolt.rsT5-based time series forecasting (64-step horizon)
Sentiment15%sentiment.rsFinBERT news sentiment with directional modifier

Cornish-Fisher VaR Emergency Gate ★ NEW

The VaR emergency gate provides dynamic statistical drawdown boundaries that replace static risk checks.

Formula

Z_cf = Z_α + (Z_α² - 1) × S/6 + (Z_α³ - 3Z_α) × K/24 - (2Z_α³ - 5Z_α) × S²/36

Where:
  Z_α = norm.ppf(0.01) = -2.326 (99% confidence)
  S   = rolling skewness of returns
  K   = rolling excess kurtosis of returns

VaR  = -(μ + Z_cf × σ)

Emergency Gate Logic

IF VaR_alpha > risk_tolerance (5%)
   OR volatility_ratio > volatility_cap (3x)
THEN:
   Force ALL layer signals to "HOLD"
   Override any bullish signals
   Log: "[VaR] ⚠ EMERGENCY TRIGGERED"

Configuration

pub struct VaRConfig {
    pub confidence_level: f64,      // 0.99 (99% VaR)
    pub lookback_window: usize,     // 60 bars (rolling window)
    pub risk_tolerance: f64,        // 0.05 (5% max portfolio VaR)
    pub volatility_cap: f64,        // 3.0 (max sigma multiplier)
    pub enabled: bool,              // default: true
}

FinBERT Sentiment Pipeline ★ NEW

Architecture

News Headlines → Keyword Classification → Embedding (BGE-small-en-v1.5)
                                              ↓
                                   384-dim Vector → Sentiment Score
                                              ↓
                                   [-1.0, +1.0] Directional Modifier

Sentiment Score Mapping

Score RangeLabelAction
< -0.6hyper-bearishStrong SELL signal
-0.6 to -0.2bearishSELL signal
-0.2 to +0.2neutralHOLD
+0.2 to +0.6bullishBUY signal
> +0.6hyper-bullishStrong BUY signal

LLM Prompt Integration

Sentiment:   score=+0.450 conf=0.72 (bullish)

8 Core Agents

AgentPurposeKey Features
AnalysisMarket data processing26+ indicators, ML regime detection
PlanningStrategy & signalsStrategy selection, Kelly sizing
DecisionCross-validationML scoring, conviction analysis
ImplementationOrder executionPaper/live trading, SL/TP monitoring
ObservationOutcome trackingTrade logging, rule learning
RiskRisk managementVaR gate, position adjustments
PsychologyBehavioral analysis5 bias types, discipline enforcement
EvolutionSelf-improvementML training, weight tuning

Quick Start

# Clone and build
git clone https://github.com/varma/cotrader.git
cd cotrader
cargo build --release

# Demo the 4-layer pipeline
cargo run --bin cotrader-cli demo BTC 58500.0

# Start the full system
./start.sh

# Monitor with TUI
./target/release/cotrader-tui

# Run tests
cargo test --workspace

Project Structure

cotrader/
├── crates/
│   ├── cotrader-core/           Core types, risk (VaR), sentiment, memory
│   ├── cotrader-autonomous/     4-layer pipeline, agents, rules engine
│   ├── cotrader-ml/             ML models (Chronos, Llama, regime, patterns)
│   ├── cotrader-orchestrator/   Service orchestration
│   ├── cotrader-runtime/        CLI and daemon management
│   ├── cotrader-eventbus/       Inter-agent event system
│   ├── cotrader-tui/            Terminal UI (Ratatui)
│   └── cotrader-broker-cotrader/ Broker adapter
├── memory/                 Agentic memory server (port 3111)
├── data/                   Model storage, logs
├── scripts/                Build/deploy scripts
├── start.sh                System launcher
├── stop.sh                 System shutdown
└── build.sh                Build automation

Tech Stack

ComponentTechnology
LanguageRust 2021
Async RuntimeTokio
ML FrameworkCandle 0.8 (neural networks)
Classical MLLinfa 0.7 (GBT, RandomForest)
Time SeriesChronos-Bolt (T5-based)
LLMLlama-3.2-3B (Candle GGUF)
Embeddingsfastembed (BGE-small-en-v1.5)
DatabaseSQLite (rusqlite), redb
UIRatatui TUI

ML Models

ModelTypeInputOutput
Chronos-BoltT5 encoder-decoder2048 timesteps64-step forecast
Regime ClassifierMLP30 indicators5 regimes
Signal ScorerMLP34 featuresP(profitable)
Win ProbabilityLogistic48 featuresP(win) for Kelly
Pattern DetectorCNN20-bar OHLCV4 directions
Strategy SelectorRandomForest48 featuresBest strategy

Hard Rules (22 Rules)

PriorityRuleThresholdAction
CriticalTrading enabledMust be trueBLOCK
CriticalDaily drawdown≤ 2%BLOCK
CriticalRed folder dayNo high-impact eventsBLOCK
HighPortfolio heat≤ 10% (vol-adjusted)BLOCK
HighConsecutive losses< 4BLOCK
HighDaily trades< 10BLOCK
HighKelly sizing≤ 2x half-KellyBLOCK
MediumRegime safetyNo BUY in bear+low confluenceBLOCK
MediumConfluence minRegime-adaptive (35-80%)BLOCK
LowMax positions< 3 per symbolWARN

Configuration

# Environment variables
PAPER_MODE=true                    # Paper trading mode
RAT_MAX_DAILY_TRADES=10            # Max trades per day

# System config (from ~/.rat/system.toml)
[llama_backend]
type = "Ollama"
url = "http://localhost:11434"
model = "llama3.2:3b"

Cross-Platform Support

  • macOS: Apple Silicon (M1/M2/M3) and Intel
  • Linux: Ubuntu x86_64/ARM64
  • Windows: Experimental support via WSL2

All paths resolve dynamically relative to ~/.rat/ or the runtime directory. No hardcoded macOS-specific paths.

License

MIT

craaraju-ctrl/Cotrader

Cotrader - Autonomous Trading System

Rust

1

0 commits

updated Jul 10, 2026

See the code

README

CoTrader — Autonomous Trading System

Rust License

A production-grade autonomous trading system with 4-layer parallel validation, Cornish-Fisher VaR risk management, FinBERT sentiment analysis, and ML-driven signal arbitration — all in pure Rust.

Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                        4-LAYER VALIDATION PIPELINE                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  Layer 1: RULES (35%)              Layer 2: ML/SIGNAL (25%)                │
│  ├─ 22 Hard Rules                  ├─ Confluence scoring                   │
│  ├─ Pivot points (Classic/Woodie)  ├─ Technical indicators                 │
│  ├─ Regime-adaptive thresholds     └─ Deterministic signal                 │
│  └─ VaR Emergency Gate ★                                                   │
│                                                                             │
│  Layer 3: CHRONOS (25%)            Layer 4: SENTIMENT (15%) ★ NEW          │
│  ├─ T5-based forecasting           ├─ FinBERT (BGE-small-en-v1.5)         │
│  ├─ 2048 context window            ├─ 768-dim embeddings                   │
│  └─ 64-step predictions            └─ Directional modifier [-1, +1]        │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                    2-of-4 Agreement Gate → LLM Arbitration                  │
│                         (Llama-3.2-3B via Candle/Ollama)                    │
└─────────────────────────────────────────────────────────────────────────────┘

4-Layer Parallel Validation

LayerWeightSourcePurpose
Rules35%hard_rules_gate.rs22 deterministic risk rules + pivot/confluence signal
ML/Signal25%check_llm_layer()Confluence + trend analysis for deterministic signal
Chronos25%chronos_bolt.rsT5-based time series forecasting (64-step horizon)
Sentiment15%sentiment.rsFinBERT news sentiment with directional modifier

Cornish-Fisher VaR Emergency Gate ★ NEW

The VaR emergency gate provides dynamic statistical drawdown boundaries that replace static risk checks.

Formula

Z_cf = Z_α + (Z_α² - 1) × S/6 + (Z_α³ - 3Z_α) × K/24 - (2Z_α³ - 5Z_α) × S²/36

Where:
  Z_α = norm.ppf(0.01) = -2.326 (99% confidence)
  S   = rolling skewness of returns
  K   = rolling excess kurtosis of returns

VaR  = -(μ + Z_cf × σ)

Emergency Gate Logic

IF VaR_alpha > risk_tolerance (5%)
   OR volatility_ratio > volatility_cap (3x)
THEN:
   Force ALL layer signals to "HOLD"
   Override any bullish signals
   Log: "[VaR] ⚠ EMERGENCY TRIGGERED"

Configuration

pub struct VaRConfig {
    pub confidence_level: f64,      // 0.99 (99% VaR)
    pub lookback_window: usize,     // 60 bars (rolling window)
    pub risk_tolerance: f64,        // 0.05 (5% max portfolio VaR)
    pub volatility_cap: f64,        // 3.0 (max sigma multiplier)
    pub enabled: bool,              // default: true
}

FinBERT Sentiment Pipeline ★ NEW

Architecture

News Headlines → Keyword Classification → Embedding (BGE-small-en-v1.5)
                                              ↓
                                   384-dim Vector → Sentiment Score
                                              ↓
                                   [-1.0, +1.0] Directional Modifier

Sentiment Score Mapping

Score RangeLabelAction
< -0.6hyper-bearishStrong SELL signal
-0.6 to -0.2bearishSELL signal
-0.2 to +0.2neutralHOLD
+0.2 to +0.6bullishBUY signal
> +0.6hyper-bullishStrong BUY signal

LLM Prompt Integration

Sentiment:   score=+0.450 conf=0.72 (bullish)

8 Core Agents

AgentPurposeKey Features
AnalysisMarket data processing26+ indicators, ML regime detection
PlanningStrategy & signalsStrategy selection, Kelly sizing
DecisionCross-validationML scoring, conviction analysis
ImplementationOrder executionPaper/live trading, SL/TP monitoring
ObservationOutcome trackingTrade logging, rule learning
RiskRisk managementVaR gate, position adjustments
PsychologyBehavioral analysis5 bias types, discipline enforcement
EvolutionSelf-improvementML training, weight tuning

Quick Start

# Clone and build
git clone https://github.com/varma/cotrader.git
cd cotrader
cargo build --release

# Demo the 4-layer pipeline
cargo run --bin cotrader-cli demo BTC 58500.0

# Start the full system
./start.sh

# Monitor with TUI
./target/release/cotrader-tui

# Run tests
cargo test --workspace

Project Structure

cotrader/
├── crates/
│   ├── cotrader-core/           Core types, risk (VaR), sentiment, memory
│   ├── cotrader-autonomous/     4-layer pipeline, agents, rules engine
│   ├── cotrader-ml/             ML models (Chronos, Llama, regime, patterns)
│   ├── cotrader-orchestrator/   Service orchestration
│   ├── cotrader-runtime/        CLI and daemon management
│   ├── cotrader-eventbus/       Inter-agent event system
│   ├── cotrader-tui/            Terminal UI (Ratatui)
│   └── cotrader-broker-cotrader/ Broker adapter
├── memory/                 Agentic memory server (port 3111)
├── data/                   Model storage, logs
├── scripts/                Build/deploy scripts
├── start.sh                System launcher
├── stop.sh                 System shutdown
└── build.sh                Build automation

Tech Stack

ComponentTechnology
LanguageRust 2021
Async RuntimeTokio
ML FrameworkCandle 0.8 (neural networks)
Classical MLLinfa 0.7 (GBT, RandomForest)
Time SeriesChronos-Bolt (T5-based)
LLMLlama-3.2-3B (Candle GGUF)
Embeddingsfastembed (BGE-small-en-v1.5)
DatabaseSQLite (rusqlite), redb
UIRatatui TUI

ML Models

ModelTypeInputOutput
Chronos-BoltT5 encoder-decoder2048 timesteps64-step forecast
Regime ClassifierMLP30 indicators5 regimes
Signal ScorerMLP34 featuresP(profitable)
Win ProbabilityLogistic48 featuresP(win) for Kelly
Pattern DetectorCNN20-bar OHLCV4 directions
Strategy SelectorRandomForest48 featuresBest strategy

Hard Rules (22 Rules)

PriorityRuleThresholdAction
CriticalTrading enabledMust be trueBLOCK
CriticalDaily drawdown≤ 2%BLOCK
CriticalRed folder dayNo high-impact eventsBLOCK
HighPortfolio heat≤ 10% (vol-adjusted)BLOCK
HighConsecutive losses< 4BLOCK
HighDaily trades< 10BLOCK
HighKelly sizing≤ 2x half-KellyBLOCK
MediumRegime safetyNo BUY in bear+low confluenceBLOCK
MediumConfluence minRegime-adaptive (35-80%)BLOCK
LowMax positions< 3 per symbolWARN

Configuration

# Environment variables
PAPER_MODE=true                    # Paper trading mode
RAT_MAX_DAILY_TRADES=10            # Max trades per day

# System config (from ~/.rat/system.toml)
[llama_backend]
type = "Ollama"
url = "http://localhost:11434"
model = "llama3.2:3b"

Cross-Platform Support

  • macOS: Apple Silicon (M1/M2/M3) and Intel
  • Linux: Ubuntu x86_64/ARM64
  • Windows: Experimental support via WSL2

All paths resolve dynamically relative to ~/.rat/ or the runtime directory. No hardcoded macOS-specific paths.

License

MIT

Languages

Rust

98.7%

Shell

1.2%