Skip to main content

Codec

ib_interface.protobuf.codec

Protobuf encoding/decoding utilities for TWS API.

This module provides the core infrastructure for Protocol Buffer communication while preserving ib-interface's asyncio architecture.

ProtobufCodec

Encode and decode Protobuf messages for TWS API communication.

The TWS API uses a specific framing format:

  • 4-byte length prefix (big-endian)
  • Message ID (0 for protobuf)
  • Message type identifier
  • Serialized protobuf bytes

encode

def encode(msg: Message, msg_type_id: int) -> bytes

Encode a Protobuf message for transmission to TWS.

Frame format: [length:4][msgId:1][typeId:2][payload:n]

Args: msg: The protobuf message to encode. msg_type_id: The TWS message type identifier.

Returns: Bytes ready for socket transmission.

decode

def decode(data: bytes, msg_class: Type[T]) -> T

Decode a Protobuf message received from TWS.

Args: data: Raw protobuf bytes (after framing removed). msg_class: The protobuf message class to decode into.

Returns: Deserialized protobuf message of type T.

Raises: DecodeError: If the data cannot be parsed as the given message type.

is_protobuf_message

def is_protobuf_message(fields: list) -> bool

Detect if incoming fields represent a Protobuf message.

The TWS API uses message ID 0 to indicate protobuf format. Legacy string-based messages use non-zero message IDs.

Args: fields: List of decoded message fields from the wire.

Returns: True if the message is protobuf format, False otherwise.