Metadata-Version: 2.4
Name: lotech-market-data
Version: 3.1.12
Requires-Dist: polars>=1.36.1
Requires-Dist: pyarrow>=22.0.0
Requires-Dist: requests>=2.31.0
Requires-Dist: tzdata ; sys_platform == 'win32'
Requires-Dist: ast-serialize>=0.11.2,<1.0.0 ; extra == 'dev'
Requires-Dist: librt>=0.16.0 ; extra == 'dev'
Requires-Dist: maturin[patchelf]>=1.0 ; extra == 'dev'
Requires-Dist: mypy>=1.11.0 ; extra == 'dev'
Requires-Dist: mypy-extensions>=1.1.0 ; extra == 'dev'
Requires-Dist: pathspec>=1.0.2 ; extra == 'dev'
Requires-Dist: pytest>=8.0.0 ; extra == 'dev'
Requires-Dist: ruff>=0.8.0 ; extra == 'dev'
Requires-Dist: twine>=6.2.0 ; extra == 'dev'
Requires-Dist: types-requests>=2.31.0 ; extra == 'dev'
Requires-Dist: typing-extensions>=4.15.0 ; extra == 'dev'
Requires-Dist: matplotlib>=3.0.0 ; extra == 'examples'
Requires-Dist: numpy>=1.24.0 ; extra == 'examples'
Requires-Dist: scipy>=1.10.0 ; extra == 'examples'
Provides-Extra: dev
Provides-Extra: examples
Summary: Python client for accessing LO:TECH market data
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# lotech-market-data

Python client for accessing LO:TECH market data.

## Installation

```bash
pip install lotech-market-data
```

For running the advanced plotting examples:

```bash
pip install lotech-market-data[examples]
```

## Usage

### Basic Example

```python
import logging
from datetime import datetime, timezone
from lotech_market_data import LotechMarketData

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

client = LotechMarketData()

# Get time range for today
query_date = datetime.now(timezone.utc).date()
start = datetime.combine(query_date, datetime.min.time()).replace(tzinfo=timezone.utc)
end = datetime.combine(query_date, datetime.max.time()).replace(tzinfo=timezone.utc)

# Fetch top of book data
df = client.load_top_of_book(
    exchange="BINANCE",
    instrument="BTC-USDT:SPOT",
    start=start,
    end=end,
)

logger.info("Total rows: %d", df.height)
```

### API Methods

The `LotechMarketData` class provides the following methods:

#### Market Data Methods

All market data methods accept the following parameters:
- `exchange`: Single exchange string or list of exchanges (e.g., `"BINANCE"` or `["BINANCE", "BYBIT"]`)
- `instrument`: Single instrument or list (e.g., `"BTC-USDT:SPOT"` or `["BTC-USDT:SPOT", "ETH-USDT:SPOT"]`)
- `start`: Start datetime (timezone-aware)
- `end`: End datetime (timezone-aware)
- `columns` (optional): List of columns to return

Available methods:
- `load_top_of_book()` - Top of book (bid/ask) data
- `load_trades()` - Trade data
- `load_funding()` - Funding rate data
- `load_reference_price()` - Reference price data
- `load_open_interest()` - Open interest data
- `load_orderbook_incremental()` - Incremental orderbook updates

#### IV Surface

Fitted option-surface tables from the LO:TECH SVI engine (Deribit BTC, ETH and
SOL), loaded exactly like the market data methods. The one difference: the
time window applies to `snapshot_ts` (the market instant a row describes)
rather than `ingress_ts`. Available on keys with the `iv_*` data types enabled.

The one-call question, "what is the IV of this strike on this expiry, as of
this time":

```python
from datetime import timedelta

client.iv_lookup("BTC", 80_000, "25DEC26")  # now
client.iv_lookup("BTC", 80_000, "2026-12-25", as_of=trade_time)  # as of a trade
client.iv_lookup("BTC", 80_000, "25DEC26", max_age=timedelta(hours=1))  # refuse a stale record
# IvLookupResult(iv=0.419, source=<IvSource.FIT: 'fit'>, surface_ok=True, extrapolated=False,
#                stale=False, forward=81048.0, snapshot_ts=datetime(2026, 8, 25, 12, 30, tzinfo=UTC),
#                age=timedelta(seconds=1846), ...)
```

`iv` is a decimal (0.419 = 41.9%), the same for a call and a put at one
strike. The answer comes from the newest snapshot at or before `as_of` with a
clean fit for the expiry (`IvSource.FIT`), else an older snapshot within three
hours that has one (`WALKBACK`), else the newest fit of any quality
(`surface_ok` False), else total-variance interpolation between the two fitted
expiries that bracket it (`INTERPOLATED`, with `bracket`). It raises only when
no fitted expiry brackets the request, or the expiry settled at or before
`as_of`. `stale` is set past three hours of age; `max_age` turns that into a
refusal. `AioLotechMarketData.iv_lookup` is the same call, awaited.

The tables themselves:

```python
from lotech_market_data import iv_at

# One row per fitted expiry per snapshot: SVI parameters, forward, fit diagnostics
fits = client.load_iv_fits(exchange="DERIBIT", base_asset="BTC", start=start, end=end)

# Model IV at a strike, for every row in the frame
ivs = iv_at(fits, 80_000)  # adds strike, log_moneyness, iv, extrapolated

# One row per option instrument per snapshot: model IV at every listed strike, greeks, quote flags
quotes = client.load_iv_quotes(exchange="DERIBIT", base_asset="BTC", start=start, end=end)

# One row per constant-maturity tenor per snapshot (7/30/60/90/180 days)
cm = client.load_iv_cm(exchange="DERIBIT", base_asset=["BTC", "ETH"], start=start, end=end)
```

