Skip to main content
This document provides detailed information about the data objects used in the Perpetuals SDK.

Core Data Objects

Order

The primary data object representing a trading order in the perpetuals platform.

Fields

FieldTypeDescription
order_idint32Unique identifier for the order
ownerstringThe owner identifier for the order
timestampstringOrder creation timestamp (ISO 8601 format)
market_idint32Identifier for the trading market
marketstringHuman-readable market name (e.g., “BTC-PERP”)
typeOrderTypeType of order (MARKET, LIMIT, etc.)
sideSideOrder side (LONG or SHORT)
threshold_pricefloatPrice threshold for order execution
sizefloatOrder size/quantity
leverageint32Leverage multiplier
statusOrderStatusCurrent order status
filled_sizefloatAmount of the order that has been filled
reduce_onlyboolWhether this is a reduce-only order

Example

from forte_perpetuals_sdk.generated.base_objects.v1.order_pb2 import (
    Order, OrderType, Side, OrderStatus
)

# Create a sample order
order = Order(
    order_id=789,
    owner="trader_123",
    timestamp="2024-11-07T12:00:00Z",
    market_id=1,
    market="BTC-PERP",
    type=OrderType.ORDER_TYPE_MARKET,
    side=Side.SIDE_LONG,
    threshold_price=75000.0,
    size=0.5,
    leverage=10,
    status=OrderStatus.ORDER_STATUS_PENDING,
    filled_size=0.0,
    reduce_only=False
)

Position

The data object representing an open trading position in the perpetuals platform.

Fields

FieldTypeDescription
ownerstringThe owner identifier for the position
market_idint32Identifier for the trading market
marketstringHuman-readable market name (e.g., “BTC-PERP”)
sideSidePosition side (LONG or SHORT)
sizefloatPosition size/quantity
leverageint32Leverage multiplier for the position
entry_pricefloatAverage entry price for the position
mark_pricefloatCurrent mark price for the position
unrealized_pnlfloatUnrealized profit and loss
realized_pnlfloatRealized profit and loss
margin_typeMarginTypeType of margin (CROSS or ISOLATED)
margin_amountfloatAmount of margin allocated to the position
liquidation_pricefloatPrice at which position would be liquidated
timestampstringPosition creation/update timestamp (ISO 8601 format)

Example

from forte_perpetuals_sdk.generated.base_objects.v1.position_pb2 import Position
from forte_perpetuals_sdk.generated.base_objects.v1.enums_pb2 import Side, MarginType

# Create a sample position
position = Position(
    owner="trader_123",
    market_id=1,
    market="BTC-PERP",
    side=Side.SIDE_LONG,
    size=0.5,
    leverage=10,
    entry_price=75000.0,
    mark_price=76000.0,
    unrealized_pnl=500.0,
    realized_pnl=0.0,
    margin_type=MarginType.MARGIN_TYPE_CROSS,
    margin_amount=3750.0,
    liquidation_price=68000.0,
    timestamp="2024-11-07T12:00:00Z"
)

GetOrderRequest

Request object for retrieving order information.

Fields

FieldTypeDescription
order_idint32The unique order identifier to retrieve
market_idint32The market identifier where the order exists
reduce_onlyboolFilter for reduce-only orders

Example

from forte_perpetuals_sdk.generated.get_order.v1.get_order_pb2 import GetOrderRequest

request = GetOrderRequest(
    order_id=123,
    market_id=1,
    reduce_only=False
)

GetOrderResponse

Response object containing order information.

Fields

FieldTypeDescription
orderOrderThe requested order object

Example

from forte_perpetuals_sdk.generated.get_order.v1.get_order_pb2 import GetOrderResponse

# Response would be received from API call
response = GetOrderResponse(
    order=order  # Order object as defined above
)

GetOrdersRequest

Request object for retrieving multiple orders with filtering options.

Fields

FieldTypeDescription
ownerstringFilter orders by owner identifier
market_idint32Filter orders by market identifier
sideSideFilter orders by side (optional)
statusOrderStatusFilter orders by status (optional)
limitint32Maximum number of orders to return

Example

from forte_perpetuals_sdk.generated.get_orders.v1.get_orders_pb2 import GetOrdersRequest
from forte_perpetuals_sdk.generated.base_objects.v1.enums_pb2 import Side

request = GetOrdersRequest(
    owner="trader_123",
    market_id=1,
    side=Side.SIDE_LONG,
    limit=50
)

GetOrdersResponse

Response object containing multiple orders.

Fields

FieldTypeDescription
ordersrepeated OrderList of order objects matching the request criteria

Example

from forte_perpetuals_sdk.generated.get_orders.v1.get_orders_pb2 import GetOrdersResponse

# Response would be received from API call
response = GetOrdersResponse(
    orders=[order1, order2, order3]  # List of Order objects
)

GetOpenPositionsRequest

Request object for retrieving open positions with filtering options.

Fields

FieldTypeDescription
ownerstringFilter positions by owner identifier
market_idint32Filter positions by market identifier (optional)
sideSideFilter positions by side (optional)

Example

from forte_perpetuals_sdk.generated.get_open_positions.v1.get_open_positions_pb2 import GetOpenPositionsRequest
from forte_perpetuals_sdk.generated.base_objects.v1.enums_pb2 import Side

request = GetOpenPositionsRequest(
    owner="trader_123",
    market_id=1,
    side=Side.SIDE_LONG
)

GetOpenPositionsResponse

