---
title: "Recovery recipes"
description: "Handle unknown order results, disconnected books and incomplete history without hiding uncertainty."
order: 8
llms: trading, market-data
---

**Advanced.** Use these recipes after a lost connection or a sequence gap, so you don't trade on a stale view
of the market or miss your own fills. For a write timeout, see
[When a write's outcome is unknown](errors-and-retries.md#when-a-writes-outcome-is-unknown).

The SDK gives you order lookup, a checked order book and history paging. Your app decides when to stop trading,
how far back to look, how to store and de-duplicate what it finds, and when its state is safe to use again.

## What happens after a gap

A **gap event** says which sequence numbers you may have missed: everything after `after_sequence` (exclusive)
through `through_sequence` (inclusive). A missing bound means the SDK doesn't know it. The range is not a REST
time window or a replay cursor ([sequence rules](websocket.md#sequence-numbers-and-gaps)).

What the SDK does next depends on the [stream kind](websocket.md#snapshots-deltas-and-events):

| Stream | After a gap, the SDK |
|---|---|
| `.s` (every frame complete) | carries on: the next frame is current. |
| `.d` (a snapshot, then deltas) | re-subscribes and waits for a fresh snapshot, then reconnects if none arrives within 5 s (the client's resync timeout option). |
| Events (fills, orders, ...) | re-subscribes. Missed events are not replayed. |

- Gap events arrive only through the client's event hook ([`on_event`](#sdk-helpers)), never in a
  subscription's frames. If you record frames, record the gap events too: they are the only record of missing
  data.
- Frames from before the gap can still be queued ahead of the new ones, with no marker in between. Don't treat
  the next frame as fresh ([Rebuild a book after a gap](#rebuild-a-book-after-a-gap)).
- A new snapshot gives you current state, not the private events you missed (fills, order updates). Fill them
  from history ([Fill missed events from history](#fill-missed-events-from-history)).

## SDK helpers

| Python | TypeScript | Go | Rust |
|---|---|---|---|
| `resolve_order` | `resolveOrder` | `ResolveOrder` | `resolve_order` |
| `on_event` (client option) | `onEvent` | `OnEvent` (`Config`) | `.on_event` (`Config`) |
| `after_sequence`, `through_sequence` | `afterSequence`, `throughSequence` | `AfterSequence`, `ThroughSequence` | `after_sequence`, `through_sequence` |
| `OrderBook.on_event`, `.apply`, `.reset` | `OrderBook.onEvent`, `.apply`, `.reset` | `OrderBook.OnEvent`, `.Apply`, `.Reset` | `OrderBook::on_event`, `apply`, `reset` |
| `backfill_pages` | `backfillPages` | `BackfillPages` | `backfill_pages` |
| `continuity` | `continuity` | `Continuity()` | `continuity()` |

Gap bounds are `int` in Python, strings in TypeScript, `*uint64` in Go and `Option<u64>` in Rust.

**`OrderBook`** keeps a local book from one subscription's frames. It merges exact price levels, removes
zero-size levels, and sorts bids high to low and asks low to high. The levels it returns are copies. Give it the
mode of the stream you feed it; it never guesses from the stream name:

| Stream | Python | TypeScript | Go | Rust |
|---|---|---|---|---|
| `orderbook_delta_stream` | `OrderBook(instrument)` | `new OrderBook(instrument)` | `grvt.NewOrderBook(instrument, grvt.BookDelta)` | `OrderBook::new(instrument, BookMode::Delta)` |
| `orderbook_snapshot_stream` | `OrderBook(instrument, mode="snapshot")` | `new OrderBook(instrument, "snapshot")` | `grvt.NewOrderBook(instrument, grvt.BookSnapshots)` | `OrderBook::new(instrument, BookMode::Snapshot)` |

- **Delta mode:** after a gap event it refuses reads and updates until you `reset` it
  ([Rebuild a book after a gap](#rebuild-a-book-after-a-gap)). Its `BookError` gives the reason and the gap
  range when known.
- **Snapshot mode:** every frame replaces the whole book, so a gap needs no reset. The book is the last complete
  snapshot received, not a promise that it is live: judge freshness from connection events and the snapshot's
  timestamp.
- The first frame binds the book to its stream and selector: it then rejects other subscriptions' frames and
  ignores their gap events. Before that frame, a delta book takes any gap as its own, so when one client has
  several streams, pass the book only its subscription's events.
- Python and Go books lock internally. In Rust, share one through `Arc<Mutex<OrderBook>>` and keep the event
  callback short.

**`backfill_pages`** pages through REST history after a gap. Your callback picks the endpoint and time window.
Each page carries the gap and a `continuity` field that is always `unproven`: the SDK can't prove the history
covers everything you missed ([Fill missed events from history](#fill-missed-events-from-history)).

**`resolve_order`** looks up an order whose write outcome is unknown, by its client order ID
([When a write's outcome is unknown](errors-and-retries.md#when-a-writes-outcome-is-unknown)).

## Rebuild a book after a gap

**When:** you keep a local order book and the SDK reports a gap on its subscription.

1. Pass the client's events to the book's `on_event`. After a gap on its subscription, a book built from delta
   frames refuses reads and updates.
2. Feed each frame to `apply`. When it fails, or reading the subscription gives an error, stop using the
   book's prices and close the subscription.
3. Open a new subscription and `reset` the book from its first frame, the snapshot.

```python
from grvt import AsyncGrvt, BookError, OrderBook, StreamOverflow

book = OrderBook("BTC_USDT_Perp")


async def keep_book():
    async with AsyncGrvt(env="testnet", on_event=book.on_event) as client:
        while True:
            async with client.orderbook_delta_stream(instrument="BTC_USDT_Perp", rate=500) as sub:  # a fresh subscription
                frames = aiter(sub)
                try:
                    book.reset(await anext(frames))  # the fresh subscription's snapshot
                    async for frame in frames:
                        book.apply(frame)
                        print(book.snapshot().bids[:1])
                except (BookError, StreamOverflow):
                    pass  # a gap: leaving the block unsubscribes; open a fresh subscription
```

```typescript
import { BookError, Grvt, OrderBook, StreamOverflow } from "grvt";

const book = new OrderBook("BTC_USDT_Perp");
const client = new Grvt({ env: "testnet", onEvent: (e) => book.onEvent(e) });
for (;;) {
  const sub = client.orderbookDeltaStream({ instrument: "BTC_USDT_Perp", rate: 500 }); // a fresh subscription
  let first = true;
  try {
    for await (const frame of sub) {
      if (first) book.reset(frame); // the fresh subscription's snapshot
      else book.apply(frame);
      first = false;
      console.log(book.snapshot().bids[0]);
    }
  } catch (e) {
    if (!(e instanceof BookError || e instanceof StreamOverflow)) throw e; // a gap: open a fresh subscription
  } finally {
    await sub.close();
  }
}
```

```go
book, err := grvt.NewOrderBook("BTC_USDT_Perp", grvt.BookDelta)
if err != nil {
	return err
}
client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), OnEvent: book.OnEvent})
if err != nil {
	return err
}
defer client.Close()
for ctx.Err() == nil {
	sub, err := client.OrderbookDeltaStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{
		Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500)}) // a fresh subscription
	if err != nil {
		return err
	}
	first := true
	for frame, err := range sub.All() {
		if err != nil {
			break // overflow or a frame that couldn't be decoded: open a fresh subscription
		}
		if first {
			err = book.Reset(*frame) // the fresh subscription's snapshot
		} else {
			err = book.Apply(*frame)
		}
		first = false
		if err != nil {
			break // a gap: open a fresh subscription
		}
		if snap, err := book.Snapshot(); err == nil {
			fmt.Println(len(snap.Bids), len(snap.Asks))
		}
	}
	sub.Close()
}
```

```rust
use futures::StreamExt;
use grvt::{BookMode, Config, Grvt, OrderBook};
use std::sync::{Arc, Mutex};

let book = Arc::new(Mutex::new(OrderBook::new("BTC_USDT_Perp", BookMode::Delta)));
let hook = book.clone();
let client = Grvt::new(Config::testnet().on_event(move |ev| hook.lock().unwrap().on_event(ev)))?;
loop {
    let mut sub = client.orderbook_delta_stream().instrument("BTC_USDT_Perp").rate(500).await?; // a fresh subscription
    let mut first = true;
    while let Some(frame) = sub.next().await {
        let Ok(frame) = frame else { break }; // overflow or a frame that couldn't be decoded: open a fresh subscription
        let mut book = book.lock().unwrap();
        let applied = if first { book.reset(&frame) } else { book.apply(&frame) }; // first: the snapshot
        first = false;
        if applied.is_err() {
            break; // a gap: dropping `sub` unsubscribes; open a fresh subscription
        }
        if let Ok(snap) = book.snapshot() {
            println!("{:?}", snap.bids.first());
        }
    }
}
```

**Watch out:**

- Reset only from a new subscription's first frame. The old subscription's queue can still hold frames from
  before the gap, even a snapshot, and the helper can't tell where a snapshot came from.
- A frame that can't be decoded is skipped with an error but no gap event. `apply` notices the missing delta
  on the next frame, except right after the snapshot, so treat any read error as a gap.
- A restored book shows current price levels only, not missed fills or other private events.

## Fill missed events from history

**When:** you missed events and want to fill the gap from REST history.

1. Pick the history call and a time window that overlaps your checkpoint: the last point up to which you
   processed every event.

   | Missed | History call | Drop duplicates by |
   |---|---|---|
   | Fills | [fill_history](../reference/rpc/fill_history.md) | `trade_id` |
   | Closed orders | [order_history](../reference/rpc/order_history.md) | `order_id` |
   | Transfers | [transfer_history](../reference/rpc/transfer_history.md) | `tx_id` |

2. Page through it with `backfill_pages`, which follows the cursors for you. Your callback makes one call per
   cursor.
3. Skip anything whose ID you already handled.
4. Compare the result with current [open_orders](../reference/rpc/open_orders.md) and
   [positions](../reference/rpc/positions.md).
5. If the history can't account for the gap, don't move your checkpoint past it: treat the gap as unresolved.

```python
from grvt import backfill_pages

# gap: the gap event's ev.gap. checkpoint: a Timestamp. seen: the trade IDs you already handled.
async for result in backfill_pages(
    lambda cursor: client.fill_history(sub_account_id=sub_account_id, start_time=checkpoint, cursor=cursor),
    gap=gap,
):
    for fill in result.page.result or []:
        if fill.trade_id not in seen:
            seen.add(fill.trade_id)
            handle(fill)
```

```typescript
import { backfillPages } from "grvt";

// gap: the gap event's e.gap. checkpoint: a Timestamp. seen: the trade IDs you already handled.
for await (const { page } of backfillPages(
  (cursor) => client.fillHistory({ sub_account_id: subAccountId, start_time: checkpoint, cursor }),
  gap,
)) {
  for (const fill of page.result ?? []) {
    if (seen.has(fill.trade_id)) continue;
    seen.add(fill.trade_id);
    handle(fill);
  }
}
```

```go
// gap: the gap event's *e.Gap. checkpoint: a time.Time. seen: the trade IDs you already handled.
fetch := func(ctx context.Context, cursor string) (models.ApiFillHistoryResponse, error) {
	resp, err := client.FillHistory(ctx, &models.ApiFillHistoryRequest{
		SubAccountID: subAccountID, StartTime: &checkpoint, Cursor: cursor})
	if err != nil {
		return models.ApiFillHistoryResponse{}, err
	}
	return *resp, nil
}
for result, err := range grvt.BackfillPages(ctx, fetch, gap) {
	if err != nil {
		return err
	}
	for _, fill := range result.Page.Result {
		if !seen[fill.TradeID] {
			seen[fill.TradeID] = true
			handle(fill)
		}
	}
}
```

```rust
use futures::StreamExt;
use grvt::backfill_pages;

// gap: the gap event's gap. checkpoint: a grvt::Timestamp. seen: the trade IDs you already handled.
let pages = backfill_pages(
    |cursor: Option<String>| {
        let call = client.fill_history().sub_account_id(sub_account_id).start_time(checkpoint);
        let call = match cursor {
            Some(cursor) => call.cursor(cursor),
            None => call,
        };
        async move { call.await }
    },
    gap,
);
futures::pin_mut!(pages);
while let Some(result) = pages.next().await {
    for fill in result?.page.result.unwrap_or_default() {
        if seen.insert(fill.trade_id.clone()) {
            handle(fill);
        }
    }
}
```

**Watch out:**

- `backfill_pages` marks every page `continuity="unproven"`, even an empty last page. Running out of cursors
  only means this pass has no more pages; delayed history may still appear. Don't wait for "proven".
- A WebSocket sequence number is not a REST cursor or a timestamp. Don't use it to page history.

## Run the recovery walkthrough

1. Install the Python SDK ([installation instructions](../sdks/python.md)).
2. Download this example.
3. Run `python recovery.py`.

It runs offline on recorded frames and pages, not against the exchange. It shows that a book with a gap
refuses reads and queued frames, that a new snapshot restores the book, and that history with no more pages
still can't prove it covers every missed event.

[Download this example](../downloads/examples/python/examples/recovery.py)

```python
"""Offline recovery walkthrough. Run with the installed grvt package; no keys needed."""

from dataclasses import dataclass
from decimal import Decimal

from grvt import BookError, Event, EventKind, GapRange, OrderBook, Timestamp, backfill_pages_sync, models


def snapshot(price: str) -> models.WSOrderbookLevelsFeedDataV1:
    # A fixture stands in for a snapshot from a newly opened subscription.
    return models.WSOrderbookLevelsFeedDataV1(
        stream="v1.book.d",
        selector="BTC_USDT_Perp@500",
        sequence_number="0",
        prev_sequence_number="0",
        feed=models.OrderbookLevels(
            event_time=Timestamp(0),
            instrument="BTC_USDT_Perp",
            bids=[models.OrderbookLevel(price=Decimal(price), size=Decimal("1"), num_orders=1)],
            asks=[],
        ),
    )


def recover_book() -> None:
    book = OrderBook("BTC_USDT_Perp")
    old_snapshot = snapshot("100")
    book.apply(old_snapshot)
    gap = GapRange(after_sequence=10, through_sequence=None, reason="disconnect")
    # Forward the hook event before consuming more frames from the subscription.
    book.on_event(Event(kind=EventKind.GAP, stream=old_snapshot.stream, selector=old_snapshot.selector, gap=gap))
    for operation in (book.snapshot, lambda: book.apply(old_snapshot)):
        try:
            operation()
        except BookError:
            pass
        else:
            raise AssertionError("a gapped book must reject reads and queued frames")
    # In a live application: close the old subscription, open a fresh one, then
    # read its snapshot. Do not use reset to accept a frame from the old queue.
    fresh_snapshot = snapshot("101")
    book.reset(fresh_snapshot)
    assert book.snapshot().bids[0].price == Decimal("101")
    print("fresh snapshot restored book; missed private events remain unresolved")


@dataclass
class HistoryPage:
    next: str | None
    events: tuple[str, ...]


def inspect_history() -> None:
    gap = GapRange(after_sequence=10, through_sequence=None, reason="disconnect")
    pages = {None: HistoryPage("second-page", ("fill-1",)), "second-page": HistoryPage(None, ())}
    calls: list[str | None] = []

    def fetch(cursor: str | None) -> HistoryPage:
        # In a live application this callback chooses the history endpoint,
        # account and overlapping time window. A sequence is not a REST cursor.
        calls.append(cursor)
        return pages[cursor]

    for result in backfill_pages_sync(fetch, gap=gap):
        assert result.continuity == "unproven"
        print("history", result.page.events, "exhausted", result.history_exhausted, result.continuity)
    assert calls == [None, "second-page"]
    # An empty final page is not proof that delayed events cannot appear later.
    assert result.history_exhausted and result.continuity == "unproven"


if __name__ == "__main__":
    recover_book()
    inspect_history()
```