`instrument` keys every row: the option id on `iv_quotes`, an expiry-level id
such as `BTC-USD:OPT-EURO-2026_12_25T08_00:INVERSE` on `iv_fits`, and a
tenor-level id such as `BTC-USD:OPT-CM-30D` on `iv_cm`.

`extrapolated` marks strikes beyond the quoted range (model wing shape, not a
market-anchored mark) and `surface_ok` / `cm_ok` mark slices that failed the
engine's arbitrage gates; both are reported rather than repaired. Java: see
`tech.lo.marketdata.IvLookup` and `Svi`.

#### Instrument Static

```python
# Get all instruments for an exchange (latest)
df = client.load_instr_static(exchange="BINANCE")

# Get all instruments at a specific datetime
df = client.load_instr_static(exchange="BINANCE", datetime=some_datetime)

# Filter for specific instrument(s)
df = client.load_instr_static(exchange="BINANCE", instrument="BTC-USDT:SPOT")

df = client.load_instr_static(exchange="BINANCE", instrument=["BTC-USDT:SPOT", "ETH-USDT:SPOT"])
```

### Column Filtering

You can filter columns to reduce data transfer:

```python
df = client.load_top_of_book(
    exchange="BINANCE",
    instrument="BTC-USDT:SPOT",
    start=start,
    end=end,
    columns=["exchange", "instrument", "ingress_ts", "bid_price", "ask_price"],
)
```

### Multiple Exchanges

Query multiple exchanges:

```python
df = client.load_top_of_book(
    exchange=["BINANCE", "BYBIT"],
    instrument="BTC-USDT:SPOT",
    start=start,
    end=end,
)
```

### Multiple Instruments

Query multiple instruments:

```python
df = client.load_top_of_book(
    exchange="BINANCE",
    instrument=["BTC-USDT:SPOT", "ETH-USDT:SPOT", "SOL-USDT:SPOT"],
    start=start,
    end=end,
)
```

## Available Exchanges

The set of exchanges is **fetched dynamically** from the API and reflects exactly
what your API key is permissioned for — the client does not hardcode a list:

```python
exchanges = LotechMarketData.get_available_exchanges()
logger.info("Available exchanges: %s", exchanges)
```

## Instrument Format

Instruments follow the format: `SYMBOL:KIND[:SUBKIND]`

Examples:
- `BTC-USDT:SPOT` - Spot market
- `BTC-USDT:PERP:LINEAR` - Linear perpetual
- `BTC-USDT:PERP:INVERSE` - Inverse perpetual
- `BTC-USD:FUT:LINEAR` - Linear future
- `BTC-USD:FUT:INVERSE` - Inverse future

## Examples

### Basic Examples (`examples/basic/`)

These examples showcase fetching each data type and display all available columns:

- `top_of_book.py` - Fetch bid/ask data
- `trades.py` - Fetch trade data
- `orderbook_incremental.py` - Fetch orderbook updates and build orderbook
- `funding.py` - Fetch funding rate data
- `open_interest.py` - Fetch open interest data
- `reference_price.py` - Fetch reference price data
- `instrument_static.py` - Fetch instrument metadata
- `list_exchanges.py` - List all available exchanges

### Advanced Examples (`examples/advanced/`)

These examples demonstrate more complex use cases:

- `plot_btc_usdt_exchanges.py` - Plot BTC-USDT mid price across multiple exchanges
- `plot_trades.py` - Visualize trades with volume bars
- `analyze_instruments.py` - Analyze instrument metadata with statistics
- `animate_orderbook.py` - Create animated orderbook visualization
- `plot_polymarket_binary.py` - Compare Polymarket binary options to GBM theoretical pricing

## Example Outputs

The advanced examples generate visualizations in `examples/outputs/`:

### BTC-USDT Mid Price Across Exchanges
![BTC-USDT Exchanges](examples/outputs/btc_usdt_exchanges.png)

Comparison of BTC-USDT perpetual mid price across BINANCE, BYBIT, OKX, BITMART, and BITMEX exchanges showing price movements and spreads.

### LTC-USDT Trades Visualization
![LTC-USDT Trades](examples/outputs/ltc_usdt_trades.png)

Trades visualization for LTC-USDT perpetual contracts showing taker buy/sell trades colored by exchange, with weighted mid price overlay and 30-second volume bars.

### DOGE-USDT Orderbook Animation
![DOGE Orderbook](examples/outputs/doge_usdt_orderbook.gif)

Animated visualization of DOGE orderbook across 5 exchanges (BINANCE, BYBIT, OKX, COINBASEUS, BITSTAMP) showing cumulative order book depth, mid price movement, and cross-exchange dynamics at 10ms intervals.

### Locked-down environments (no extension downloads)

The Java client loads DuckDB's `httpfs` extension via `INSTALL httpfs` at startup. If your
environment blocks that download, provision the extension file yourself (it must match the
bundled DuckDB version, `duckdb_jdbc` in `java/pom.xml`) and point the client at it — nothing is
downloaded:

```java
Client c = Client.builder().httpfsExtension("/opt/duckdb/httpfs.duckdb_extension").build();
// or: export LOTECH_DUCKDB_HTTPFS_EXTENSION=/opt/duckdb/httpfs.duckdb_extension
```

