> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polynode.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Python PN1 Orderbook

> Maintain exact Python orderbooks with PN1 sequence and checksum verification.

Use `OrderbookEngine` for a managed local book. Enable PN1 integrity for price-sensitive decisions.

```python theme={null}
import asyncio
import os
from polynode import OrderbookEngine

async def main() -> None:
    token_id = os.environ["POLYMARKET_TOKEN_ID"]
    engine = OrderbookEngine(
        os.environ["POLYNODE_API_KEY"],
        integrity=True,
        allow_stale_reads=False,
    )

    engine.on("integrity_error", lambda error: print(
        error.code, error.token, error
    ))
    engine.on("ready", lambda: print({
        "best_bid": engine.best_bid(token_id),
        "best_ask": engine.best_ask(token_id),
        "midpoint": engine.midpoint(token_id),
        "spread": engine.spread(token_id),
    }))

    try:
        await engine.subscribe([token_id])
        await asyncio.Event().wait()
    finally:
        engine.close()

asyncio.run(main())
```

PN1 keeps price and size values as exact decimal strings. It validates the full-snapshot anchor, then validates sequence continuity and a deterministic checksum on each applicable update.

Managed state moves through `initializing`, `ready`, `stale`, `resyncing`, and `failed`. With stale reads disabled, queries are unavailable until a verified anchor is ready and become unavailable after a disconnect or integrity failure. The engine requests a fresh anchor before returning to `ready`.

<Warning>
  Wildcard `"*"` subscriptions are unavailable in integrity mode. Use explicit token IDs, slugs, or condition IDs.
</Warning>

For raw messages, construct `OrderbookWS(..., integrity=True)`, register `snapshot`, `resyncing`, `error`, and `unknown` handlers, then `await subscribe(...)`. Close it with `disconnect()`.

See the [shared orderbook guide](/sdks/orderbook) and [PN1 protocol reference](/orderbook/integrity).
