# Python stream reference

Python 3.10 or newer. This is a reference decoder, **not a supported SDK**.
JSON mode needs no decoder and is the simpler choice for most clients. Both
formats have the same snapshot, sequence and gap recovery rules.

The decoder and tests use only the standard library. From the repository root:

```sh
python3 -m unittest discover -s clients/python -v
# Equivalent focused gate, also included in make check:
make python-client-check
```

Only the asyncio example needs a third-party package:

```sh
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install 'websockets>=14'
# Set OPTIONSDATA_API_KEY securely in your shell environment first.
python3 clients/python/stream_example.py --underlying SPX --expiration '' --expiration 2026-12-18
python3 clients/python/stream_example.py --format psf1 --underlying SPX --expiration ''
# A local fixture (never put credentials in the URL):
python3 clients/python/stream_example.py --url ws://127.0.0.1:9000/v1/stream --underlying SYNTH
```

`--format` defaults to `json`. Repeat `--expiration` for multiple streams; `''`
is the underlying stream. Omitting it subscribes to all expirations plus the
underlying stream. All subscriptions share **one connection**, since accounts
have limited connection slots. The key is sent only in the Authorization Bearer
header on upgrade. Reconnect delays grow from 1 to 30 seconds.

The example waits for hello, selects format, lists the underlying, then subscribes
after both replies. It prints one JSON line per accepted frame with the stream,
sequence, snapshot flag and row counts. Sequence breaks discard that stream and
send unsub/sub; queued deltas are ignored until the new snapshot. Gap markers
mark the stream degraded until its automatic recovery snapshot. A source outage
also waits for snapshots, retaining subscriptions. Gap refetch hints are printed
to stderr: current-state snapshots cannot recover missing prints. Applications
needing every print must retrieve that range over REST and deduplicate it.

Read the socket continuously to keep up with busy subscriptions. If application
work per frame is heavy, hand decoded frames to another task or thread for that
work, preserving frame order. A `gap` with reason `backpressure` means the client
fell behind.

## Decoder API

```python
from psf1 import Decoder, State  # add clients/python to your import path

decoder = Decoder(hello, names={123: "SPX"})
state = State(hello)
frame = decoder.decode(binary_message)
state.apply(frame)
```

`hello` can be a dict or UTF-8 JSON bytes, either the full hello or its schema
value. Descriptors always come from that connection's hello. Replace **both**
objects on every new hello. On unsubscribe call `drop((underlying_iid,
expiration))` on both. `PSF1Error` rejects malformed frames without changing
committed decoder state; `SequenceBreak` is its subclass and exposes `.stream`
for resubscription. Catch it around `decode` and `State.apply`.

Returned frames match protocol §2 JSON shapes: floats in real units, exact
fixed-scale decimal strings, lossless integers, omitted absent fields, explicit
`None` for null. Supply catalog names through `names` or update `decoder.names`
from `streams` replies; without a name the `underlying` string is empty.
Optional `decoder_schema=` limits output to an older application's known fields,
while consuming and retaining bases for every received field. Known field name,
wire type and unit mismatches are rejected. Schema version 2 is required.

`State.rows[stream][record_name][(iid, *key_values)]` holds current rows, with key
fields in received descriptor order. Snapshots replace one stream; deltas retain
absent fields and clear nulls. Prints fold to their latest row per iid: read each
frame's rows to preserve every event.

The offline tests read the vectors from `$PSF1_VECTORS` if set, else `vectors.json` in the
same directory as `test_psf1.py` (put the downloaded files side by side and run
`python3 -m unittest test_psf1`), else `docs/psf1/vectors.json` in the repository. They
compare float bits and verify transactionality for all invalid vectors. No live
service, API key or network is required. The implementation follows
[the PSF1 spec](../../docs/psf1.md) and [vector guide](../../docs/psf1/README.md).
