# StreamTwapStatuses - Real-time TWAP Status Streaming

Stream TWAP order lifecycle events starting from a position, providing real-time access to TWAP state updates across Hyperliquid.

Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js.

## When to Use This Method

`StreamTwapStatuses` is essential for:

- **TWAP Lifecycle Tracking** - Follow TWAP orders as their state changes
- **Execution Monitoring** - Track executed size and notional over time
- **Strategy Analytics** - Reconstruct TWAP execution progress across blocks
- **Compliance and Auditing** - Record TWAP status transitions with block alignment

`StreamTwapStatuses` reports lifecycle changes after the order exists on HyperCore. To decode the signed request that created or canceled a TWAP, pair this stream with [twapOrder](https://www.dwellir.com/docs/hyperliquid/twapOrder) and [twapCancel](https://www.dwellir.com/docs/hyperliquid/twapCancel) actions from [StreamBlocks](https://www.dwellir.com/docs/hyperliquid/stream_blocks).

Method signature

```protobuf
rpc StreamTwapStatuses(StreamRequest) returns (stream Record) {}
```

V3 accepts an inclusive `position.block_number` or Unix-millisecond `position.timestamp`. Explicit zero is invalid. A positioned call replays inclusively and then tails live; an empty request tails newly written TWAP status records. Set `progress` to opt in to [progress frames](#progress-frames).

```protobuf
filter: {
  fields: {
    field: "coins"
    op: FILTER_OP_IN
    values: "BTC"
  }
}
```

TWAP statuses accept `users`, `coins` and `dexes` filters. User matching is case-insensitive, coin matching is case-sensitive and dex matching is exact on the HIP-3 dex prefix; values within a field use OR semantics and separate fields use AND semantics. Records with zero matching events are skipped. Each `Record` contains optional `block_number` and `timestamp` cursors plus the filtered envelope in `data`. A pruned position returns `NOT_FOUND`; malformed filters return `INVALID_ARGUMENT`.

## V3 reference

### Request Parameters

- `position.timestamp` (`int64, optional`): Inclusive V3 Unix-millisecond cursor. Omit the position to tail newly written records.
- `position.block_number` (`int64, optional`): Inclusive V3 sequential block cursor. Explicit zero is invalid.
- `filter.fields` (`FieldFilter[], optional`): V3 users/coins constraints. Fields AND together; values within one field OR together.
- `filter.fields.field` (`string, required`): Feed-advertised filter field name, either users or coins.
- `filter.fields.op` (`FilterOp, optional`): FILTER_OP_UNSPECIFIED or FILTER_OP_IN.
- `filter.fields.values` (`string[], required`): One or more accepted values; entries within the list use OR semantics.
- `progress.interval_ms` (`uint32, optional`): Set progress to opt in to progress frames; leave it unset for none. Longest silence in milliseconds before a progress frame. 0 selects the feed default, currently 20000 within bounds of 10000 to 60000; ListFeeds reports the bounds in FeedInfo.progress.

### Request Example

```bash
grpcurl \
  -import-path content/docs/hyperliquid/grpc \
  -proto v3.proto \
  -H "x-api-key: ${DWELLIR_API_KEY}" \
  -d '{"position":{"block_number":"1058646974"},"filter":{"fields":[{"field":"coins","op":"FILTER_OP_IN","values":["BTC"]}]}}' \
  "${HYPERLIQUID_GRPC_ENDPOINT}" \
  hyperliquid_l1_gateway.v3.HyperliquidL1Gateway/StreamTwapStatuses
```

### Response Fields

- `block_number` (`optional int64, optional`): Sequential Hyperliquid block cursor; never the HyperBFT consensus round.
- `timestamp` (`optional int64, optional`): Record time in Unix milliseconds.
- `data` (`bytes, required`): Bytes from the node_twap_statuses_by_block, with non-matching events removed when a filter is applied.
- `progress` (`StreamProgress, optional`): Set only on progress frames, which leave data, block_number, and timestamp unset. Check it before decoding data.
- `progress.scanned_through.block_number` (`int64, optional`): Inclusive cursor of the newest block the stream examined, sent or removed by the filter. A valid resume position; unset until the stream has examined a record.
- `progress.timestamp` (`optional int64, optional`): Source time at scanned_through in Unix milliseconds.

### Successful Response

```protobuf
block_number: 1058646974
timestamp: 1785736814057
data: "{\"block_number\":1058646974,\"events\":[]}"
```

### Error Responses

#### Invalid argument

- Code: `INVALID_ARGUMENT`
- Description: A cursor is zero or malformed, or a filter has an unsupported field, duplicate field, empty name, or empty value list.

#### Invalid progress request

- Code: `INVALID_ARGUMENT`
- Description: A nonzero progress.interval_ms is outside the bounds advertised in FeedInfo.progress.

#### Not found

- Code: `NOT_FOUND`
- Description: Available replay history varies by feed and endpoint. A cursor outside retained history returns NOT_FOUND.

#### Replay capacity exhausted

- Code: `RESOURCE_EXHAUSTED`
- Description: Replay capacity is temporarily unavailable; retry with backoff.

#### Filter operator not implemented

- Code: `UNIMPLEMENTED`
- Description: The requested filter operator is well formed but is not implemented by this gateway version.

#### Stream unavailable

- Code: `UNAVAILABLE`
- Description: No new records arrived before the stream timeout, or the stream failed mid-stream. Progress frames do not reset the timeout. Reconnect from the last cursor received.

#### Records lost

- Code: `DATA_LOSS`
- Description: The stream lost records, for example because it fell behind the live feed. It ends before sending any cursor past them; reconnect from the last cursor received to re-read the gap.

#### Slow consumer

- Code: `DEADLINE_EXCEEDED`
- Description: The stream could not deliver records in time because the client read too slowly or stopped reading; reconnect from the last processed cursor.

#### Unauthenticated

- Code: `UNAUTHENTICATED`
- Description: The request did not include usable authentication metadata.

#### Permission denied

- Code: `PERMISSION_DENIED`
- Description: The supplied credential is not permitted to call this service.

## V2 reference

### Request Parameters

- `timestamp_ms` (`int64, optional`): Inclusive Unix-millisecond cursor. Omit it to start from the latest data and continue streaming.
- `block_height` (`int64, optional`): Inclusive block-height cursor. Omit it to start from the latest data and continue streaming.

### Request Example

```bash
grpcurl \
  -import-path content/docs/hyperliquid/grpc \
  -proto v2.proto \
  -H "x-api-key: ${DWELLIR_API_KEY}" \
  -d '{"block_height":"1058646974"}' \
  "${HYPERLIQUID_GRPC_ENDPOINT}" \
  hyperliquid_l1_gateway.v2.HyperliquidL1Gateway/StreamTwapStatuses
```

### Response Fields

- `data` (`bytes, required`): JSON-encoded payload returned in the V2 BlockTwapStatuses wrapper.

### Successful Response

```protobuf
message BlockTwapStatuses {
  bytes data = 1;
}
```

```protobuf
rpc StreamTwapStatuses(Position) returns (stream BlockTwapStatuses) {}
```

V2 accepts the inclusive cursor fields `block_height` and `timestamp_ms`; an empty `Position` tails new TWAP status records. It returns the source JSON in `BlockTwapStatuses.data`.

## Response Stream

V3 carries the JSON-encoded `node_twap_statuses_by_block` envelope in `Record.data`.

V2 carries the JSON-encoded `node_twap_statuses_by_block` envelope in `BlockTwapStatuses.data`.

Decode the `data` field to access:

- Block reference (`local_time`, `block_time`, `block_number`)
- An `events` array of TWAP status records
- A TWAP state object behind each lifecycle update

## Per-Block Delivery

`StreamTwapStatuses` emits one message per source block-envelope record, including records with an empty `events` array. Most blocks do not contain a TWAP lifecycle update, so empty envelopes are normal. They still let consumers advance their cursor and confirm exactly which block was last processed.

V3 clients must detect discontinuities and duplicates and persist only cursors present on `Record`. Reconnect with `StreamRequest.position.block_number` or `position.timestamp`; replay is inclusive.

V2 clients reconnect with the next `block_height` or a `timestamp_ms` in `Position`. Both are inclusive; an empty or zero `Position` targets the latest data.

## Full TWAP Status Spec

`StreamTwapStatuses` emits a JSON payload matching Hyperliquid's `node_twap_statuses_by_block` format, passed through byte-for-byte from the node with no normalization. The envelope is the same block-envelope shape as fills, but `events` holds TWAP lifecycle objects rather than fill tuples.

Top-level keys (always present):

```json
{
  "local_time": "2026-07-03T06:00:14.508835456",
  "block_time": "2026-07-03T06:00:14.057132297",
  "block_number": 1058646974,
  "events": [
    {
      "time": "2026-07-03T06:00:14.057132297",
      "twap_id": 1999381,
      "state": {
        "coin": "kPEPE",
        "user": "0x2ee1f7d5650bb9bc08e101dc5ab2300b4f5c1be9",
        "side": "B",
        "sz": "555555.0",
        "executedSz": "555555.0",
        "executedNtl": "1371.51378",
        "minutes": 5,
        "reduceOnly": false,
        "randomize": false,
        "timestamp": 1783058112775
      },
      "status": "finished"
    }
  ]
}
```

Status event fields (`events[i]`):

| Field     | Type             | Description                                                                      |
| --------- | ---------------- | -------------------------------------------------------------------------------- |
| `time`    | string           | Event timestamp in the no-`Z` layout. A string, not an integer millisecond value |
| `twap_id` | number           | TWAP order identifier                                                            |
| `state`   | object           | TWAP state at the lifecycle update. See [TWAP State Object](#twap-state-object)  |
| `status`  | string or object | Lifecycle status. See [Status Values](#status-values)                            |

Every event is global, not user-scoped to the API key. Filter by `state.user`, `state.coin`, or `twap_id` in your application when you only need a subset.

### TWAP State Object

| Field         | Type    | Description                                      |
| ------------- | ------- | ------------------------------------------------ |
| `coin`        | string  | Coin identifier                                  |
| `user`        | string  | User address                                     |
| `side`        | string  | `"B"` for buy, `"A"` for sell                    |
| `sz`          | string  | Target TWAP size as a numeric string             |
| `executedSz`  | string  | Executed size so far as a numeric string         |
| `executedNtl` | string  | Executed notional so far as a numeric string     |
| `minutes`     | number  | TWAP duration in minutes                         |
| `reduceOnly`  | boolean | Whether the TWAP is reduce-only                  |
| `randomize`   | boolean | Whether the TWAP randomizes slice timing or size |
| `timestamp`   | number  | TWAP creation time in Unix milliseconds          |

The `state` object is a snapshot of the TWAP at the lifecycle event, not a fill-by-fill execution log. Use `executedSz` and `executedNtl` to measure aggregate progress for that TWAP at the event boundary. For individual trade executions, consume [StreamFills](https://www.dwellir.com/docs/hyperliquid/stream_fills) and join on user, coin, and time windows according to your own strategy model.

### Status Values

Observed string `status` values include:

| Status       | Meaning                                                          |
| ------------ | ---------------------------------------------------------------- |
| `activated`  | TWAP order became active                                         |
| `finished`   | TWAP execution completed or otherwise reached its terminal state |
| `terminated` | TWAP order was terminated before normal completion               |

`status` can also be an object when the lifecycle update carries an error:

```json
{
  "status": {
    "error": "Reduce only order would increase position."
  }
}
```

Treat the `status` set as non-exhaustive. Hyperliquid can add new lifecycle states and error payloads over time.

### Lifecycle Examples

An `activated` event starts a TWAP lifecycle. At activation, `executedSz` and `executedNtl` are typically zero:

```json
{
  "time": "2026-07-03T06:00:30.373151284",
  "twap_id": 1999392,
  "state": {
    "coin": "xyz:NBIS",
    "user": "0x6f97b7de6be7b7771e975e46bae96c35e332e172",
    "side": "B",
    "sz": "226.72",
    "executedSz": "0.0",
    "executedNtl": "0.0",
    "minutes": 7,
    "reduceOnly": false,
    "randomize": false,
    "timestamp": 1783058430373
  },
  "status": "activated"
}
```

A `terminated` event records the final observed state when a TWAP stops before normal completion. Partial execution is visible through `executedSz` and `executedNtl`:

```json
{
  "time": "2026-07-03T06:02:08.835250901",
  "twap_id": 1999394,
  "state": {
    "coin": "xyz:NBIS",
    "user": "0x6f97b7de6be7b7771e975e46bae96c35e332e172",
    "side": "B",
    "sz": "226.7",
    "executedSz": "60.45",
    "executedNtl": "13377.625",
    "minutes": 7,
    "reduceOnly": false,
    "randomize": false,
    "timestamp": 1783058434767
  },
  "status": "terminated"
}
```

Guarantees and alignment:

- `events` contains TWAP status records from the block across all users.
- Messages arrive in strictly increasing `block_number`, one per source block-envelope record.
- `block_number` is sequential and distinct from the potentially skipping `abci_block.round` consensus value in StreamBlocks; `block_time` aligns with `abci_block.time`.

Developer tips:

- Use `twap_id` as the primary key for TWAP lifecycle state.
- Parse `sz`, `executedSz`, and `executedNtl` as decimals to avoid precision loss.
- Treat `time` as a formatted string, distinct from the integer-millisecond `timestamp` inside `state`.
- Handle empty `events` arrays; quiet blocks are normal.
- Store the raw block envelope if you need reproducible audits; the gateway does not normalize or reshape the node payload.

## Common Use Cases

### 1. TWAP Lifecycle Index

```python
from decimal import Decimal

def apply_twap_status(block, index):
    for event in block.get('events', []):
        state = event['state']
        target = Decimal(state['sz'])
        executed = Decimal(state['executedSz'])

        status = event['status']
        status_key = status if isinstance(status, str) else 'error'

        index[event['twap_id']] = {
            'status': status,
            'status_key': status_key,
            'user': state['user'],
            'coin': state['coin'],
            'side': state['side'],
            'target_size': target,
            'executed_size': executed,
            'progress': executed / target if target else Decimal('0'),
            'block_number': block['block_number'],
            'block_time': block['block_time'],
        }
```

### 2. TWAP Alert Stream

```python
def alert_on_terminal_twaps(block):
    for event in block.get('events', []):
        status = event['status']
        if status not in ('finished', 'terminated') and not isinstance(status, dict):
            continue

        state = event['state']
        status_label = status.get('error', 'error') if isinstance(status, dict) else status
        print(
            f"{status_label} twap={event['twap_id']} "
            f"user={state['user']} coin={state['coin']} "
            f"executed={state['executedSz']}/{state['sz']}"
        )
```

### 3. Streaming TWAP Statuses in Python

Open V3 with an empty `StreamRequest` to tail newly written records, or set `StreamRequest.position.block_number` for inclusive replay. Decode each `Record.data` envelope and apply it with the lifecycle-index helper above.

```python
import grpc
import json
import os
from decimal import Decimal
import hyperliquid_pb2
import hyperliquid_pb2_grpc

def apply_twap_status(block, index):
    for event in block.get('events', []):
        state = event['state']
        target = Decimal(state['sz'])
        executed = Decimal(state['executedSz'])

        status = event['status']
        status_key = status if isinstance(status, str) else 'error'

        index[event['twap_id']] = {
            'status': status,
            'status_key': status_key,
            'user': state['user'],
            'coin': state['coin'],
            'side': state['side'],
            'target_size': target,
            'executed_size': executed,
            'progress': executed / target if target else Decimal('0'),
            'block_number': block['block_number'],
        }

def stream_twap_statuses():
    endpoint = os.getenv('HYPERLIQUID_ENDPOINT')
    api_key = os.getenv('API_KEY')

    credentials = grpc.ssl_channel_credentials()
    options = [('grpc.max_receive_message_length', 150 * 1024 * 1024)]  # 150MB max
    metadata = [('x-api-key', api_key)]

    with grpc.secure_channel(endpoint, credentials, options=options) as channel:
        client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel)

        # Empty Position means latest; set block_height or timestamp_ms to backfill
        request = hyperliquid_pb2.Position()

        twaps = {}

        for response in client.StreamTwapStatuses(request, metadata=metadata):
            block = json.loads(response.data)
            apply_twap_status(block, twaps)
```

## Progress Frames

Progress frames are an application-level heartbeat. Set `StreamRequest.progress` to receive one after each interval of silence. A `users` or `coins` filter can leave the stream silent for minutes. They keep it open through idle-limited proxies, which HTTP/2 keepalive pings do not, and advance your resume cursor through blocks the filter removed.

A progress frame sets `Record.progress.scanned_through.block_number` and leaves the data fields unset, so check `progress` before decoding `data`. Persist `scanned_through` as an inclusive resume cursor. See [progress frames](https://www.dwellir.com/docs/hyperliquid/grpc#progress-frames) for the full contract.

V2 streams do not send progress frames. Use the V3 method to opt in.

## Error Handling and Reconnection

Reconnect with `StreamRequest.position.block_number` set to the last committed V3 cursor, from a data record or a progress frame's `scanned_through`. Replay is inclusive, so deduplicate that record before advancing.

Reconnect by replaying from the last processed block. Pass the next `block_height` in the `Position` so no events are skipped or duplicated.

```python
def stream_with_resume(client, metadata, start_block):
    next_block = start_block
    while True:
        request = hyperliquid_pb2.Position(block_height=next_block)
        try:
            for response in client.StreamTwapStatuses(request, metadata=metadata):
                block = json.loads(response.data)
                process(block)
                next_block = block['block_number'] + 1
        except grpc.RpcError as e:
            print(f"stream error, resuming from {next_block}: {e}")
```

## Best Practices

1. **Connection Management**: Implement robust reconnection logic with exponential backoff
2. **Resumable State**: Follow the version-specific recovery guidance above and persist the cursor required by your selected API version
3. **Stable Keys**: Index TWAP lifecycle state on `twap_id`
4. **Defensive Parsing**: Handle empty `events` arrays, unknown future string statuses, and object status payloads
5. **Numeric Precision**: Parse numeric strings with decimal-safe types
6. **Action Correlation**: Join with [StreamBlocks](https://www.dwellir.com/docs/hyperliquid/stream_blocks) when you need the original signed `twapOrder` or `twapCancel` action
7. **Selective Storage**: Store terminal events and the last active state if you do not need every empty envelope

## Current Limitations

- **Replay History**: Available replay history varies by feed and endpoint. A cursor outside retained history returns `NOT_FOUND`
- **Schema Coverage**: The upstream lifecycle set can grow; treat documented statuses as examples, not an exhaustive list
- **Backpressure**: High-volume periods may require careful handling to avoid overwhelming downstream systems

## Resources

- **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples
- **[GetTwapStatuses](https://www.dwellir.com/docs/hyperliquid/get_twap_statuses)** - Point-in-time TWAP status retrieval
- **[twapOrder Action Type](https://www.dwellir.com/docs/hyperliquid/twapOrder)** - TWAP order submission payloads in StreamBlocks
- **[twapCancel Action Type](https://www.dwellir.com/docs/hyperliquid/twapCancel)** - TWAP cancellation payloads in StreamBlocks

*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](https://www.dwellir.com/docs/hyperliquid/grpc).*
