Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **Bulk fetch is opt-in: `bulk_fetch` now defaults to `"off"`.** How a large pull can be split depends on what the server accepts, and a change on the server side can break a split before the SDK follows it, so every query now runs as one request, in the server's own order, unless you turn the split on. Migration: set `bulk_fetch = "auto"` to keep splitting large history pulls: `config.bulk_fetch = "auto"` in Python, `config.market_data.bulk_fetch = BulkFetchPolicy::Auto` in Rust, `config.setBulkFetch("auto")` in TypeScript, `config.set_bulk_fetch(0)` in C++, or `bulk_fetch = "auto"` under `[market_data]` in a TOML config file.

- **A one-day option chain at a bar interval is split across concurrent requests by expiration.** A history pull over every strike at an interval such as `1s` or `1m` went out as a single request when it named one day, because cutting its window in time would restart each bar's accumulation at the seam and change the bars. With `bulk_fetch = "auto"`, the SDK now splits such a chain by contract instead, so every contract's bars still cover the whole window. A chain over every expiration first lists the day's contracts in one request, then fetches each expiration on its own, calls and puts separately. A chain with one expiration, or one whose contract list fails, is fetched as one request for calls and one for puts, and a small chain keeps that pair, since dozens of requests would cost it more than they save. A buffered pull merges the pieces into the chain order every split pull already returns. A Greeks chain with `implied_vol_method="out_of_the_money"` reads each strike's volatility from the other side, so it keeps both rights in every request. Quote ticks over every expiration split the same way: the server prepares the whole chain for every piece of a time split, so on SPXW those pieces sent nothing for minutes, while one request per expiration started at once. A trade chain keeps the time split, because its trades are too few for one request per expiration to pay. An OHLC chain over every expiration is refused by the server as one request, so it is not split either.

- **TypeScript streaming callbacks keep up with a higher message rate.** The native side hands events to the Node main thread in arrays instead of waking it once per event, and the package still calls your `startStreaming` callback once per event, in order. On the offline callback benchmark (`thetadatadx-ts/benches/streaming_throughput.mjs`) a no-op callback goes from about 300k to about 460k events a second, and live on the dev replay server the Node main thread is about a fifth less busy at the same message rate. A callback that throws still ends the process at that event unless an `uncaughtException` handler is installed; with one, the handler gets the error and the rest of the events are still delivered.

- **The five Greeks tick structs carry `implied_vol_source`, which breaks Rust code that builds or exhaustively destructures them and C or C++ code built against the previous header.** `GreeksAllTick`, `GreeksEodTick`, `GreeksFirstOrderTick`, `GreeksSecondOrderTick` and `GreeksThirdOrderTick` gain `implied_vol_source` and its presence flag `has_implied_vol_source`. In Rust a struct literal or a pattern that names every field has to add both, or `..`. Python and TypeScript only gain a field, `None` or `undefined` where the route does not send it. In C and C++ the new members move the contract identity members that follow them and change the size of the five structs, and `ThetaDataDxEndpointRequestOptions` gains the two new parameters as `const char*` members at its end, so a program built against the previous header would read the wrong bytes; rebuild against the new header.

### Fixed

- **A market-data request without its own deadline is no longer cut off after five minutes.** `request_timeout_secs` (default 300) bounded the whole request, so a large pull that was still streaming, such as a day of one-second quotes across an option chain, failed part way with a deadline error, and a request waiting for a free slot in the request pool spent its time there. It now bounds only how long the server may stay silent: for the response to start, and then between two messages. Its default is now 2700 seconds (45 minutes), because the server prepares a large response before sending its first row, and on a one-day chain of one-second bars that can take longer than five minutes. A pull that keeps streaming runs to completion, through the local server and the MCP server too, while a stalled one still fails, now as a `DeadlineExceeded` status that the retry policy treats as transient, as a flat-file download already did. A per-call deadline (`with_deadline` in Rust, `timeout_ms` elsewhere) still bounds the whole call, and 0 still lifts every limit. Migration: Rust code that matched `Error::Timeout` for the configured limit should match `Error::Grpc { kind: GrpcStatusKind::DeadlineExceeded, .. }`. Python, TypeScript, C and C++ report a stall as the same `DeadlineExceededError` (`THETADATADX_ERR_DEADLINE_EXCEEDED`) as before. Set `request_timeout_secs` lower to give up on a silent server sooner.

