Skip to content
Proyectos

Lqz13Th/extrema_infra

Ver en GitHub

Acerca de

A high-performance quantitative trading infrastructure built in Rust.

Negocios y finanzas

Cómo se miden estas cifras

What you can do

  • Features can be sent via ZeroMQ to Python ML models (Torch, GBM, Transformer, etc.).
  • ONNX models can also run directly inside extrema_infra without an external Python service.
  • AltTensor is the common dense tensor payload for feature input and model output.
  • Predictions return asynchronously to Rust for signal generation and order execution.

Crecimiento de estrellas medido

in 24h
0
in 7 days
+1
in 15 days
+4
in 1 month
Recopilando historial

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

Extrema Infra

A quantitative trading environment built in Rust.

  • Event-driven, channel-based, and designed for modular strategy execution across multiple exchanges.

  • Maximizes runtime efficiency through static dispatch and promotes scalability with Heterogeneous Lists (HList) for strategy registration.

At its core: One unified framework for multiple exchanges and strategies, with static dispatch at the strategy-registration boundary.


SOTA Usages

Explore state-of-the-art example usages, architecture walkthroughs, and community Q&A—no need to run it, just see how strategies and data flows are structured.

👉 Join the discussion & explore examples:
GitHub Discussions – Show and tell


Key Features

  • Machine Learning Integration Across Languages

    • Features can be sent via ZeroMQ to Python ML models (Torch, GBM, Transformer, etc.).
    • ONNX models can also run directly inside extrema_infra without an external Python service.
    • AltTensor is the common dense tensor payload for feature input and model output.
    • Predictions return asynchronously to Rust for signal generation and order execution.
  • Unified Exchange Abstraction

    • Supported exchange clients normalize common fields into the shared Market enum and data structs.
    • Strategies can consume unified types while still handling exchange-specific capabilities where needed.
    • Venues implemented outside this crate run on the same websocket relay through LobWsDecoder and Market::Custom.
  • Task-local Broadcast Distribution

    • Every concrete TaskKey owns one bounded Tokio broadcast ring.
    • Multiple strategies can consume the same task feed without extra exchange I/O.
    • with_strategy_module subscribes a module to every task, while with_strategy_module_on binds it to an explicit set of tasks; with_strategy_modules / with_strategy_modules_on register many modules of one type, and with_tasks registers several tasks at once.
    • A task's lifecycle event and primary data events travel through the same ring.
    • Delivery is lossy: a module that falls behind loses the oldest events instead of stalling the publisher, and receives on_lagged(key, skipped) (at most once per second per task stream) so it can resync, for example over REST.
  • Static Dispatch

    • HList keeps strategy types concrete, avoiding Box<dyn Strategy> and vtable dispatch.
    • Task routes are bound at startup, avoiding per-event TaskKey lookups.
  • Normalized Data

    • REST and WS payloads are converted into shared types at the exchange boundary.
    • WS data is converted once before being broadcast to strategies.
  • Channel-based Concurrency

    • Message passing via Tokio channels and broadcast streams keeps data flow explicit.
    • Reduces shared-state contention for real-time trading workloads.
    • Fits latency-sensitive, multi-consumer data flows.

Extrema Infra Architecture

Extrema Infra Architecture

The diagram predates the in-process ONNX runner, the OrderExecution / InstIntent relays and the task-local broadcast rings; the flowchart below reflects the current runtime.


Architecture Example: From Signal To Execution

Extrema Infra can model signal generation, model inference, allocation, portfolio mediation, and execution orchestration as independent tasks or strategy modules. Each module owns local state and communicates through async channels instead of directly sharing mutable state.

flowchart TB
    EXS["N Exchanges<br/>Binance / OKX / Gate / Hyperliquid<br/>+ custom venues"]

    subgraph RT["Extrema Infra runtime"]

        subgraph INGEST["WS ingestion tasks"]
            PUB["Public market WS<br/>trade / book / candle"]
            ACC["Account WS<br/>position / order / fill"]
        end

        subgraph SIGS["N strategy signal modules"]
            S1["Signal A"]
            S2["Signal B"]
            S3["Signal N"]
        end

        FEAT["Feature stream<br/>AltTensor"]

        subgraph MODELS["N model strategy modules"]
            M1["PyTorch<br/>Python / ZMQ"]
            M2["ONNX<br/>Rust"]
            M3["Model N"]
        end

        MPRED["Model preds<br/>AltTensor"]
        ALLOC["Allocator modules<br/>preds + price + account state"]
        PM["Portfolio mediator<br/>risk / constraints / OMS"]
        PLAN["Order planner<br/>slice / net / reduce-only / route"]

        subgraph ORDERS["N application order-execution modules"]
            O1["Account A execution"]
            O2["Account B execution"]
            O3["Account N execution"]
        end

        CMD["Strategy Cmd Path<br/>optional WS order route"]
    end

    EXS -->|market stream| PUB
    EXS -->|account stream| ACC

    PUB -->|market events| S1
    PUB -->|market events| S2
    PUB -->|market events| S3
    PUB -->|market events| ALLOC

    S1 --> FEAT
    S2 --> FEAT
    S3 --> FEAT

    FEAT --> M1
    FEAT --> M2
    FEAT --> M3

    M1 --> MPRED
    M2 --> MPRED
    M3 --> MPRED

    MPRED -->|model preds| ALLOC
    ACC -->|positions / fills| ALLOC
    ACC -->|order reports| PM

    ALLOC -->|allocator intent| PM
    PM --> PLAN

    PLAN -->|OrderExecute via relay| O1
    PLAN -->|OrderExecute via relay| O2
    PLAN -->|OrderExecute via relay| O3

    O1 -->|application REST submission| EXS
    O2 -->|application REST submission| EXS
    O3 -->|application REST submission| EXS

    O1 -.->|WS order via command handle| CMD
    O2 -.->|WS order via command handle| CMD
    O3 -.->|WS order via command handle| CMD
    CMD -.->|WS order command| EXS

    ACC -.->|state feedback| PM

