Skip to main content

Crate thetadatadx

Crate thetadatadx 

Source
Expand description

§thetadatadx — No-JVM ThetaData Terminal

Native Rust SDK that connects directly to ThetaData’s upstream servers, eliminating the Java terminal entirely. No JVM, no subprocess, no local proxy — just your application speaking the same wire protocol the terminal uses.

§Data types live in tdbe

Tick types (TradeTick, EodTick, …), Price, enums (SecType, DataType), the FIT/FIE codecs, and the Greeks calculator have been extracted into the tdbe crate. This crate re-exports what it needs, but if you only want types and offline Greeks, depend on tdbe directly.

§Architecture

ThetaData exposes two upstream services:

  • MDDS (Market Data Distribution Server) — historical data via gRPC at mdds-01.thetadata.us:443
  • FPSS (Feed Processing Streaming Server) — real-time streaming via custom TCP at nj-a.thetadata.us:20000

This crate speaks both protocols natively, handling authentication, request building, response decompression, and tick parsing entirely in Rust.

§Quick Start

The recommended entry point is ThetaDataDxClient, which authenticates once and provides both historical and streaming through a single object:

use thetadatadx::{ThetaDataDxClient, Credentials, DirectConfig};
use thetadatadx::fpss::{FpssData, FpssControl, FpssEvent};
use thetadatadx::fpss::protocol::Contract;

#[tokio::main]
async fn main() -> Result<(), thetadatadx::Error> {
    let creds = Credentials::from_file("creds.txt")?;
    // Or inline: let creds = Credentials::new("user@example.com", "your-password");

    // Connect -- authenticates once, historical ready immediately
    let tdx = ThetaDataDxClient::connect(&creds, DirectConfig::production()).await?;

    // Historical (MDDS gRPC) -- every generated method via Deref
    let ticks = tdx.stock_history_eod("AAPL", "20240101", "20240301").await?;

    // Streaming (FPSS TCP) -- connects lazily on first call
    tdx.start_streaming(|event: &FpssEvent| {
        match event {
            FpssEvent::Data(FpssData::Trade { contract, price, size, .. }) => {
                println!("Trade: {} @ {price} x {size}", contract.symbol);
            }
            _ => {}
        }
    })?;

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

    // ... when done:
    tdx.stop_streaming();
    Ok(())
}

For historical-only usage, just skip start_streaming() – every historical methods are available directly on ThetaDataDxClient via Deref<Target = MddsClient>:

use thetadatadx::{ThetaDataDxClient, Credentials, DirectConfig};

let creds = Credentials::from_file("creds.txt")?;
// Or inline: let creds = Credentials::new("user@example.com", "your-password");
let tdx = ThetaDataDxClient::connect(&creds, DirectConfig::production()).await?;
let ticks = tdx.stock_history_eod("AAPL", "20240101", "20240301").await?;

§Wire protocol

  • Proto definitions: crates/thetadatadx/proto/mdds.proto — single BetaEndpoints package, 60 RPCs, BetaThetaTerminal service.

  • Auth flow: POST to https://nexus-api.thetadata.us/identity/terminal/auth_user with header TD-TERMINAL-KEY and JSON {email, password}SessionInfoV3 with UUID.

  • MDDS: Standard gRPC server-streaming over TLS. Session UUID embedded in QueryInfo.auth_token field of every request (in-band, not metadata).

  • FPSS: Custom TLS-over-TCP protocol. 1-byte length + 1-byte message code + payload. FIT nibble encoding (4-bit variable-length integers) with delta compression for ticks.

See proto/MAINTENANCE.md for how to update the proto file and regenerate stubs when ThetaData ships a new version.

Re-exports§