- **A subscribe larger than the command queue no longer fails part way.** One `subscribe_many` (`subscribeMany` in TypeScript) over a whole option chain, such as SPXW quotes and trades within 10% of spot (19,228 streams), could fail with "command queue full" and leave the session subscribed to only part of the list. Subscribe and unsubscribe now wait while the queue to the streaming connection is full, so a call of any size goes through, in every language. The error is returned only if the connection takes no commands for longer than its read timeout.
- **A large subscribe no longer spends seconds on bookkeeping.** Each subscribe searched every subscription already made and swept every unanswered one, so one `subscribe_many` over a whole option chain took time that grew with the square of its size, seconds of CPU on the calling thread for the 19,228-stream SPXW chain. Both lookups are now constant time, and the same subscribe takes milliseconds. In Rust, `SubscriptionKind` now implements `Hash`.

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ High-performance market-data SDKs for [ThetaData](https://thetadata.us), in **Py

- **Complete coverage**: stocks, options, indices, and rates across 81 typed endpoints.
- **Three access modes, one client**: point-in-time history, real-time streaming, and bulk flat-file downloads.
- **Optional bulk fetch**: with `bulk_fetch = "auto"`, a large history pull runs as several concurrent requests within your account's concurrent-request allowance and is merged back into the rows one request returns. It is off by default, because which splits work depends on what the server accepts. See [Bulk Downloads](https://userfrm.github.io/ThetaDataDx/articles/bulk-downloads).
- **DataFrames built in**: every result chains straight to Polars, pandas, or Arrow over a zero-copy boundary.
- **Greeks on demand**: first- through third-order Greeks and implied volatility, served straight from the option endpoints.
- **The same surface in every language**: identical methods and identical typed errors, Python through Rust.
Expand Down
30 changes: 27 additions & 3 deletions docs-site/docs/articles/bulk-downloads.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,37 @@ Raise them for even fatter streams if you have memory to spare, or lower them wh

A single large request does not have to be one stream. The SDK splits the requested time (or date) range into equal concurrent pieces. The split comes straight from the shape of the request, with no sizing round-trip. It then runs them in parallel across your concurrent-request pool and reassembles them into exactly the rows one request would have returned.

A one-day option chain at a bar interval, such as `1s` or `1m`, is split by contract instead of by time: each bar builds up from the start of the requested window, so a piece starting mid-day would return different bars. A chain over every expiration first lists the day's contracts in one small request, then fetches each expiration as its own request, calls and puts separately. A chain with a single expiration splits into calls and puts. Either way, every contract's bars cover the whole window, exactly as one request returns them. Quote ticks over every expiration split the same way, because the server prepares the whole chain for every piece of a time split; a trade chain keeps the time split, since it is too sparse for one request per expiration to pay. An OHLC chain over every expiration is one the server refuses as a single request, and the SDK returns that same error rather than working around it.

The number of pieces is the request-pool size, which defaults to your account's allowance: the SDK sizes the pool to your subscription tier at connect time (Free 1 / Value 2 / Standard 4 / Pro 8), and setting `max_concurrent_requests` overrides that with no client-side cap, because the server enforces the real allowance. See [Concurrent Requests](/articles/concurrent-requests).

On Pro, one big query becomes eight pieces fetching at once; a boosted account with `max_concurrent_requests = 32` fans out 32 ways. How much that shortens the wall clock depends on how much of the fan-out the server actually runs in parallel under current conditions; the table below shows one measured day. It scales down cleanly too: four pieces on Standard, two on Value, one on Free.

Sharding is on by default. Small pulls stay a single request, so there is nothing to tune for them. If you want control:
Sharding is opt-in. Which ways a request can be split depends on what the server accepts, and a change on the server side could break a split before the SDK catches up, so every query is one request until you turn it on:

```python
from thetadatadx import Client, Config, Credentials

cfg = Config.production()
cfg.bulk_fetch = "auto"
client = Client(Credentials.from_file("creds.txt"), cfg)
```

```rust
use thetadatadx::config::{BulkFetchPolicy, DirectConfig};

let mut cfg = DirectConfig::production();
cfg.market_data.bulk_fetch = BulkFetchPolicy::Auto;
```

```typescript
const cfg = Config.production();
cfg.setBulkFetch("auto");
```

In a TOML config file, set `bulk_fetch = "auto"` under `[market_data]`. Small pulls stay a single request even then, so there is nothing to tune for them. If you want control:

- `bulk_fetch = "off"` runs every query as one request, in the server's own order.
- `bulk_fetch = "off"` (the default) runs every query as one request, in the server's own order.
- `shard_concurrency` caps how many pieces run at once (default: the full pool). Lower it to leave concurrency free for other requests running at the same time.

Sharding only fills the pool you configured. It never exceeds it.
Expand Down Expand Up @@ -119,7 +143,7 @@ Every setup returns the same rows. A concrete single contract comes back byte-fo

| Field | Default | What it does |
|---|---|---|
| `bulk_fetch` | `"auto"` | `"auto"` splits large pulls across the request pool; `"off"` runs one request in server order. |
| `bulk_fetch` | `"off"` | `"auto"` splits large pulls across the request pool; `"off"` runs one request in server order. |
| `max_concurrent_requests` | your tier | Concurrent-request pool size. Defaults to your subscription tier's allowance; set it to a boosted allowance to go wider (the server enforces the real limit). |
| `shard_concurrency` | full pool | Caps pieces per pull. Lower to share concurrency with other requests. |
| `stream_window_size_kb` | `8192` | Per-stream HTTP/2 flow-control window, in KB. |
Expand Down
4 changes: 2 additions & 2 deletions docs-site/docs/articles/concurrent-requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ Pick the client by what else you need (streaming, sync calls, a smaller surface)

## One giant request, split for you

The pattern above parallelizes work you have already split into many requests. The SDK also does the reverse for you: a **single** large history request has its time or date range split into equal pieces, run in parallel across the request pool, and reassembled into exactly the rows one request would have returned. You write one ordinary query and it runs at your configured concurrency. This is on by default.
The pattern above parallelizes work you have already split into many requests. The SDK also does the reverse for you: a **single** large history request has its time or date range split into equal pieces, run in parallel across the request pool, and reassembled into exactly the rows one request would have returned. You write one ordinary query and it runs at your configured concurrency. Turn it on with `bulk_fetch = "auto"`.

See [Bulk Downloads](/articles/bulk-downloads) for the full picture: how the split works, buffered versus streaming delivery, the `bulk_fetch` and `shard_concurrency` knobs, API examples, and measured performance.

## When parallelism pays

Concurrency multiplies throughput on multi-request workloads: per-day backfills, per-contract chain pulls, anything you can split with `split_date_range`. For a single large request you no longer have to split it yourself, since `bulk_fetch` does it automatically ([above](#one-giant-request-split-for-you)); splitting manually still works when you want direct control over the pieces.
Concurrency multiplies throughput on multi-request workloads: per-day backfills, per-contract chain pulls, anything you can split with `split_date_range`. For a single large request you no longer have to split it yourself, since `bulk_fetch = "auto"` does it for you ([above](#one-giant-request-split-for-you)); splitting manually still works when you want direct control over the pieces.

If the service reports exhaustion (because a burst exceeded your account's allowance, or during peak hours), the SDK retries with backoff before surfacing an error. Long-running bulk jobs should expect occasional retries at peak; see [Data Issues?](/articles/data-issues) if a job stalls beyond that.
11 changes: 3 additions & 8 deletions docs-site/docs/articles/flat-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,13 @@ The most recent **7 calendar days** are available; the prior day is generally re

## Pull a file

A small file (stock or index EOD) comes back whole like any other endpoint. The trade-quote, quote and option files are far larger: stream them chunk by chunk, and lift the per-request deadline, which defaults to 300 seconds and would end a long download early.
A small file (stock or index EOD) comes back whole like any other endpoint. The trade-quote, quote and option files are far larger: stream them chunk by chunk. A download that keeps streaming has no time limit; the SDK gives up only when the server sends nothing for `request_timeout_secs` (default 2700 seconds).

<SdkTabs>

<template #rust>

```rust
use std::time::Duration;

// A small file, whole:
let eod = client.market_data().stock_flat_file_eod("20261021").await?;
let df = eod.to_polars()?; // leads with the `symbol` column
Expand All @@ -49,7 +47,6 @@ let df = eod.to_polars()?; // leads with the `symbol` column
client
.market_data()
.option_flat_file_trade_quote("20261021")
.with_deadline(Duration::ZERO)
.stream(|chunk| {
// `chunk` derefs to `&[TradeQuoteTick]`; `chunk.columns()` names each row's root
})
Expand All @@ -69,7 +66,6 @@ def on_chunk(chunk): # TradeQuoteTickList, like a whole result

(client.market_data
.option_flat_file_trade_quote_builder("20261021")
.timeout_ms(0)
.stream(on_chunk))
```

Expand All @@ -80,7 +76,7 @@ def on_chunk(chunk): # TradeQuoteTickList, like a whole result
```typescript
const eod = await client.marketData.stockFlatFileEOD('20261021');

await client.marketData.optionFlatFileTradeQuoteStream('20261021', { timeoutMs: 0 }, (rows, columns) => {
await client.marketData.optionFlatFileTradeQuoteStream('20261021', null, (rows, columns) => {
// rows: TradeQuoteTick[]; columns names each row's root
});
```
Expand All @@ -95,8 +91,7 @@ auto eod = client.market_data().stock_flat_file_eod("20261021");
client.market_data().option_flat_file_trade_quote_stream("20261021",
[](auto rows, const thetadatadx::ColumnPresence& columns) {
// rows: Span<const TradeQuoteTick>; columns names each row's root
},
thetadatadx::EndpointRequestOptions{}.with_timeout_ms(0));
});
```

</template>
Expand Down
Loading
Loading