### Install MCP server from source Source: https://userfrm.github.io/ThetaDataDx/mcp Build and install the server directly using Cargo if you have a Rust toolchain. ```bash cargo install thetadatadx-mcp-server --git https://github.com/userFRM/ThetaDataDx ``` -------------------------------- ### Initialize Python client Source: https://userfrm.github.io/ThetaDataDx/streaming Basic setup for the Python client using credentials and production configuration. ```python from thetadatadx import Config, Contract, Credentials, Client creds = Credentials.from_file("creds.txt") client = Client(creds, Config.production()) ``` -------------------------------- ### Install SDK Packages Source: https://userfrm.github.io/ThetaDataDx Commands to install the ThetaDataDx SDKs for Python, TypeScript, and Rust. ```bash pip install thetadatadx-py # Python 3.12+ npm install thetadatadx-ts # Node.js 20+ cargo add thetadatadx-rs # Rust async client ``` -------------------------------- ### Install ThetaDataDx Dependencies Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Installation commands for various programming environments. ```toml # Cargo.toml [dependencies] thetadatadx-rs = "0.2.0" ``` ```bash pip install thetadatadx-py # Optional DataFrame adapters: pip install "thetadatadx-py[pandas]" # pandas pip install "thetadatadx-py[polars]" # polars pip install "thetadatadx-py[arrow]" # pyarrow only ``` ```bash npm install thetadatadx-ts ``` ```bash # Prerequisites: C++17 compiler, CMake 3.16+, Rust toolchain git clone https://github.com/userFRM/ThetaDataDx.git cd ThetaDataDx cargo build --release -p thetadatadx-ffi cd thetadatadx-cpp cmake -B build && cmake --build build ``` ```bash cargo install thetadatadx-server --git https://github.com/userFRM/ThetaDataDx ``` -------------------------------- ### Start the ThetaDataDX server Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Export environment variables and launch the server process. ```bash export $(grep -v '^#' .env | xargs) thetadatadx-server & ``` -------------------------------- ### Start the ThetaDataDx Server Source: https://userfrm.github.io/ThetaDataDx/streaming Command to initialize the server process using a credentials file. ```bash thetadatadx-server --creds creds.txt & ``` -------------------------------- ### WebSocket Subscription Command Source: https://userfrm.github.io/ThetaDataDx/streaming/options/full-open-interest Example of sending a JSON subscription command via websocat. ```bash websocat ws://127.0.0.1:25520/v1/events {"msg_type": "STREAM", "sec_type": "OPTION", "req_type": "FULL_OPEN_INTEREST", "id": 1, "add": true} ``` -------------------------------- ### Open Interest JSON Response Example Source: https://userfrm.github.io/ThetaDataDx/reference/option/snapshot/open-interest Example of the JSON structure returned by the open interest snapshot endpoint. ```json [ { "open_interest": 8066, "timestamp": "2025-08-20T06:30:13" } ] ``` -------------------------------- ### Example JSON Response Source: https://userfrm.github.io/ThetaDataDx/reference/option/snapshot/greeks/first-order The structure of the returned data containing Greeks and pricing information. ```json [ { "ask": 1.5, "bid": 1.47, "delta": 0.106, "epsilon": -9.7049, "implied_vol": 0.2142, "iv_error": -0.0003, "lambda": 16.1782, "rho": 9.105, "theta": -0.0217, "timestamp": "2025-08-20T15:59:59.805", "underlying_price": 225.74, "underlying_timestamp": "2025-08-20T16:37:06.988", "vega": 26.3226 } ] ``` -------------------------------- ### Example JSON Response Source: https://userfrm.github.io/ThetaDataDx/reference/option/at-time/trade A sample JSON response structure for an option trade request. ```json [ { "condition": 130, "exchange": 22, "ext_condition1": 255, "ext_condition2": 255, "ext_condition3": 255, "ext_condition4": 255, "price": 3.9, "sequence": 18902138, "size": 2, "timestamp": "2024-11-04T09:30:00.471" } ] ``` -------------------------------- ### Connect and subscribe via websocat Source: https://userfrm.github.io/ThetaDataDx/server/websocket Command-line example using websocat to connect to the WebSocket and send a subscription request. ```bash websocat ws://127.0.0.1:25520/v1/events {"msg_type": "STREAM", "sec_type": "OPTION", "req_type": "TRADE", "id": 1, "add": true, "contract": {"symbol": "SPY", "expiration": 20250321, "strike": 570000, "right": "C"}} ``` -------------------------------- ### Execute first market data request Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Example of building a client and fetching end-of-day stock history. ```rust use thetadatadx::Client; async fn run() -> Result<(), thetadatadx::Error> { // Pass your API key directly. Add .stage() before .connect() for staging. let client = Client::builder().api_key("your_api_key").connect().await?; let rows = client.market_data().stock_history_eod("AAPL", "20250303", "20250306").await?; for t in &rows { println!("{}: open={} close={} volume={}", t.date, t.open, t.close, t.volume); } Ok(()) } ``` ```python from thetadatadx import Client ``` -------------------------------- ### Start the ThetaData server Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Launch the server process using an API key provided as a command-line flag. ```bash thetadatadx-server --api-key "your_api_key" & ``` -------------------------------- ### Pulling Flat Files Source: https://userfrm.github.io/ThetaDataDx/articles/flat-files Examples for retrieving market data archives across different programming languages. ```rust use thetadatadx::flatfiles::{FlatFileFormat, ReqType, SecType}; // Decoded rows in memory, via the `flat_files` view: let rows = client.flat_files().option_trade_quote("20250303").await?; // Generic dispatcher (same view), for config-driven call shapes: let rows = client.flat_files().request(SecType::Option, ReqType::TradeQuote, "20250303").await?; // Vendor-format file straight to disk (bounded memory): client.flat_files().to_path(SecType::Option, ReqType::TradeQuote, "20250303", "trade_quotes.csv", FlatFileFormat::Csv).await?; ``` ```python rows = client.flat_files.option_trade_quote("20250303") df = rows.to_polars() # or .to_pandas() / .to_arrow() / .to_list() # Or write the vendor-format file straight to disk (bounded memory): client.flatfile_to_path("OPTION", "TRADE_QUOTE", "20250303", "trade_quotes.csv", "csv") ``` ```typescript const rows = await client.flatFiles.optionTradeQuote('20250303'); const ipc = rows.toArrowIpc(); // feed into apache-arrow `tableFromIPC` ``` ```cpp auto rows = client.flat_files().option_trade_quote("20250303"); auto ipc = rows.to_arrow_ipc(); // std::vector ``` ```bash curl 'http://127.0.0.1:25503/v3/option/flat_file/trade_quote?date=20250303&format=csv' -o trade_quotes.csv ``` -------------------------------- ### Example JSON response for trade snapshot Source: https://userfrm.github.io/ThetaDataDx/reference/stock/snapshot/trade Sample structure of the data returned by the trade snapshot endpoint. ```json [ { "condition": 1, "price": 225.75, "sequence": 63539137, "size": 23, "symbol": "AAPL", "timestamp": "2025-08-20T16:36:05.549" } ] ``` -------------------------------- ### Define environment variables in .env format Source: https://userfrm.github.io/ThetaDataDx/articles/configuration Example of a .env file containing both API keys and environment selectors. ```ini THETADATA_API_KEY=your_api_key_here THETADATA_MARKET_DATA_TYPE=STAGE THETADATA_STREAMING_TYPE=DEV ``` -------------------------------- ### Index Price at Time JSON Response Sample Source: https://userfrm.github.io/ThetaDataDx/reference/index/at-time/price Example of the JSON structure returned by the index price at time request. ```json [ { "condition": 0, "exchange": 5, "ext_condition1": 255, "ext_condition2": 255, "ext_condition3": 255, "ext_condition4": 255, "price": 5725.15, "sequence": 0, "size": 0, "timestamp": "2024-11-04T09:30:01" }, { "condition": 0, "exchange": 5, "ext_condition1": 255, "ext_condition2": 255, "ext_condition3": 255, "ext_condition4": 255, "price": 5722.43, "sequence": 0, "size": 0, "timestamp": "2024-11-05T09:30:01" }, { "condition": 0, "exchange": 5, "ext_condition1": 255, "ext_condition2": 255, "ext_condition3": 255, "ext_condition4": 255, "price": 5864.89, "sequence": 0, "size": 0, "timestamp": "2024-11-06T09:30:01" } ] ``` -------------------------------- ### Perform an HTTP REST Request Source: https://userfrm.github.io/ThetaDataDx/server Example curl command to fetch end-of-day stock history from the local server. ```bash curl 'http://127.0.0.1:25503/v3/stock/history/eod?symbol=AAPL&start_date=2025-03-03&end_date=2025-03-06' ``` -------------------------------- ### Subscribe to Full Open Interest Source: https://userfrm.github.io/ThetaDataDx/streaming/options/full-open-interest Examples for subscribing to and unsubscribing from the full open interest stream in various programming languages. ```rust use thetadatadx::streaming::SecTypeExt; use thetadatadx::streaming::{StreamData, StreamEvent}; use thetadatadx::SecType; client.stream().start_streaming(|event: &StreamEvent| { if let StreamEvent::Data(StreamData::OpenInterest { contract, open_interest, .. }) = event { println!("{} oi={open_interest}", contract.symbol); } })?; let sub = SecType::Option.full_open_interest(); client.stream().subscribe(sub.clone())?; // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub)?; ``` ```python from thetadatadx import SecType def on_event(event): if event.kind == "open_interest": print(event.contract.symbol, event.open_interest) client.stream.start_streaming(on_event) sub = SecType.OPTION.full_open_interest() client.stream.subscribe(sub) # Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub) ``` ```typescript import { SecType } from 'thetadatadx-ts'; await client.stream.startStreaming((event) => { if (event.kind === 'open_interest') { const e = event.openInterest!; console.log(e.contract.symbol, e.openInterest); } }); const sub = SecType.option().fullOpenInterest(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub); ``` ```cpp client.stream().set_callback([](const thetadatadx::StreamEvent& event) { if (event.kind == THETADATADX_STREAM_OPEN_INTEREST) { auto& e = event.open_interest; std::cout << e.contract.symbol << " oi=" << e.open_interest << "\n"; } }); auto sub = thetadatadx::SecType::option().full_open_interest(); client.stream().subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub); ``` -------------------------------- ### Subscribe to Option Full Trades Source: https://userfrm.github.io/ThetaDataDx/streaming/options/full-trade Examples for subscribing to and handling full option trade streams across multiple programming languages. ```rust use thetadatadx::streaming::SecTypeExt; use thetadatadx::streaming::{StreamData, StreamEvent}; use thetadatadx::SecType; client.stream().start_streaming(|event: &StreamEvent| match event { StreamEvent::Data(StreamData::Quote { contract, bid, ask, .. }) => { println!("{} quote bid={bid} ask={ask}", contract.symbol); } StreamEvent::Data(StreamData::Ohlcvc { contract, open, high, low, close, .. }) => { println!("{} bar o={open} h={high} l={low} c={close}", contract.symbol); } StreamEvent::Data(StreamData::Trade { contract, price, size, .. }) => { println!("{} trade price={price} size={size}", contract.symbol); } _ => {} })?; let sub = SecType::Option.full_trades(); client.stream().subscribe(sub.clone())?; // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub)?; ``` ```python from thetadatadx import SecType def on_event(event): if event.kind == "quote": print(event.contract.symbol, "quote", event.bid, event.ask) elif event.kind == "ohlcvc": print(event.contract.symbol, "bar", event.open, event.high, event.low, event.close) elif event.kind == "trade": print(event.contract.symbol, "trade", event.price, event.size) client.stream.start_streaming(on_event) sub = SecType.OPTION.full_trades() client.stream.subscribe(sub) # Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub) ``` ```typescript import { SecType } from 'thetadatadx-ts'; await client.stream.startStreaming((event) => { switch (event.kind) { case 'quote': { const q = event.quote!; console.log(q.contract.symbol, 'quote', q.bid, q.ask); break; } case 'ohlcvc': { const b = event.ohlcvc!; console.log(b.contract.symbol, 'bar', b.open, b.high, b.low, b.close); break; } case 'trade': { const t = event.trade!; console.log(t.contract.symbol, 'trade', t.price, t.size); break; } } }); const sub = SecType.option().fullTrades(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub); ``` ```cpp client.stream().set_callback([](const thetadatadx::StreamEvent& event) { switch (event.kind) { case THETADATADX_STREAM_QUOTE: std::cout << event.quote.contract.symbol << " quote bid=" << event.quote.bid << " ask=" << event.quote.ask << "\n"; break; case THETADATADX_STREAM_OHLCVC: std::cout << event.ohlcvc.contract.symbol << " bar o=" << event.ohlcvc.open << " c=" << event.ohlcvc.close << "\n"; break; case THETADATADX_STREAM_TRADE: std::cout << event.trade.contract.symbol << " trade price=" << event.trade.price << " size=" << event.trade.size << "\n"; break; default: break; } }); auto sub = thetadatadx::SecType::option().full_trades(); client.stream().subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub); ``` -------------------------------- ### Stream Open Interest Updates Source: https://userfrm.github.io/ThetaDataDx/streaming/options/open-interest Examples for subscribing to open interest data across multiple programming languages. ```rust use thetadatadx::streaming::{Contract, OptionLeg}; use thetadatadx::streaming::{StreamData, StreamEvent}; client.stream().start_streaming(|event: &StreamEvent| { if let StreamEvent::Data(StreamData::OpenInterest { contract, open_interest, .. }) = event { println!("{} oi={open_interest}", contract.symbol); } })?; let sub = Contract::option("SPY", OptionLeg { expiration: "20260618", strike: "570", right: "C" })?.open_interest(); client.stream().subscribe(sub.clone())?; // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub)?; ``` ```python from thetadatadx import Contract def on_event(event): if event.kind == "open_interest": print(event.contract.symbol, event.open_interest) client.stream.start_streaming(on_event) sub = Contract.option("SPY", expiration="20260618", strike="570", right="C").open_interest() client.stream.subscribe(sub) # Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub) ``` ```typescript import { Contract } from 'thetadatadx-ts'; await client.stream.startStreaming((event) => { if (event.kind === 'open_interest') { const e = event.openInterest!; console.log(e.contract.symbol, e.openInterest); } }); const sub = Contract.option('SPY', { expiration: '20260618', strike: '570', right: 'C' }).openInterest(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub); ``` ```cpp client.stream().set_callback([](const thetadatadx::StreamEvent& event) { if (event.kind == THETADATADX_STREAM_OPEN_INTEREST) { auto& e = event.open_interest; std::cout << e.contract.symbol << " oi=" << e.open_interest << "\n"; } }); auto sub = thetadatadx::Contract::option("SPY", {.expiration = "20260618", .strike = "570", .right = "C"}).open_interest(); client.stream().subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub); ``` -------------------------------- ### GET ws://127.0.0.1:25520/v1/events Source: https://userfrm.github.io/ThetaDataDx/streaming/indices/price Establishes a WebSocket connection to the local streaming server to receive index price updates. ```APIDOC ## GET ws://127.0.0.1:25520/v1/events ### Description Connects to the streaming server to receive real-time trade events for indices. Subscriptions are managed by sending JSON envelopes over the established WebSocket connection. ### Method GET ### Endpoint ws://127.0.0.1:25520/v1/events ### Request Body - **msg_type** (string) - Required - Must be "STREAM" - **sec_type** (string) - Required - Must be "INDEX" - **req_type** (string) - Required - Must be "TRADE" - **id** (integer) - Required - Unique request identifier - **add** (boolean) - Required - Set to true to subscribe, false to unsubscribe - **contract** (object) - Required - Contains the symbol of the index (e.g., {"symbol": "SPX"}) ### Request Example { "msg_type": "STREAM", "sec_type": "INDEX", "req_type": "TRADE", "id": 1, "add": true, "contract": {"symbol": "SPX"} } ``` -------------------------------- ### Stream Market Value Events Source: https://userfrm.github.io/ThetaDataDx/streaming/stocks/market-value Examples for subscribing to and unsubscribing from market value updates across supported languages. ```rust use thetadatadx::streaming::Contract; use thetadatadx::streaming::{StreamData, StreamEvent}; client.stream().start_streaming(|event: &StreamEvent| { if let StreamEvent::Data(StreamData::MarketValue { contract, market_price, .. }) = event { println!("{} market_price={market_price}", contract.symbol); } })?; let sub = Contract::stock("AAPL").market_value(); client.stream().subscribe(sub.clone())?; // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub)?; ``` ```python from thetadatadx import Contract def on_event(event): if event.kind == "market_value": print(event.contract.symbol, event.market_price) client.stream.start_streaming(on_event) sub = Contract.stock("AAPL").market_value() client.stream.subscribe(sub) # Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub) ``` ```typescript import { Contract } from 'thetadatadx-ts'; await client.stream.startStreaming((event) => { if (event.kind === 'market_value') { const e = event.marketValue!; console.log(e.contract.symbol, e.marketPrice); } }); const sub = Contract.stock('AAPL').marketValue(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub); ``` ```cpp client.stream().set_callback([](const thetadatadx::StreamEvent& event) { if (event.kind == THETADATADX_STREAM_MARKET_VALUE) { auto& e = event.market_value; std::cout << e.contract.symbol << " market_price=" << e.market_price << "\n"; } }); auto sub = thetadatadx::Contract::stock("AAPL").market_value(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub); ``` -------------------------------- ### Converting to Columnar DataFrames Source: https://userfrm.github.io/ThetaDataDx/articles/flat-files Examples for converting retrieved flat file rows into Arrow, Polars, or pandas formats. ```rust let rows = client.flat_files().option_trade_quote("20250303").await?; let batch = thetadatadx::flatfiles::arrow::rows_to_arrow(&rows)?; // arrow_array::RecordBatch ``` ```python rows = client.flat_files.option_trade_quote("20250303") pl_df = rows.to_polars() # Polars DataFrame pd_df = rows.to_pandas() # pandas DataFrame table = rows.to_arrow() # pyarrow Table (zero-copy) records = rows.to_list() # list[dict] ``` ```typescript import { tableFromIPC } from "apache-arrow"; const rows = await client.flatFiles.optionTradeQuote('20250303'); const table = tableFromIPC(rows.toArrowIpc()); // apache-arrow Table ``` ```cpp auto rows = client.flat_files().option_trade_quote("20250303"); std::vector ipc = rows.to_arrow_ipc(); // feed arrow::ipc::RecordBatchStreamReader ``` -------------------------------- ### Initialize Client with Advanced Configuration Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Connect using environment variables, .env files, or email/password credentials for staging environments. ```rust // Source the key from THETADATA_API_KEY, or from a .env file. let client = thetadatadx::Client::builder().api_key_from_env().connect().await?; let client = thetadatadx::Client::builder().api_key_from_dotenv(".env").connect().await?; // Email and password inline, staging environment. let client = thetadatadx::Client::builder() .email_password("you@example.com", "your-password") .stage() .connect() .await?; ``` ```python # Source the key from THETADATA_API_KEY, or from a .env file. client = Client.from_env() client = Client.from_dotenv(".env") # Email and password inline, staging environment. client = Client(email="you@example.com", password="your-password", market_data_type="STAGE") ``` ```typescript // Source the key from THETADATA_API_KEY, or from a .env file. const fromEnv = await Client.connectWith({ apiKeyFromEnv: true }); const fromDotenv = await Client.connectWith({ apiKeyFromDotenv: '.env' }); // Email and password inline, staging environment. const withLogin = await Client.connectWith({ email: 'you@example.com', password: 'your-password', marketDataType: 'STAGE', }); ``` ```cpp // Source the key from THETADATA_API_KEY, or from a .env file. auto fromEnv = thetadatadx::Client::builder().api_key_from_env().connect(); auto fromDotenv = thetadatadx::Client::builder().api_key_from_dotenv(".env").connect(); // Email and password inline, staging environment. auto staged = thetadatadx::Client::builder() .email_password("you@example.com", "your-password") .stage() .connect(); ``` -------------------------------- ### Initialize Client with API Key Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Connect to the production environment using an inline API key. ```python client = Client(api_key="your_api_key") ``` ```typescript // API key inline, production by default. const client = await Client.connectWith({ apiKey: 'your_api_key' }); ``` ```cpp // API key inline, production by default. auto client = thetadatadx::Client::builder() .api_key("your_api_key") .connect(); ``` ```bash thetadatadx-server --api-key "your_api_key" & ``` -------------------------------- ### Build and run ThetaDataDx server from source Source: https://userfrm.github.io/ThetaDataDx/server Use these commands to install the server binary via Cargo and execute it using a credentials file. ```bash cargo install thetadatadx-server --git https://github.com/userFRM/ThetaDataDx thetadatadx-server --creds creds.txt ``` -------------------------------- ### GET /v3/terminal/shutdown Source: https://userfrm.github.io/ThetaDataDx/server/http Kills the server process. ```APIDOC ## GET /v3/terminal/shutdown ### Description Kills the server process; returns the plain text OK. ### Method GET ### Endpoint /v3/terminal/shutdown ``` -------------------------------- ### GET /v3/option/snapshot/quote Source: https://userfrm.github.io/ThetaDataDx/server/http Retrieves an option quote snapshot for a specific contract. ```APIDOC ## GET /v3/option/snapshot/quote ### Description Retrieves an option quote snapshot for a specific contract. ### Method GET ### Endpoint /v3/option/snapshot/quote ### Query Parameters - **symbol** (string) - Required - The underlying ticker symbol. - **expiration** (string) - Required - Expiration date in YYYYMMDD or YYYY-MM-DD format. - **strike** (number) - Required - The strike price. - **right** (string) - Required - The option type (C, P, call, put). - **format** (string) - Optional - Response format (json, csv, ndjson, html). ``` -------------------------------- ### Connect, Subscribe, and Receive Streaming Data Source: https://userfrm.github.io/ThetaDataDx/streaming Examples demonstrating how to establish a connection, register a callback for events, and subscribe to market data contracts. ```rust use thetadatadx::streaming::Contract; use thetadatadx::streaming::{StreamData, StreamEvent}; use thetadatadx::{Credentials, DirectConfig, Client}; async fn run() -> Result<(), thetadatadx::Error> { let creds = Credentials::from_file("creds.txt")?; let client = Client::connect(&creds, DirectConfig::production()).await?; client.stream().start_streaming(|event: &StreamEvent| { if let StreamEvent::Data(StreamData::Quote { contract, bid, ask, .. }) = event { println!("{} bid={bid} ask={ask}", contract.symbol); } })?; client.stream().subscribe(Contract::stock("AAPL").quote())?; std::thread::sleep(std::time::Duration::from_secs(60)); client.stream().stop_streaming(); Ok(()) } ``` ```python import time from thetadatadx import Config, Contract, Credentials, Client creds = Credentials.from_file("creds.txt") client = Client(creds, Config.production()) def on_event(event): if event.kind == "quote": print(event.contract.symbol, event.bid, event.ask) with client.streaming(on_event): # stops streaming and drains on exit client.stream.subscribe(Contract.stock("AAPL").quote()) time.sleep(60) ``` ```typescript import { Contract, Client } from 'thetadatadx-ts'; const client = await Client.connectFromFile('creds.txt'); await client.stream.startStreaming((event) => { if (event.kind === 'quote') { const q = event.quote!; console.log(q.contract.symbol, q.bid, q.ask); } }); client.stream.subscribe(Contract.stock('AAPL').quote()); setTimeout(() => client.stream.stopStreaming(), 60_000); ``` ```cpp #include "thetadatadx.hpp" #include #include int main() { auto creds = thetadatadx::Credentials::from_file("creds.txt"); auto client = thetadatadx::Client::connect(creds, thetadatadx::Config::production()); client.stream().set_callback([](const thetadatadx::StreamEvent& event) { if (event.kind == THETADATADX_STREAM_QUOTE) { auto& q = event.quote; std::cout << q.contract.symbol << " bid=" << q.bid << " ask=" << q.ask << "\n"; } }); client.stream().subscribe(thetadatadx::Contract::stock("AAPL").quote()); std::this_thread::sleep_for(std::chrono::seconds(60)); // RAII: the destructor stops streaming and drains. } ``` -------------------------------- ### Configure client settings in Python Source: https://userfrm.github.io/ThetaDataDx/articles/configuration Initialize the configuration object and override default fields before passing it to the client. ```python from thetadatadx import Config cfg = Config.production() cfg.retry_max_attempts = 5 client = Client(creds, cfg) ``` -------------------------------- ### Run the Linux Server Binary Source: https://userfrm.github.io/ThetaDataDx/server Commands to make the binary executable and launch the server on Linux systems. ```bash chmod +x thetadatadx-server ./thetadatadx-server ``` -------------------------------- ### Quote at Time JSON Response Source: https://userfrm.github.io/ThetaDataDx/reference/stock/at-time/quote Example structure of the QuoteTick data returned by the API. ```json [ { "ask": 475.28, "ask_condition": 0, "ask_exchange": 7, "ask_size": 8, "bid": 475.28, "bid_condition": 0, "bid_exchange": 1, "bid_size": 15, "timestamp": "2024-01-16T09:30:00.1" } ] ``` -------------------------------- ### Construct credentials from .env file Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Initialize credentials by loading them from a specified .env file. ```rust let creds = thetadatadx::Credentials::from_dotenv(".env")?; ``` ```python creds = Credentials.from_dotenv(".env") ``` ```typescript const creds = Credentials.fromDotenv('.env'); ``` ```cpp auto creds = thetadatadx::Credentials::from_dotenv(".env"); ``` -------------------------------- ### GET /v1/options/greeks Source: https://userfrm.github.io/ThetaDataDx/reference/option/snapshot/greeks/all Retrieves Greeks for specified options with optional overrides for calculation parameters. ```APIDOC ## GET /v1/options/greeks ### Description Retrieves Greeks for options based on the provided symbol and filters. Allows for custom calculation inputs like interest rates, dividends, and underlying prices. ### Method GET ### Parameters #### Query Parameters - **symbol** (string) - Required - Ticker symbol (e.g. AAPL) - **expiration** (date) - Required - Expiration date YYYYMMDD. Pass * to select all expirations. - **strike** (string) - Optional - Strike price in dollars as a string. Default: * - **right** (string) - Optional - Option side (call, put, both, *). Default: both - **annual_dividend** (float) - Optional - Annualized expected dividend amount. - **rate_type** (string) - Optional - Risk-free-rate source. Default: sofr - **rate_value** (float) - Optional - Interest rate as a percent. - **stock_price** (float) - Optional - Underlying price override. - **version** (string) - Optional - Greeks model version. Default: latest - **max_dte** (int) - Optional - Maximum days to expiration. - **strike_range** (int) - Optional - Strike range filter. - **min_time** (string) - Optional - Minimum time filter. - **use_market_value** (bool) - Optional - Calculate against market value. Default: false - **timeout_ms** (int) - Optional - Per-request deadline in milliseconds. ``` -------------------------------- ### Construct credentials from environment or file Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Initialize credentials by reading from an environment variable or a fallback file. ```rust let creds = thetadatadx::Credentials::from_env_or_file("creds.txt")?; ``` ```python creds = Credentials.from_env_or_file("creds.txt") ``` ```typescript const creds = Credentials.fromEnvOrFile('creds.txt'); ``` ```cpp auto creds = thetadatadx::Credentials::from_env_or_file("creds.txt"); ``` ```bash export THETADATA_API_KEY="your_api_key" thetadatadx-server & ``` -------------------------------- ### GET /options/history/trade-greeks/implied-volatility Source: https://userfrm.github.io/ThetaDataDx/reference/option/history/trade-greeks/implied-volatility Retrieves implied volatility and Greeks data for specified options contracts. ```APIDOC ## GET /options/history/trade-greeks/implied-volatility ### Description Retrieves implied volatility and Greeks data for options based on the provided symbol and filtering criteria. ### Method GET ### Endpoint /options/history/trade-greeks/implied-volatility ### Parameters #### Query Parameters - **symbol** (string) - Required - Ticker symbol (e.g. AAPL) - **expiration** (date) - Required - Expiration date YYYYMMDD. Pass * to select all expirations. - **strike** (string) - Optional - Strike price in dollars as a string. Default: * - **right** (string) - Optional - Option side (call, put, both, *). Default: both - **date** (date) - Optional - Single date YYYYMMDD. - **start_time** (string) - Optional - Start time filter. Default: 09:30:00 - **end_time** (string) - Optional - End time filter. Default: 16:00:00 - **annual_dividend** (float) - Optional - Annualized expected dividend amount. - **rate_type** (string) - Optional - Risk-free-rate source. Default: sofr - **rate_value** (float) - Optional - Interest rate as a percent. - **version** (string) - Optional - Greeks model version. Default: latest - **max_dte** (int) - Optional - Maximum days to expiration. - **strike_range** (int) - Optional - Strike range filter. - **start_date** (date) - Optional - Start date YYYYMMDD. - **end_date** (date) - Optional - End date YYYYMMDD. - **timeout_ms** (int) - Optional - Per-request deadline in milliseconds. ``` -------------------------------- ### Initialize configuration from presets Source: https://userfrm.github.io/ThetaDataDx/articles/configuration Use built-in presets to initialize configuration, which automatically respects environment variables. ```python from thetadatadx import Config cfg = Config.production() # reads THETADATA_MARKET_DATA_TYPE / THETADATA_STREAMING_TYPE client = Client(creds, cfg) ``` -------------------------------- ### Fetch Option History Quotes in Python Source: https://userfrm.github.io/ThetaDataDx/reference/option/history/quote Example demonstrating how to initialize the client and retrieve historical quotes for a specific option contract. ```python from thetadatadx import Client client = Client.from_env() rows = client.market_data.option_history_quote( "SPY", "20250321", strike="570", right="C", interval="1m", ) for t in rows: print(t.date, t.ms_of_day, t.bid, t.ask) ``` -------------------------------- ### Retrieve Open Interest Snapshot in Python Source: https://userfrm.github.io/ThetaDataDx/reference/option/snapshot/open-interest Demonstrates how to initialize the client and fetch open interest data for a specific SPY call option. ```python from thetadatadx import Client client = Client.from_env() rows = client.market_data.option_snapshot_open_interest( "SPY", "20250321", strike="570", right="C", ) for t in rows: print(t.date, t.open_interest) ``` -------------------------------- ### Define an option contract Source: https://userfrm.github.io/ThetaDataDx/server/websocket Example of an option contract object using the default strike format. ```json {"symbol": "SPY", "expiration": 20250321, "strike": 570000, "right": "C"} ``` -------------------------------- ### OHLC Snapshot JSON Response Source: https://userfrm.github.io/ThetaDataDx/reference/index/snapshot/ohlc Example of the JSON structure returned by the OHLC snapshot request. ```json [ { "close": 6395.78, "count": 0, "high": 6408.4, "low": 6343.86, "open": 6406.62, "symbol": "SPX", "timestamp": "2025-08-20T16:02:06", "volume": 0 } ] ``` -------------------------------- ### Load configuration from .env file Source: https://userfrm.github.io/ThetaDataDx/articles/configuration Read environment selectors from a .env file to configure client channels. ```python from thetadatadx import Config cfg = Config.from_dotenv(".env") client = Client(creds, cfg) ``` -------------------------------- ### Example EOD response structure Source: https://userfrm.github.io/ThetaDataDx/reference/index/history/eod A JSON representation of the data returned by the EOD history request. ```json [ { "ask": 0, "ask_condition": 0, "ask_exchange": 0, "ask_size": 0, "bid": 0, "bid_condition": 0, "bid_exchange": 0, "bid_size": 0, "close": 5712.69, "count": 0, "created": "2024-11-04T17:19:50.198", "high": 5741.43, "last_trade": "2024-11-04T16:03:03", "low": 5696.51, "open": 5725.15, "volume": 0 }, { "ask": 0, "ask_condition": 0, "ask_exchange": 0, "ask_size": 0, "bid": 0, "bid_condition": 0, "bid_exchange": 0, "bid_size": 0, "close": 5782.76, "count": 0, "created": "2024-11-05T17:15:03.061", "high": 5783.44, "last_trade": "2024-11-05T16:02:30", "low": 5722.1, "open": 5722.43, "volume": 0 }, { "ask": 0, "ask_condition": 0, "ask_exchange": 0, "ask_size": 0, "bid": 0, "bid_condition": 0, "bid_exchange": 0, "bid_size": 0, "close": 5929.04, "count": 0, "created": "2024-11-06T17:16:28.297", "high": 5936.14, "last_trade": "2024-11-06T16:01:37", "low": 5864.89, "open": 5864.89, "volume": 0 } ] ``` -------------------------------- ### GET /v3/stock/history/eod Source: https://userfrm.github.io/ThetaDataDx/server/http Retrieves end-of-day stock history for a specific symbol across a date range. ```APIDOC ## GET /v3/stock/history/eod ### Description Retrieves end-of-day stock history for a specific symbol across a date range. ### Method GET ### Endpoint /v3/stock/history/eod ### Query Parameters - **symbol** (string) - Required - The stock ticker symbol. - **start_date** (string) - Required - Start date in YYYYMMDD or YYYY-MM-DD format. - **end_date** (string) - Required - End date in YYYYMMDD or YYYY-MM-DD format. - **format** (string) - Optional - Response format (json, csv, ndjson, html). ``` -------------------------------- ### Connect with custom configuration Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Manually construct credentials and configuration for advanced connection tuning. ```rust let creds = thetadatadx::Credentials::from_file("creds.txt")?; let client = thetadatadx::Client::connect(&creds, thetadatadx::DirectConfig::production()).await?; ``` ```python client = Client(Credentials.from_file("creds.txt"), Config.production()) ``` ```typescript const client = await Client.connect(Credentials.fromFile('creds.txt')); ``` ```cpp auto creds = thetadatadx::Credentials::from_file("creds.txt"); auto client = thetadatadx::Client::connect(creds, thetadatadx::Config::production()); ``` ```bash thetadatadx-server --creds creds.txt & ``` -------------------------------- ### GET /v1/options/history/trade-greeks Source: https://userfrm.github.io/ThetaDataDx/reference/option/history/trade-greeks/all Retrieves historical trade Greeks for specified options based on provided filters. ```APIDOC ## GET /v1/options/history/trade-greeks ### Description Retrieves historical trade Greeks for options. Users can filter by symbol, expiration, strike, and side, while also configuring parameters for the Greeks calculation such as interest rates and dividend amounts. ### Method GET ### Parameters #### Query Parameters - **symbol** (string) - Required - Ticker symbol (e.g. AAPL) - **expiration** (date) - Required - Expiration date YYYYMMDD. Pass * to select all expirations. - **strike** (string) - Optional - Strike price in dollars as a string. Default: * - **right** (string) - Optional - Option side (call, put, both, *). Default: both - **date** (date) - Optional - Single date YYYYMMDD. - **start_time** (string) - Optional - Start time filter. Default: 09:30:00 - **end_time** (string) - Optional - End time filter. Default: 16:00:00 - **annual_dividend** (float) - Optional - Annualized expected dividend amount. - **rate_type** (string) - Optional - Risk-free-rate source. Default: sofr - **rate_value** (float) - Optional - Interest rate as a percent. - **version** (string) - Optional - Greeks model version. Default: latest - **max_dte** (int) - Optional - Maximum days to expiration. - **strike_range** (int) - Optional - Strike range filter. - **start_date** (date) - Optional - Start date YYYYMMDD. - **end_date** (date) - Optional - End date YYYYMMDD. - **timeout_ms** (int) - Optional - Per-request deadline in milliseconds. ``` -------------------------------- ### Subscribe to Stock Quotes Source: https://userfrm.github.io/ThetaDataDx/streaming/stocks/quote Examples for subscribing to and unsubscribing from stock quote streams using the native SDKs. ```rust use thetadatadx::streaming::Contract; use thetadatadx::streaming::{StreamData, StreamEvent}; client.stream().start_streaming(|event: &StreamEvent| { if let StreamEvent::Data(StreamData::Quote { contract, bid, ask, .. }) = event { println!("{} bid={bid} ask={ask}", contract.symbol); } })?; let sub = Contract::stock("AAPL").quote(); client.stream().subscribe(sub.clone())?; // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub)?; ``` ```python from thetadatadx import Contract def on_event(event): if event.kind == "quote": print(event.contract.symbol, event.bid, event.ask) client.stream.start_streaming(on_event) sub = Contract.stock("AAPL").quote() client.stream.subscribe(sub) # Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub) ``` ```typescript import { Contract } from 'thetadatadx-ts'; await client.stream.startStreaming((event) => { if (event.kind === 'quote') { const e = event.quote!; console.log(e.contract.symbol, e.bid, e.ask); } }); const sub = Contract.stock('AAPL').quote(); client.stream.subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream.unsubscribe(sub); ``` ```cpp client.stream().set_callback([](const thetadatadx::StreamEvent& event) { if (event.kind == THETADATADX_STREAM_QUOTE) { auto& e = event.quote; std::cout << e.contract.symbol << " bid=" << e.bid << " ask=" << e.ask << "\n"; } }); auto sub = thetadatadx::Contract::stock("AAPL").quote(); client.stream().subscribe(sub); // Remove this stream; the session stays open for other subscriptions. client.stream().unsubscribe(sub); ``` -------------------------------- ### Initialize credentials directly Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Pass email and password directly to the constructor. ```rust let creds = thetadatadx::Credentials::new("you@example.com", "your-password"); ``` ```python creds = Credentials("you@example.com", "your-password") ``` ```typescript const creds = new Credentials('you@example.com', 'your-password'); ``` ```cpp auto creds = thetadatadx::Credentials::from_email("you@example.com", "your-password"); ``` ```bash # The HTTP server reads the pair from a credentials file. thetadatadx-server --creds creds.txt & ``` -------------------------------- ### Load credentials from file Source: https://userfrm.github.io/ThetaDataDx/articles/getting-started Initialize credentials using a local file path. ```rust let creds = thetadatadx::Credentials::from_file("creds.txt")?; ``` ```python creds = Credentials.from_file("creds.txt") ``` ```typescript const creds = Credentials.fromFile('creds.txt'); ``` ```cpp auto creds = thetadatadx::Credentials::from_file("creds.txt"); ``` ```bash thetadatadx-server --creds creds.txt & ```