Skip to content

Generalize trading daemon for multi-asset venues and crypto#21

Merged
jadenfix merged 4 commits into
mainfrom
codex/multi-asset-engine-generalization
Feb 17, 2026
Merged

Generalize trading daemon for multi-asset venues and crypto#21
jadenfix merged 4 commits into
mainfrom
codex/multi-asset-engine-generalization

Conversation

@jadenfix

Copy link
Copy Markdown
Owner

No description provided.

@greptile-apps

greptile-apps Bot commented Feb 17, 2026

Copy link
Copy Markdown

Greptile Summary

This PR transforms the trading daemon from a Kalshi-specific implementation into a generalized multi-asset, multi-venue trading platform. The changes introduce a unified domain model (trading_domain), an exchange adapter abstraction (ExchangeAdapter trait), and concrete implementations for Kalshi (binary prediction markets), Coinbase Spot (crypto), and a paper-only derivatives adapter.

Key architectural improvements:

  • Centralized InstrumentId with support for multiple asset classes (Prediction, Crypto, Equity, Forex, Derivative) and market types (Spot, Binary, Perpetual, Futures, Option)
  • Venue-aware execution mode management allowing per-venue/market-type Paper vs Live mode configuration
  • New risk management with venue-specific notional limits via HardSafetyCage
  • SQLite persistence for runtime state including venues, execution modes, orders, fills, and events
  • Protocol extensions for venue management, portfolio queries, and order submission
  • Three new strategy plugins: crypto momentum, Kalshi arbitrage, and Kalshi weather

Critical issue found:

  • crates/trading_daemon/src/main.rs:396-400 - The default_execution_modes function contains a logic bug where both branches of the if-else statement return ExecutionMode::Paper, preventing any venue from ever defaulting to Live mode despite venues being marked as live_enabled: true

Confidence Score: 3/5

  • This PR contains a critical bug that prevents live trading from being enabled by default
  • The logic bug in default_execution_modes means all venues will default to Paper mode regardless of configuration. While the architectural changes are solid and the code is well-structured with proper risk controls, this bug prevents the core functionality (live trading on non-paper-only venues) from working as intended. The bug is easily fixable but must be corrected before merge.
  • Pay close attention to crates/trading_daemon/src/main.rs - specifically the default_execution_modes function which contains a copy-paste error

Important Files Changed

Filename Overview
crates/trading_daemon/src/main.rs Added multi-venue support with venues, execution modes, and adapters; contains critical bug in default_execution_modes that prevents live trading
crates/trading_domain/src/lib.rs New file defining core multi-asset domain types (AssetClass, MarketType, InstrumentId, OrderRequest, etc.)
crates/exchange_core/src/lib.rs New ExchangeAdapter trait providing venue-agnostic abstraction for orders, positions, balances, and health
crates/exchange_kalshi/src/lib.rs New KalshiAdapter implementation for binary prediction markets with paper and live mode support
crates/exchange_coinbase_spot/src/lib.rs New CoinbaseSpotAdapter for crypto spot trading with proper asset class validation
crates/risk_core/src/lib.rs New hard safety cage with venue-aware notional limits, position limits, and promotion gate validation

Class Diagram

classDiagram
    class TradingDaemon {
        +EngineState
        +handle_connection()
        +initial_engine_state()
    }
    
    class EngineState {
        +venues: HashMap
        +execution_modes: HashMap
        +adapters: HashMap
        +strategies: HashMap
        +risk_snapshot: RiskSnapshot
    }
    
    class ExchangeAdapter {
        <<interface>>
        +venue() str
        +capabilities() Vec
        +execution_mode() ExecutionMode
        +place_order()
        +cancel_order()
        +sync_positions()
        +sync_balances()
        +health()
    }
    
    class KalshiAdapter {
        +mode: ExecutionMode
        +state: AdapterState
    }
    
    class CoinbaseSpotAdapter {
        +mode: ExecutionMode
        +state: AdapterState
    }
    
    class DerivativesPaperAdapter {
        +state: AdapterState
    }
    
    class TradingDomain {
        +InstrumentId
        +OrderRequest
        +OrderSummary
        +PositionSnapshot
        +BalanceSnapshot
    }
    
    class HardSafetyCage {
        +policy: HardSafetyPolicy
        +evaluate_order()
        +evaluate_promotion()
    }
    
    class StrategyPlugin {
        <<interface>>
        +id() str
        +family() StrategyFamily
        +evaluate()
    }
    
    TradingDaemon --> EngineState
    EngineState --> ExchangeAdapter
    EngineState --> HardSafetyCage
    ExchangeAdapter <|-- KalshiAdapter
    ExchangeAdapter <|-- CoinbaseSpotAdapter
    ExchangeAdapter <|-- DerivativesPaperAdapter
    ExchangeAdapter --> TradingDomain
    StrategyPlugin --> TradingDomain
    HardSafetyCage --> RiskSnapshot
Loading

Last reviewed commit: ff19223

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