Signal, model, allocator, portfolio-mediator, and execution components can all be Strategy Modules. The runtime composes them with websocket tasks, scheduler tasks, model-prediction tasks, command handles, and order-execution relays. The built-in OrderExecution task only republishes OrderExecute batches to on_order_execution; an application module performs actual REST or websocket submission.


Why HList?

A common approach stores strategies in homogeneous containers (e.g., Vec<Box<dyn Strategy>>), which means:

  • Runtime overhead due to dynamic dispatch (vtable lookups).
  • Possible type erasure issues.
  • Harder to leverage compile-time optimizations.

With HList:

  • Heterogeneous strategies (different struct types) can be stored in one container.
  • Compile-time guarantees: only strategies implementing the Strategy trait can be registered.
  • Static strategy registration: no Box<dyn Strategy> at the module-list boundary.

Strategy Execution Model

  • Trait-driven: EventHandler has one no-op callback per event type, from on_trade, on_lob, on_candle and the account streams to on_schedule, on_preds, on_order_execution, on_ws_other and on_lagged.
  • Strategy modules receive all registered tasks by default and can opt into concrete TaskKey bindings when they need a narrower hot path.
  • HList ensures safe registration of multiple strategy types.
  • All infra timestamps are unified to microseconds (µs).
  • All instrument names returned by the internal API are automatically normalized, except Hyperliquid @index spot ids, # / + outcome coins and coins of builder dexes outside the known list, which are returned raw.

For a generic end-to-end wiring guide with scheduler, websocket, account-stream, and multi-module examples, see docs/usage.md.

Instrument naming conventions:

  • Crypto: underscore-separated, e.g., BTC_USDT_PERP

Strategy Traits

The extrema_infra crate provides the core traits to implement trading strategies:

  • Strategy
    Entry point of your strategy. Defines how it executes and spawns tasks.

  • EventHandler

    • handle timer or alternative task events.
    • handle Limit Order Book (LOB) events like trades, orderbook, candles, account orders.
    • handle asynchronous model prediction events.
    • handle on_lagged(key, skipped) when the module fell behind and lost events.
  • CommandEmitter
    Used to initialize and register command handles for communication with tasks.

A minimal strategy must implement at least Strategy + CommandEmitter + EventHandler.


ONNX Model Runner

extrema_infra supports local ONNX inference through AltTaskType::ModelPreds(ModelRunner::Onnx(...)). Enable the model_onnx feature, or model_runner / all, to make this backend available.

  • The ONNX model is loaded once during task initialization.
  • Inference requests are routed through a dedicated worker thread owned by the ONNX task.
  • Callers send an AltTensor feature payload and receive an AltTensor prediction payload.
  • An inference that takes longer than 20 s is skipped with a warning.
  • Like every alt task, the runner starts 5 s after the runtime launches.
  • For multi-output models, select a specific output with output_index. Otherwise, the runner prefers the first f32 or f64 output; if neither is present, it selects the first output that can be converted to f32.

You can initialize the runner in two ways:

  1. Pass a direct .onnx path.
  2. Pass a JSON config path:
{
  "model_path": "models/demo.onnx",
  "model_name": "demo_model",
  "output_index": 0
}

The JSON config supports:

  • model_path: required; a relative path is resolved against the directory of the JSON config
  • model_name: optional, defaults to the file stem of the config (or of the direct .onnx path)
  • output_index: optional, useful for multi-output models such as classifier label + probability outputs

Predictions carry model_name and the selected output_index in AltTensor::metadata.

AltTensor Contract

AltTensor is a generic dense tensor carrier:

  • timestamp: data time in microseconds
  • data: row-major / C-order flattened Vec<f32>
  • shape: original tensor shape before flattening
  • metadata: free-form string labels such as model, instrument or threshold
  • data.len() must equal the product of shape
  • infra does not perform implicit transpose / squeeze / reshape

