Skip to main content

Crate rithmic_rs

Crate rithmic_rs 

Source
Expand description

§rithmic-rs

rithmic-rs is a Rust client library for the Rithmic R | Protocol API.

§Features

  • Stream real-time market data (trades, quotes, order book depth)
  • Submit and manage orders (bracket orders, modifications, cancellations)
  • Access historical market data (ticks and time bars)
  • Manage risk and track positions and P&L
  • Connection health monitoring with heartbeat and forced logout handling

§Quick Start

use rithmic_rs::{
    RithmicConfig, RithmicEnv, ConnectStrategy, RithmicTickerPlant,
    rti::messages::RithmicMessage,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load configuration from environment variables
    let config = RithmicConfig::from_env(RithmicEnv::Demo)?;

    // Connect with Retry strategy (recommended default)
    let ticker_plant = RithmicTickerPlant::connect(&config, ConnectStrategy::Retry).await?;
    let mut handle = ticker_plant.get_handle();

    // Login and subscribe to market data
    handle.login().await?;
    handle.subscribe("ESM6", "CME").await?;

    // Process real-time updates
    loop {
        match handle.subscription_receiver.recv().await {
            Ok(update) => {
                // Check for connection health issues
                if let Some(err) = &update.error {
                    eprintln!("Error: {}", err);
                    if err.is_connection_issue() { break; }
                    continue;
                }

                // Process market data
                match update.message {
                    RithmicMessage::LastTrade(trade) => {
                        println!("Trade: {:?}", trade);
                    }
                    RithmicMessage::BestBidOffer(bbo) => {
                        println!("BBO: {:?}", bbo);
                    }
                    _ => {}
                }
            }
            Err(e) => {
                eprintln!("Channel error: {}", e);
                break;
            }
        }
    }

    Ok(())
}

§Connection Strategies

The library provides three connection strategies:

A graceful disconnect().await logs out first and then closes the WebSocket. On a healthy connection, that shutdown path does not emit synthetic HeartbeatTimeout or ConnectionError subscription updates; reserve those for unexpected connection-health failures and reconnect logic.

§Configuration

Use RithmicConfig for modern, ergonomic configuration:

use rithmic_rs::{RithmicAccount, RithmicConfig, RithmicEnv};

fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // From environment variables
    let config = RithmicConfig::from_env(RithmicEnv::Demo)?;
    let account = RithmicAccount::from_env(RithmicEnv::Demo)?;

    // Or using builder pattern
    let config = RithmicConfig::builder(RithmicEnv::Demo)
        .user("your_user".to_string())
        .password("your_password".to_string())
        .system_name("Rithmic Paper Trading".to_string())
        .app_name("your_app_name".to_string())
        .app_version("1".to_string())
        .build()?;

    let account = RithmicAccount::new("your_fcm", "your_ib", "your_account");
    let _ = (config, account);
    Ok(())
}

§Error Handling

All plant handle methods return Result<_, RithmicError>. The RithmicError enum lets you programmatically distinguish error kinds:

use rithmic_rs::RithmicError;

match handle.subscribe("ESM6", "CME").await {
    Ok(resp) => { /* success */ }
    Err(RithmicError::ConnectionClosed | RithmicError::SendFailed) => {
        handle.abort();
        // reconnect — see examples/reconnect.rs
    }
    Err(RithmicError::RequestRejected(err)) => {
        eprintln!(
            "Server rejected: code={} msg={}",
            err.code.as_deref().unwrap_or("?"),
            err.message.as_deref().unwrap_or(""),
        );
    }
    Err(RithmicError::ProtocolError(msg)) => {
        eprintln!("Protocol error: {msg}");
    }
    Err(e) => eprintln!("{e}"),
}

For inspecting a RithmicResponse directly, match on response.error — it is Option<RithmicError> with RequestRejected for rp_code rejections and ProtocolError for other non-transport failures. Use RithmicError::is_connection_issue to distinguish transport-level events that warrant reconnection. The raw rp_code payload is available via response.rp_code(), response.rp_code_num(), and response.rp_code_text().