27 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +396 to +400
let mode = if venue.paper_only {
ExecutionMode::Paper
} else {
ExecutionMode::Paper
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

always defaults to Paper mode regardless of venue.paper_only value

Suggested change
let mode = if venue.paper_only {
ExecutionMode::Paper
} else {
ExecutionMode::Paper
};
let mode = if venue.paper_only {
ExecutionMode::Paper
} else {
ExecutionMode::Live
};

@jadenfix

Copy link
Copy Markdown
Owner Author

@greptile

@greptile-apps

greptile-apps Bot commented Feb 17, 2026

Copy link
Copy Markdown

Greptile Summary

This PR generalizes the trading daemon to support multiple asset classes and venues. The implementation adds three exchange adapters (Kalshi, Coinbase Spot, Derivatives Paper) with runtime execution mode control, SQLite-based state persistence, and three new strategy plugins for crypto momentum and Kalshi markets.

Key changes:

  • Added VenueState and per-venue/market execution mode management with ExecutionMode.Set/Get commands
  • Implemented SQLite persistence for venues, execution modes, orders, fills, and risk state with WAL mode
  • Enhanced risk management with per-venue notional limits, leverage checks, and position limits
  • Created modular exchange adapter pattern with ExchangeAdapter trait
  • Added CLI commands for venue management, portfolio queries, and order submission
  • TypeScript client extended with new venue and execution mode APIs

Found issue:

  • derivatives_paper adapter doesn't respect execution mode changes (always uses Paper mode)

Confidence Score: 3/5

  • This PR is generally safe but has one logic issue with execution mode handling that should be addressed
  • The PR demonstrates good architecture with modular adapters, comprehensive risk management, and SQLite persistence. However, the derivatives_paper adapter has an inconsistency where it doesn't respect execution mode changes, always defaulting to Paper mode regardless of configuration. While this may be intentional (it's marked as paper-only), the inconsistency in the refresh pattern could lead to confusion.
  • Pay attention to crates/trading_daemon/src/main.rs line 1474-1478 and crates/exchange_derivatives_paper/src/lib.rs to ensure the execution mode behavior is intentional

Important Files Changed

Filename Overview
crates/trading_daemon/src/main.rs Major refactoring to support multi-venue/multi-asset trading with SQLite persistence, execution mode management, and venue adapters. Found issue with derivatives_paper adapter not respecting execution mode changes.
crates/exchange_core/src/lib.rs Clean trait definition for exchange adapters with execution mode support.
crates/exchange_derivatives_paper/src/lib.rs Paper-only derivatives adapter implementation that hardcodes ExecutionMode::Paper and cannot be configured otherwise, which may be intentional but inconsistent with other adapters.
crates/exchange_coinbase_spot/src/lib.rs Coinbase spot adapter with configurable execution mode, properly handles both paper and live mode order submission.
crates/exchange_kalshi/src/lib.rs Kalshi adapter with configurable execution mode, properly handles paper vs live order execution.
crates/trading_domain/src/lib.rs Core domain types for multi-asset trading including instruments, orders, execution modes, and venue capabilities.
crates/trading_protocol/src/lib.rs Protocol definitions for venue, portfolio, order, and execution mode commands with proper serialization.
crates/risk_core/src/lib.rs Enhanced risk management with per-venue notional limits, leverage checks, and position limits with comprehensive tests.

Flowchart

flowchart TD
    A[Trading Daemon] --> B[Venue Management]
    A --> C[Execution Mode Control]
    A --> D[Order Routing]
    A --> E[Risk Management]
    
    B --> F[Kalshi Adapter]
    B --> G[Coinbase Spot Adapter]
    B --> H[Derivatives Paper Adapter]
    
    C --> I[Per-Venue/Market Mode]
    I --> J[Live Mode]
    I --> K[Paper Mode]
    
    D --> L[Strategy Signals]
    L --> M[Crypto Momentum]
    L --> N[Kalshi Arbitrage]
    L --> O[Kalshi Weather]
    
    E --> P[Per-Venue Limits]
    E --> Q[Position Limits]
    E --> R[Leverage Checks]
    
    A --> S[SQLite Persistence]
    S --> T[Venues State]
    S --> U[Execution Modes]
    S --> V[Orders/Fills]
    S --> W[Risk State]
Loading

Last reviewed commit: d7ed0de

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