Response object containing open positions.

Fields

FieldTypeDescription
positionsrepeated PositionList of position objects matching the request criteria

Example

from forte_perpetuals_sdk.generated.get_open_positions.v1.get_open_positions_pb2 import GetOpenPositionsResponse

# Response would be received from API call
response = GetOpenPositionsResponse(
    positions=[position1, position2]  # List of Position objects
)

Enums

OrderType

Defines the type of order being placed.
ValueDescription
ORDER_TYPE_MARKETMarket order - executes immediately at current market price

Side

Defines the direction of the order.
ValueDescription
SIDE_LONGLong position - betting price will go up
SIDE_SHORTShort position - betting price will go down

OrderStatus

Defines the current status of an order.
ValueDescription
ORDER_STATUS_PENDINGOrder has been submitted but not yet processed
ORDER_STATUS_PARTIALLY_FILLEDOrder has been partially executed
ORDER_STATUS_FULLY_FILLEDOrder has been completely executed
ORDER_STATUS_CLOSEDOrder has been closed
ORDER_STATUS_CANCELLEDOrder has been cancelled

TimeInForce

Defines how long an order remains active.
ValueDescription
TIME_IN_FORCE_GTCGood Till Cancelled - order remains active until filled or cancelled

MarginType

Defines the type of margin used for a position.
ValueDescription
MARGIN_TYPE_CROSSCross margin - uses entire account balance as collateral
MARGIN_TYPE_ISOLATEDIsolated margin - uses only allocated margin as collateral

Working with Data Objects

Converting to Python Dictionaries

Use the utility functions to convert protobuf objects to Python dictionaries:
from forte_perpetuals_sdk.utils import order_to_dict, position_to_dict

# Convert order to dictionary with human-readable enum values
order_dict = order_to_dict(order)
print(order_dict['status'])  # Prints "FULLY_FILLED" instead of enum number

# Convert position to dictionary with human-readable enum values
position_dict = position_to_dict(position)
print(position_dict['margin_type'])  # Prints "CROSS" instead of enum number

Enum Conversions

The SDK provides utility enums that can convert from protobuf enum values:
from forte_perpetuals_sdk.utils import OrderType, Side, OrderStatus, MarginType
from forte_perpetuals_sdk.generated.base_objects.v1.enums_pb2 import (
    OrderType as ProtoOrderType,
    Side as ProtoSide,
    OrderStatus as ProtoOrderStatus,
    MarginType as ProtoMarginType
)

# Convert from protobuf enum to Python enum
order_type = OrderType.from_proto(ProtoOrderType.ORDER_TYPE_MARKET)
side = Side.from_proto(ProtoSide.SIDE_LONG)
status = OrderStatus.from_proto(ProtoOrderStatus.ORDER_STATUS_PENDING)
margin_type = MarginType.from_proto(ProtoMarginType.MARGIN_TYPE_CROSS)

print(order_type.value)   # Prints "MARKET"
print(side.value)         # Prints "LONG"
print(status.value)       # Prints "PENDING"
print(margin_type.value)  # Prints "CROSS"

Formatting for Display

Use the formatting utilities for human-readable summaries:
from forte_perpetuals_sdk.utils import format_order_summary, format_position_summary

# Format order summary
order_summary = format_order_summary(order)
print(order_summary)
# Output: "Order #789 (BTC-PERP): LONG 0.5 @ $75,000.00 - Status: PENDING"

# Format position summary
position_summary = format_position_summary(position)
print(position_summary)
# Output: "Position (BTC-PERP): LONG 0.5 @ $75,000.00, PnL: +$500.00 (CROSS margin)"

Type Safety

All data objects are fully typed for use with mypy and other type checkers:
from typing import Optional, List
from forte_perpetuals_sdk.generated.base_objects.v1.order_pb2 import Order
from forte_perpetuals_sdk.generated.base_objects.v1.position_pb2 import Position
from forte_perpetuals_sdk.generated.base_objects.v1.enums_pb2 import OrderStatus

def process_order(order: Order) -> Optional[float]:
    """Process an order and return the total value."""
    if order.status == OrderStatus.ORDER_STATUS_FULLY_FILLED:
        return order.size * order.threshold_price
    return None

def calculate_portfolio_pnl(positions: List[Position]) -> float:
    """Calculate total unrealized PnL across all positions."""
    return sum(position.unrealized_pnl for position in positions)

Best Practices

  1. Always validate data: Check that required fields are set before using order or position objects
  2. Use enums for comparisons: Compare against enum values rather than raw integers
  3. Handle partial fills: Check filled_size vs size for partially filled orders
  4. Monitor position health: Regularly check liquidation_price and unrealized_pnl for risk management
  5. Timestamp handling: Parse timestamps as needed for your timezone requirements
  6. Error handling: Always wrap API calls in try-catch blocks for robust error handling
  7. Margin management: Understand the difference between CROSS and ISOLATED margin types
  8. Batch operations: Use get_orders() and get_open_positions() for efficient bulk data retrieval

Protobuf Details

The data objects are generated from protobuf definitions located in the proto/ submodule. When the protobuf definitions are updated:
  1. Run git submodule update --remote to get the latest definitions
  2. Run buf generate to regenerate the Python classes
  3. Update any custom wrapper code if field names or types change
The generated protobuf classes provide:
  • Serialization to/from binary protobuf format
  • JSON serialization support
  • Field validation and type checking
  • Default values for optional fields