A graceful disconnect().await is separate from that reconnect path: it shuts the plant down without sending synthetic HeartbeatTimeout or ConnectionError updates to subscribers when the close handshake succeeds.

RithmicError implements std::error::Error, so ? works in functions returning Box<dyn Error>.

§Feature Flags

FlagDefaultDescription
serdeoffAdds Serialize/Deserialize derives on trading types (RithmicEnv, OrderSide, OrderType, TimeInForce, OrderStatus, RithmicOrder, TrailingStop)

TLS backend: The crate uses native-tls (via tokio-tungstenite) for all WebSocket connections. There is currently no rustls option.

§Module Organization

  • plants: Specialized clients for different data types (ticker, order, P&L, history)
  • config: Configuration API for connecting to Rithmic
  • error: Typed error enum for plant handle methods
  • api: Low-level API interfaces for sending and receiving messages
  • rti: Protocol message definitions
  • ws: WebSocket connectivity and connection strategies
  • util: Utility types and helpers (timestamps, order status, instrument info)

Re-exports§

pub use plants::history_plant::RithmicHistoryPlant;
pub use plants::history_plant::RithmicHistoryPlantHandle;
pub use plants::order_plant::RithmicOrderPlant;
pub use plants::order_plant::RithmicOrderPlantHandle;
pub use plants::pnl_plant::RithmicPnlPlant;
pub use plants::pnl_plant::RithmicPnlPlantHandle;
pub use plants::ticker_plant::RithmicTickerPlant;
pub use plants::ticker_plant::RithmicTickerPlantHandle;
pub use config::ConfigError;
pub use config::RithmicAccount;
pub use config::RithmicConfig;
pub use config::RithmicConfigBuilder;
pub use config::RithmicEnv;
pub use error::RithmicError;
pub use error::RithmicRequestError;
pub use ws::ConnectStrategy;
pub use api::BracketCondition;
pub use api::BracketDuration;
pub use api::BracketPriceField;
pub use api::BracketPriceType;
pub use api::BracketTransactionType;
pub use api::BracketType;
pub use api::EasyToBorrowRequest;
pub use api::LoginConfig;
pub use api::ModifyPriceType;
pub use api::NewOrderDuration;
pub use api::NewOrderPriceType;
pub use api::NewOrderTransactionType;
pub use api::OcoDuration;
pub use api::OcoPriceType;
pub use api::OcoTransactionType;
pub use api::RithmicAdvancedBracketOrder;
pub use api::RithmicBracketOrder;
pub use api::RithmicCancelOrder;
pub use api::RithmicIfTouchedTrigger;
pub use api::RithmicModifyOrder;
pub use api::RithmicOcoOrderLeg;
pub use api::RithmicOrder;
pub use api::RithmicResponse;
pub use api::TrailingStop;
pub use util::InstrumentInfo;
pub use util::InstrumentInfoError;
pub use util::OrderStatus;
pub use util::rithmic_to_unix_nanos;
pub use util::rithmic_to_unix_nanos_precise;
pub use types::OrderSide;
pub use types::OrderType;
pub use types::ParseOrderSideError;
pub use types::ParseOrderTypeError;
pub use types::ParseTimeInForceError;
pub use types::TimeInForce;

Modules§

api
Low-level API types for Rithmic communication.
config
Configuration API for connecting to Rithmic Configuration for Rithmic connections.
error
Error types for plant handle methods.
plants
Specialized clients (“plants”) for different Rithmic services.
rti
Rithmic protocol message definitions (protobuf-generated).
types
High-level trading types with optional serde support. Order enums with serde support and protobuf conversions.
util
Utility types for working with Rithmic data. Utility types for working with Rithmic data.
ws
WebSocket connectivity layer