27 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +1474 to +1478
"derivatives_paper" => {
state.adapters.insert(
"derivatives_paper".to_string(),
Arc::new(DerivativesPaperAdapter::default()),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

derivatives_paper adapter doesn't receive execution mode parameter

Unlike kalshi and coinbase_spot adapters, DerivativesPaperAdapter::default() ignores execution modes. The adapter hardcodes ExecutionMode::Paper in its implementation (see crates/exchange_derivatives_paper/src/lib.rs:89-91). This is inconsistent with the pattern used for other adapters and means execution mode changes via ExecutionMode.Set won't affect this venue.

@jadenfix

Copy link
Copy Markdown
Owner Author

@greptile

@greptile-apps

greptile-apps Bot commented Feb 17, 2026

Copy link
Copy Markdown

Greptile Summary

This PR transforms the trading daemon from a Kalshi-specific system into a generalized multi-asset trading platform. The changes introduce three new exchange adapters (Coinbase spot, Kalshi, derivatives paper), a unified domain model supporting multiple asset classes and market types, SQLite-based state persistence, and runtime execution mode management.

Major changes:

  • Architecture: Introduced ExchangeAdapter trait allowing pluggable venue support with normalized order execution
  • Multi-asset support: Added domain types for crypto spot, binary prediction markets, perpetuals, futures, and options
  • Execution modes: Runtime-switchable paper/live modes per venue+market_type with adapter refresh on mode changes
  • Persistence: SQLite database stores venues, execution modes, orders, fills, strategies, risk state, and event journal
  • Risk enhancements: Added per-venue notional limits, position count limits, and leverage constraints
  • Protocol extensions: New command families for Venue, Portfolio, Order, and ExecutionMode management
  • Safety: derivatives_paper adapter intentionally clamps all execution modes to Paper (lines 35-38)

The codebase demonstrates careful attention to safety with hardened derivatives adapter behavior, comprehensive risk controls, and proper state synchronization between in-memory and persistent storage.

Confidence Score: 4/5

  • This PR is safe to merge with minor risk from the substantial architectural changes
  • The implementation demonstrates strong safety practices (paper-only derivatives clamping, comprehensive risk limits, proper state persistence), clean architectural patterns (trait-based adapters, normalized domain types), and thorough testing of risk constraints. The score reflects the large surface area of changes (3600+ lines) and complexity of multi-venue coordination, but the careful defensive programming patterns and the fact that previous issues have been addressed mitigate most concerns.
  • Pay close attention to crates/trading_daemon/src/main.rs for adapter lifecycle management and state synchronization between SQLite and in-memory state

Important Files Changed

Filename Overview
crates/trading_daemon/src/main.rs Added multi-asset venue support, SQLite persistence, execution mode management, portfolio/order commands; major refactoring with proper adapter lifecycle
crates/exchange_coinbase_spot/src/lib.rs New Coinbase spot adapter for crypto trading with paper/live mode support, position tracking, and order management
crates/exchange_derivatives_paper/src/lib.rs Paper-only derivatives adapter that intentionally clamps all execution modes to Paper for safety
crates/trading_domain/src/lib.rs Canonical multi-asset domain types including AssetClass, MarketType, InstrumentId, OrderRequest, and execution primitives
crates/trading_protocol/src/lib.rs Extended protocol with Venue, Portfolio, Order, and ExecutionMode commands and payloads
crates/risk_core/src/lib.rs Enhanced risk controls with per-venue notional limits, position count limits, and leverage constraints
crates/trading_daemon/migrations/0001_runtime.sql SQLite schema for persisting venues, execution modes, orders, fills, strategies, risk state, and events
.openclaw/extensions/trading-bridge/src/index.ts Trading bridge updated with venue, order, portfolio, and execution mode management support

Flowchart

flowchart TD
    CLI[tradingctl CLI] -->|Unix Socket| Daemon[Trading Daemon]
    Bridge[Trading Bridge] -->|Unix Socket| Daemon
    
    Daemon -->|Manages| State[(SQLite State)]
    Daemon -->|Manages| Venues[Venue Registry]
    Daemon -->|Manages| ExecModes[Execution Modes]
    
    Venues -->|Creates| Adapters[Exchange Adapters]
    
    Adapters -->|Kalshi| KalshiAdapter[Kalshi Adapter]
    Adapters -->|Coinbase| CoinbaseAdapter[Coinbase Spot Adapter]
    Adapters -->|Paper| DerivAdapter[Derivatives Paper Adapter]
    
    KalshiAdapter -->|Binary Markets| Markets
    CoinbaseAdapter -->|Crypto Spot| Markets
    DerivAdapter -->|Perp/Futures/Options| Markets[Market Operations]
    
    Daemon -->|Validates| Risk[Risk Core]
    Risk -->|Enforces| Limits[Per-Venue Notional<br/>Position Count<br/>Leverage Limits]
    
    Daemon -->|Executes| Strategies[Strategy Plugins]
    Strategies -->|Kalshi| KalshiStrats[Kalshi Arbitrage<br/>Weather Strategy]
    Strategies -->|Crypto| CryptoStrats[Crypto Momentum]
    
    State -->|Persists| VenueState[Venues Table]
    State -->|Persists| ExecState[Execution Modes Table]
    State -->|Persists| Orders[Orders Table]
    State -->|Persists| Events[Events Journal]
Loading

Last reviewed commit: b8739ad

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

27 files reviewed, no comments

Edit Code Review Agent Settings | Greptile

@jadenfix jadenfix merged commit cf6790f into main Feb 17, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant