Skip to main content

Crate thetadatadx

Crate thetadatadx 

Source
Expand description

§thetadatadx

Native Rust SDK for ThetaData market data. Historical data via ThetaData’s MDDS service, real-time streaming via ThetaData’s FPSS service, and bulk flat-file pulls — all through a single authenticated client, without a JVM, subprocess, or local proxy.

Requires a valid ThetaData subscription.

§Quick start

use thetadatadx::{Client, Credentials, DirectConfig};
use thetadatadx::streaming::{StreamEvent, StreamData};
use thetadatadx::streaming::Contract;

let creds = Credentials::from_file("creds.txt")?;
let client = Client::connect(&creds, DirectConfig::production()).await?;

// Market-data — every query endpoint on the `market-data` surface
let ticks = client.market_data().stock_history_eod("AAPL", "20240101", "20240301").await?;

// Real-time streaming — on the `stream` surface
client.stream().start_streaming(|event: &StreamEvent| {
    if let StreamEvent::Data(StreamData::Trade { contract, price, size, .. }) = event {
        println!("Trade: {} @ {price} x {size}", contract.symbol);
    }
})?;
client.stream().subscribe(Contract::stock("AAPL").quote())?;

// Bulk flat files — on the `flat_files` surface, decoded in memory
let rows = client.flat_files().option_trade_quote("20240115").await?;

For streaming-only workloads, build an streaming::StreamingClient directly and iterate events on the caller’s thread:

use thetadatadx::streaming::{StreamingClient, StreamEvent};
use thetadatadx::{Credentials, DirectConfig};
use thetadatadx::streaming::Contract;

let creds = Credentials::new("user@example.com", "pw");
let config = DirectConfig::production();
let hosts = config.streaming_hosts();

let client = StreamingClient::builder(&creds, hosts)
    .build()?;

client.subscribe(Contract::stock("AAPL").quote())?;

for event in &client {
    let _event: StreamEvent = event?;
}

client.next_event() blocks until the next event or terminal shutdown; try_next_event is the non-blocking variant; poll_batch(FnMut) and for_each(FnMut) are the closure-driven shapes.

For market-data-only workloads, build a market_data::MarketDataClient directly and query endpoints on it:

use thetadatadx::market_data::MarketDataClient;
use thetadatadx::{Credentials, DirectConfig};

let creds = Credentials::from_file("creds.txt")?;
let client = MarketDataClient::connect(&creds, DirectConfig::production()).await?;

let eod = client.stock_history_eod("AAPL", "20240101", "20240301").await?;
println!("{} EOD ticks", eod.len());

§Data delivery

Historical data arrives over ThetaData’s MDDS service; real-time ticks arrive over ThetaData’s FPSS service. Both are decoded inside the crate — consumers see typed tick rows on the market-data side and a typed streaming::StreamEvent stream on the streaming side.

Re-exports§

pub use auth::Credentials;
pub use backoff::JitterMode;
pub use config::BulkFetchPolicy;
pub use config::DirectConfig;
pub use config::FlatFilesConfig;
pub use config::MarketDataEnvironment;
pub use config::ReconnectAttemptClass;
pub use config::ReconnectAttemptLimits;
pub use config::ReconnectPolicy;
pub use config::RetryPolicy;
pub use config::RuntimeConfig;
pub use config::StreamingEnvironment;
pub use config::WaitMode;
pub use error::AuthErrorKind;
pub use error::ConfigErrorKind;
pub use error::DecodeErrorKind;
pub use error::DecompressErrorKind;
pub use error::Error;
pub use error::GrpcStatusKind;
pub use error::StreamErrorKind;
pub use error::TransportErrorKind;
pub use crate::columns::ColumnPresence;
pub use crate::columns::Ticks;
pub use crate::columns::WireColumns;
pub use right::parse_right;
pub use right::parse_right_strict;
pub use right::ParsedRight;
pub use right::RightError;
pub use flatfiles_api::*;

Modules§

auth
Authentication for ThetaData direct server access.
backoff
Shared backoff and jitter primitives for every retry surface in the SDK: the streaming reconnect driver, the market-data-channel retry policy, the market-data-channel transport reconnect, and the flatfile retry loop.
columns
Per-response column presence — the wire’s actual column set for one decoded response.
config
Server configuration for direct ThetaData access.
error
The crate’s public Error type and its category enums.
flatfiles
FLATFILES: whole-universe daily snapshots over the legacy MDDS port. Pulls one INDEX + DATA blob per (SecType, ReqType, date) tuple and emits CSV, JSONL, or Vec<FlatFileRow>.
flatfiles_api
Bulk flat-file downloads from ThetaData’s flat-file distribution.
frames_apiarrow or polars
DataFrame conversion for tick slices.
market_data
Market-data query consumer surface.
prelude
Convenience re-exports for the contract-first streaming API.
right
Canonical parser for the option right parameter.
streaming
Real-time streaming consumer surface.
util
Cross-cutting utilities shared by multiple subsystems.
utils
Auxiliary lookup tables.

Structs§

CalendarDay
Calendar day – 4 fields. Market open/close schedule.
Client
Unified ThetaData client.
ClientBuilder
Fluent builder for Client.
EodTick
End-of-day tick – 20 fields. Full EOD snapshot with OHLC + quote.
FlatFiles
Borrowed view exposing a client’s flat-files surface.
GreeksAllTick
Full union Greeks tick – every Greek the v3 server publishes on the option_*_greeks_all and option_*_greeks_eod endpoints.
GreeksEodTick
End-of-day union Greeks tick – every Greek the v3 server publishes on option_history_greeks_eod, paired with the twelve EOD trade/quote context columns (open, high, low, close, volume, count, bid_size, bid_exchange, bid_condition, ask_size, ask_exchange, ask_condition) that identify the daily bar + closing NBBO snapshot the Greeks were calculated against.
GreeksFirstOrderTick
First-order Greeks tick – the strict column subset emitted by the vendor’s option_*_greeks_first_order endpoints (delta / theta / vega / rho / epsilon / lambda) plus the bid/ask quote pair, the IV pair, and the underlying snapshot used to derive each Greek.
GreeksSecondOrderTick
Second-order Greeks tick – the strict column subset emitted by the vendor’s option_*_greeks_second_order endpoints (gamma / vanna / charm / vomma / veta) plus the bid/ask quote pair, the IV pair, and the underlying snapshot.
GreeksThirdOrderTick
Third-order Greeks tick – the strict column subset emitted by the vendor’s option_*_greeks_third_order endpoints (speed / zomma / color / ultima) plus the bid/ask quote pair, the IV pair, and the underlying snapshot. The vendor’s third-order schema does not publish vera.
IndexPriceAtTimeTick
Index price-at-time tick – the trade-shaped row the v3 server publishes on index_at_time_price. The bare PriceTick (3 fields: ms_of_day, price, date) silently dropped seven server-emitted columns – sequence, ext_condition1..4, condition, size, exchange – including the SIP-exchange attribution field.
InterestRateTick
Interest rate tick – 2 fields. End-of-day interest rate (percent).
IvTick
Implied volatility tick – 14 fields.
MarketDataClientNon-__internal
Standalone market-data query client.
MarketValueTick
Market value tick – quoted bid/ask/price for a symbol.
OhlcTick
OHLC tick – 12 fields. Aggregated bar data including SIP-rule VWAP.
OpenInterestTick
Open interest tick – 6 fields.
OptionContract
Option contract – 4 fields. Contract specification.
PriceTick
Price tick – 3 fields. Generic price data point.
QuoteTick
Quote tick – 13 fields. NBBO quote data.
ShardPlanNon-__internal
Bulk-fetch shard planning (manual mode): describe a history query as a ShardQuery, obtain the balanced ShardPlan via MarketDataClient::bulk_fetch_plan, and run the ShardBand sub-requests under your own concurrency. The automatic path (BulkFetchPolicy::Auto) uses exactly these plans. A balanced fan-out plan for one logical history query: the per-shard band overrides, in output order.
ShardQueryNon-__internal
Bulk-fetch shard planning (manual mode): describe a history query as a ShardQuery, obtain the balanced ShardPlan via MarketDataClient::bulk_fetch_plan, and run the ShardBand sub-requests under your own concurrency. The automatic path (BulkFetchPolicy::Auto) uses exactly these plans. Wire-level view of a history query, as consumed by the shard planner.
StreamSurface
Borrowed view exposing the unified Client’s streaming surface.
SubscriptionInfo
Subscription tier information captured at authentication time.
TradeGreeksAllTick
Per-trade union Greeks tick – every Greek the v3 server publishes on option_history_trade_greeks_all, paired with the trade-side execution columns (sequence, ext_condition1..4, condition, size, exchange, price) that identify which OPRA print each Greek was calculated against.
TradeGreeksFirstOrderTick
Per-trade first-order Greeks tick (delta / theta / vega / rho / epsilon / lambda) paired with the trade-side execution columns identifying the OPRA print each Greek was calculated against.
TradeGreeksImpliedVolatilityTick
Per-trade implied-volatility tick (single implied_volatility + iv_error pair, NOT the bid/mid/ask IV triple of the interval-sampled IvTick) paired with the trade-side execution columns identifying the OPRA print the IV was calculated against.
TradeGreeksSecondOrderTick
Per-trade second-order Greeks tick (gamma / vanna / charm / vomma / veta) paired with the trade-side execution columns identifying the OPRA print each Greek was calculated against.
TradeGreeksThirdOrderTick
Per-trade third-order Greeks tick (speed / zomma / color / ultima) paired with the trade-side execution columns identifying the OPRA print each Greek was calculated against. The vendor’s third-order schema does not publish vera.
TradeQuoteTick
Combined trade + quote tick – 27 fields.
TradeTick
Trade tick – 18 fields. Core unit of trade data.

Enums§

ChunkErrorNon-__internal
Date-range split math for history requests beyond the server’s 365-day cap: split_date_range divides an inclusive (start, end) span into contiguous server-accepted chunks. Also exposed to Python as thetadatadx.split_date_range. Failure modes of the date-range split.
ConnectionStatus
Current state of the streaming connection.
Interval
Wire string enum Interval.
PollOutcome
Outcome of a single streaming::StreamingClient::poll_batch call, re-exported at the crate root for callers that drive the batch loop directly. Outcome of a single non-blocking StreamingClient::poll_batch drain.
RateType
Wire string enum RateType.
RemoveReason
Disconnect reason codes.
RequestType
Wire string enum RequestType.
Right
Wire string enum Right.
SecType
Security type identifier.
ShardBandNon-__internal
Bulk-fetch shard planning (manual mode): describe a history query as a ShardQuery, obtain the balanced ShardPlan via MarketDataClient::bulk_fetch_plan, and run the ShardBand sub-requests under your own concurrency. The automatic path (BulkFetchPolicy::Auto) uses exactly these plans. One shard’s filter override. Applied onto a clone of the original wire parameters; every other parameter is forwarded verbatim, so each shard is a normal terminal-parity query.
StreamMsgType
Streaming message types for real-time data.
StreamResponseType
Streaming subscription response.
SubscriptionTierNon-__internal
Standalone market-data query client.
Venue
Wire string enum Venue.
Version
Wire string enum Version.

Functions§

split_date_rangeNon-__internal
Date-range split math for history requests beyond the server’s 365-day cap: split_date_range divides an inclusive (start, end) span into contiguous server-accepted chunks. Also exposed to Python as thetadatadx.split_date_range. Split (start, end) (YYYYMMDD strings, inclusive on both ends) into chunks that each span at most 365 days. The returned chunks are contiguous and cover the full range exactly once.