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

# Python

> Connect to Anthid's Streaming API using Python.

Anthid provides generated Protocol Buffer definitions that can be used to build Python clients for the Streaming API.

This guide demonstrates how to generate the Python gRPC client and subscribe to real-time trading events.

## Prerequisites

Install the required Python packages.

```bash theme={null}
python -m pip install grpcio grpcio-tools protobuf
```

## Download the Protobuf Definitions

Clone the Anthid protobuf repository.

```bash theme={null}
git clone https://github.com/anthid-labs/proto.git anthid-proto
```

## Generate Python Client Code

Generate Python classes from the protobuf definitions.

```bash theme={null}
cd anthid-proto

mkdir -p ../generated/python

python -m grpc_tools.protoc \
  -I . \
  --python_out=../generated/python \
  --grpc_python_out=../generated/python \
  $(find . -name "*.proto")
```

The generated output contains the protobuf message definitions and gRPC service stubs required to interact with Anthid services.

## Authentication

Streaming requests are authenticated using an API key passed as gRPC metadata.

```python theme={null}
metadata = (
    ("x-api-key", "YOUR_API_KEY"),
)
```

## Subscribe to Events

The example below demonstrates connecting to the server-streaming endpoint and subscribing to broker order and position events.

```python theme={null}
import grpc

from generated import trading_pb2
from generated import trading_pb2_grpc


API_KEY = "YOUR_API_KEY"

request = trading_pb2.Subscribe(
    trading_account_id="YOUR_TRADING_ACCOUNT_ID",
    subscriptions=[
        trading_pb2.EVENT_TYPE_BROKER_ORDER,
        trading_pb2.EVENT_TYPE_BROKER_POSITION,
    ],
)

credentials = grpc.ssl_channel_credentials()

with grpc.secure_channel(
    "stream.anthid.com:443",
    credentials,
) as channel:
    stub = trading_pb2_grpc.TradingServiceStub(
        channel,
    )

    stream = stub.SubscribeEvents(
        request,
        metadata=(
            ("x-api-key", API_KEY),
        ),
    )

    for event in stream:
        if event.HasField("heartbeat"):
            print("heartbeat")

        elif event.HasField("status"):
            print(
                "status:",
                event.status.message,
            )

        elif event.HasField("error"):
            print(
                "error:",
                event.error.message,
            )

        elif event.HasField("broker_order"):
            print(
                "order:",
                event.broker_order,
            )

        elif event.HasField("broker_position"):
            print(
                "position:",
                event.broker_position,
            )
```

## Bidirectional Streaming

Backend and native applications may prefer the bidirectional `StreamEvents` endpoint.

This endpoint allows subscriptions and unsubscriptions to be sent over an existing stream without creating a new connection.

```python theme={null}
import grpc

from generated import trading_pb2
from generated import trading_pb2_grpc


def requests():
    yield trading_pb2.StreamEventsRequest(
        subscribe=trading_pb2.Subscribe(
            trading_account_id=
                "YOUR_TRADING_ACCOUNT_ID",
            subscriptions=[
                trading_pb2.EVENT_TYPE_BROKER_ORDER,
                trading_pb2.EVENT_TYPE_BROKER_POSITION,
            ],
        )
    )

    while True:
        pass


credentials = grpc.ssl_channel_credentials()

with grpc.secure_channel(
    "stream.anthid.com:443",
    credentials,
) as channel:
    stub = trading_pb2_grpc.TradingServiceStub(
        channel,
    )

    stream = stub.StreamEvents(
        requests(),
        metadata=(
            ("x-api-key", "YOUR_API_KEY"),
        ),
    )

    for event in stream:
        print(event)
```

## Handling Disconnects

Applications should automatically reconnect when a stream is interrupted.

After reconnecting:

1. Establish a new stream.
2. Re-authenticate using the API key.
3. Re-subscribe to required trading accounts.
4. Resume event processing.

## Related Resources

* Streaming Overview
* Trading Accounts
* Orders
* Positions
* Ledger
* Intents