pub use mdds::endpoint_args as endpoint;
pub use mdds::decode;
pub use auth::Credentials;
pub use fpss::protocol::Contract;
pub use fpss::protocol::ContractParseError;
pub use fpss::protocol::FullSubscriptionKind;
pub use fpss::protocol::SecTypeExt;
pub use fpss::protocol::Subscription;
pub use fpss::protocol::SubscriptionKind;
pub use fpss::EventIterator;
pub use fpss::NextEvent;
pub use config::DirectConfig;
pub use config::FpssFlushMode;
pub use config::ReconnectPolicy;
pub use error::AuthErrorKind;
pub use error::Error;
pub use error::FpssErrorKind;
pub use flatfiles::default_output_filename as flatfile_default_filename;
pub use flatfiles::flatfile_request;
pub use flatfiles::flatfile_request_decoded;
pub use flatfiles::flatfile_request_raw;
pub use flatfiles::FlatFileFormat;
pub use flatfiles::FlatFileRow;
pub use flatfiles::FlatFileValue;
pub use flatfiles::FlatFilesUnavailableReason;
pub use flatfiles::ReqType as FlatFileReqType;
pub use flatfiles::SecType as FlatFileSecType;
pub use mdds::endpoint_args::EndpointArgValue;
pub use mdds::endpoint_args::EndpointArgs;
pub use mdds::endpoint_args::EndpointError;
pub use mdds::endpoint_args::EndpointOutput;
pub use mdds::MddsClient;
pub use mdds::SubscriptionTier;

Modules§

auth
Authentication for ThetaData direct server access.
config
Server configuration for direct ThetaData access.
error
flatfiles
FLATFILES surface: whole-universe daily snapshots over the legacy MDDS port.
fpss
FPSS (Feed Processing Streaming Server) real-time streaming client.
framespolars or arrow
DataFrame ergonomics for Rust consumers — .to_polars() / .to_arrow() extension traits on slices of tick rows.
mdds
MDDS (Market Data Distribution Server) gRPC client.
observability
Optional Prometheus exporter for the metrics crate recorders.
prelude
Convenience prelude for the fluent contract-first API.
utils
wire
gRPC wire-payload re-exports for offline-decode callers.

Structs§

CalendarDay
Calendar day – 5 fields. Market open/close schedule.
EndpointMeta
Metadata for a single endpoint.
EodTick
End-of-day tick – 17 fields. Full EOD snapshot with OHLC + quote.
GreeksAllTick
Full union Greeks tick – every Greek the v3 server publishes on the option_*_greeks_all and option_*_greeks_eod endpoints.
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.
GreeksResult
All Greeks computed in a single struct.
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.
InterestRateTick
Interest rate tick – 3 fields. End-of-day interest rate.
IvTick
Implied volatility tick – 4 fields.
MarketValueTick
Market value tick – quoted bid/ask/price for a symbol.
OhlcTick
OHLC tick – 8 fields. Aggregated bar data.
OpenInterestTick
Open interest tick – 3 fields.
OptionContract
Option contract – 4 fields. Contract specification.
ParamMeta
Metadata for a single parameter.
Price
Fixed-point price with variable decimal precision.
PriceTick
Price tick – 3 fields. Generic price data point.
QuoteTick
Quote tick – 10 fields + midpoint. NBBO quote data.
SubscriptionInfo
Subscription tier information captured at authentication time.
ThetaDataDxClient
Unified ThetaData client.
TradeQuoteTick
Combined trade + quote tick – 24 fields.
TradeTick
Trade tick – 15 fields. Core unit of trade data.

Enums§

ConnectionStatus
Current state of the streaming connection.
DataType
Data field types returned in responses.
Interval
Wire string enum Interval.
ParamType
ParsedRight
Parsed representation of the option right parameter.
RateType
Wire string enum RateType.
RemoveReason
Disconnect reason codes.
RequestType
Wire string enum RequestType.
ReturnType
Right
Wire string enum Right.
SecType
Security type identifier.
StreamMsgType
Streaming message types for real-time data.
StreamResponseType
Streaming subscription response.
Venue
Wire string enum Venue.
Version
Wire string enum Version.

Constants§

CATEGORIES

Statics§

ENDPOINTS

Functions§

all_greeks
Compute all 23 Greeks at once with maximally shared intermediates.
by_category
All endpoints in a category.
find
Find an endpoint by its method name.
implied_volatility
Implied volatility solver using bisection. Returns (iv, error) on success.
param_type_to_json_type
parse_right
Parse a user-supplied right string.
parse_right_strict
Parse a right that must resolve to a single side (call or put).