Typical examples:

  • Tabular feature row: shape=[1, 4], data=[f1, f2, f3, f4]
  • Multi-asset feature row: shape=[1, assets, features]
  • Conv input: shape=[1, 1, 3, 3]
  • Regression output: shape=[1, 1]
  • Classification probabilities: shape=[1, classes]

When exporting from PyTorch, the intended semantics are equivalent to:

tensor = tensor.to(torch.float32).contiguous()
data = tensor.view(-1).tolist()
shape = list(tensor.shape)

LOB Exchange API Traits

These traits apply to LOB-based exchanges such as Binance, OKX, Gate, and Hyperliquid.

Client implementors use these traits to expose exchange capabilities. Applications can use the built-in clients directly or dispatch through LobClients. Operations that a selected client does not support return InfraError::Unimplemented.

  • LobWebsocket
    Defines how to build subscription/connect messages for websocket streams.

  • MarketLobApi = LobPublicRest + LobPrivateRest

    • LobPublicRest: market data (ticker, mark price, orderbook, candles, instruments).
    • LobPrivateRest: trading operations (init API key, place/cancel orders, open orders, order history, single-order lookup, get balance, get positions).
  • LobWsDecoder
    Runs a venue implemented outside this crate on the built-in websocket relay. Register it with EnvBuilder::with_ws_decoder and declare its tasks on Market::Custom(id); its frames reach the same callbacks as the built-in venues.


TLS / rustls Initialization

This framework relies on rustls for secure REST and WebSocket connections (e.g. via reqwest and tokio-tungstenite).

When exactly one built-in provider feature is enabled, rustls 0.23 can select it automatically. A final binary can still install a provider explicitly before creating REST or websocket clients to pin the process-wide choice:

#[tokio::main]
async fn main() { 
  rustls::crypto::aws_lc_rs::default_provider()
          .install_default()
          .expect("failed to install rustls crypto provider");

  // start tokio runtime, env builder, etc.
}

Explicit selection is necessary when the dependency graph enables zero or multiple built-in providers, or when the application uses a custom provider. Provider installation belongs in the final binary because rustls allows only one process-wide default provider.


Example: Spawn example strategy

Install the latest published crate:

cargo add extrema_infra --features all

In your strategy Cargo.toml:

[package]
name = "strategy"
version = "0.1.0"
edition = "2024"

[dependencies]
extrema_infra = { version = "0.7", features = ["all"] }

# For local development.
# extrema_infra = { path = "../extrema_infra", features = ["all"] }

# Tokio async runtime
tokio = { version = "1.54", features = ["full"] }

# TLS / Cryptography
rustls = { version = "0.23", features = ["aws-lc-rs"] }

# Logging
tracing = "0.1"
tracing-subscriber = "0.3"

Then in main.rs:

use std::{sync::Arc, time::Duration};
use tracing::info;

use extrema_infra::prelude::*;

#[derive(Clone)]
struct EmptyStrategy;

impl Strategy for EmptyStrategy {
  async fn initialize(&mut self) {
    info!("[EmptyStrategy] Executing...");
  }
}

impl CommandEmitter for EmptyStrategy {
  fn command_init(&mut self, _registry: Arc<CommandRegistry>) {
    info!("[EmptyStrategy] Command channel initialized");
  }

  fn command_registry(&self) -> Arc<CommandRegistry> {
    // Safe here because this example never sends commands.
    Arc::new(CommandRegistry::default())
  }
}

impl EventHandler for EmptyStrategy {
  async fn on_schedule(&mut self, msg: InfraMsg<AltScheduleEvent>) {
    info!("[EmptyStrategy] AltEventHandler: {:?}", msg);
  }
}

#[tokio::main]
async fn main() -> InfraResult<()> {
  tracing_subscriber::fmt::init();
  info!("Logger initialized");

  let alt_task = AltTaskInfo {
    alt_task_type: AltTaskType::TimeScheduler(Duration::from_secs(5)),
    chunk: 1,
    task_base_id: None,
  };

  let env = EnvBuilder::new()
          .with_task(alt_task)
          .with_strategy_module(EmptyStrategy)
          .build()?;

  env.execute().await;
  Ok(())
}

Latency-sensitive ML strategy

For a practical implementation, see the complex strategy example.

  • Latency-sensitive module

    • Receives execution requests and can implement placement, cancel/replace, LOB reaction, and other application logic.
    • The example logs relayed execution requests; exchange submission is omitted.
    • Minimal logic, no blocking, no heavy computation.
    • Samples only the data needed by the fast path.
  • Supporting tasks

    • Feature generation, risk checks, position management, and evaluation.
    • These tasks communicate with the latency-sensitive module through channels (CommandEmitter -> OrderExecution relay) and task-local state.
    • Use AltTask for feature extraction, sending data to a ZMQ or ONNX model runner via command handle, then generating signals to execute orders.

Latency-sensitive logic can be decomposed into multiple tasks, with each task handling only a subset of instruments for maximum efficiency.


License

This project is licensed under the Apache 2.0 license.

Explorar proyectos relacionados

Cargando…