Python API reference

This reference documents the public Python layer. It is generated with Sphinx autodoc from the openpit package and is organized by import path.

Import layout

Use these import paths in application code:

  • openpit: engine, root order/report models, and commonly used classes.

  • openpit.param: domain value types and enums.

  • openpit.pretrade: result handles, rejects, and policy interfaces.

  • openpit.pretrade.policies: built-in policies.

  • openpit.account_adjustment: account-adjustment models and policy interface.

Engine

Embeddable pre-trade risk SDK for trading systems.

openpit evaluates orders through a deterministic two-stage pipeline before they leave the application. The package provides:

  • Engine - pre-trade risk engine.

  • param - typed financial values (Price, Pnl, Quantity, etc.)

    with exact decimal arithmetic.

  • pretrade - pluggable policy interfaces, standard reject

    codes, deferred requests, and reservations.

  • core - order, execution-report, and account-adjustment group models.

Quickstart:

import openpit

engine = (
    openpit.Engine.builder()
    .no_sync()
    .builtin(openpit.pretrade.policies.build_order_validation())
    .build()
)

order = openpit.Order(
    operation=openpit.OrderOperation(
        instrument=openpit.Instrument("AAPL", "USD"),
        account_id=openpit.param.AccountId.from_int(99224416),
        side=openpit.param.Side.BUY,
        trade_amount=openpit.param.TradeAmount.quantity(100.0),
        price=openpit.param.Price(185.0),
    ),
)

result = engine.start_pre_trade(order=order)

Threading: The SDK never spawns OS threads: each public method runs on the OS thread that invoked it. The engine handle’s threading capability depends on the sync policy selected at builder time:

  • full_sync() - concurrent invocation on the same handle is safe;

    sequential cross-thread invocation is also safe.

  • no_sync() - the handle stays on the OS thread that created the

    engine.

  • account_sync() - concurrent invocation on the same handle is safe when

    the caller pins each account to a single chain (one queue or one worker at a time), so calls for the same account are never concurrent.

class openpit.Engine
class openpit.EngineBuilder

First stage of the engine builder. Select a synchronization policy via full_sync(), no_sync(), or account_sync().

Prefer no_sync() when you do not explicitly work with multiple threads yourself: it has zero synchronization overhead and is the right default for embeddings that drive the engine from a single thread (synchronous code or one asyncio loop). Use full_sync() when sharing the engine across threads concurrently. Use account_sync() for sharded sequential workloads where each account is pinned to one processing chain. Storage owned by built-in or custom policies is always account-keyed regardless of sync mode.

class openpit.SyncedEngineBuilder

Second stage of the engine builder (sync policy already chosen). Add at least one policy to obtain a ReadyEngineBuilder.

class openpit.ReadyEngineBuilder

Third stage of the engine builder (at least one policy registered). Accepts additional policies and builds the engine via build().

Policy names must be unique within one engine configuration.

class openpit.RejectError

Exception raised for Python binding misuse or callback-level failures.

Normal policy rejects are returned through result objects instead of raising this exception.

Domain value types

The openpit.param module contains identifiers, enums, and exact financial-domain values. These objects should be used at API boundaries instead of raw strings and numbers.

class openpit.param.AccountGroupId

Type-safe account-group identifier (32-bit).

Use from_int() when group IDs are already numeric - zero cost, zero collision risk. The value 0 is reserved for DEFAULT_ACCOUNT_GROUP, so from_int(0) raises ValueError.

Use from_string() when only a string identifier is available. The string is hashed with FNV-1a 32-bit. Collisions are possible; for n distinct group strings the probability of at least one collision is approximately n² / (2 × 2³²). If that risk is unacceptable, maintain a collision-free string-to-integer mapping and use from_int().

WARNING: Do not mix IDs created with from_int and from_string in the same runtime state. A hashed string-derived ID can equal a direct numeric ID.

DEFAULT = AccountGroupId(value=0)
static from_int(value)

Constructs an account-group identifier from an integer.

No hashing, no collision risk.

Raises ValueError when value equals the reserved DEFAULT_ACCOUNT_GROUP (0); that group cannot be named by a constructor. Raises OverflowError for values outside 1..=4294967295.

static from_string(value)

Constructs an account-group identifier by hashing a string with FNV-1a 32-bit.

Hash collisions are possible. For n distinct group strings the probability of at least one collision is approximately n^2 / (2 * 2^32). If collision risk is unacceptable, use from_int with a collision-free integer mapping instead. See <http://www.isthe.com/chongo/tech/comp/fnv/> for the algorithm specification.

value
class openpit.param.AccountId

Type-safe account identifier.

Use from_int() when the broker or venue assigns numeric account IDs — zero cost, zero collision risk.

Use from_string() when only a string identifier is available. The string is hashed with FNV-1a 64-bit, so hash collisions are theoretically possible. For n distinct account strings the probability of at least one collision is approximately n² / 2⁶⁵. If that risk is unacceptable, maintain a collision-free string-to-integer mapping on your side and use from_int(). See <http://www.isthe.com/chongo/tech/comp/fnv/> for the algorithm specification.

WARNING: Use exactly one source model per runtime:

  • either only AccountId.from_int(...),

  • or only AccountId.from_string(...).

Do not mix both in one runtime state. A hashed string-derived ID can equal a direct numeric ID, and then two distinct accounts become one logical key.

static from_int(value)

Constructs an account identifier.

No hashing. No collision risk.

Raises OverflowError for negative values.

static from_string(value)
Parameters:

value (str)

Return type:

AccountId

value
exception openpit.param.AccountIdError

Error type for account identifier validation failures.

class openpit.param.AdjustmentAmount(*args, **kwargs)

Delta or absolute payload wrapper.

Parameters:
  • args (object)

  • kwargs (object)

Return type:

AdjustmentAmount

static delta(value)

Create a delta-type adjustment amount.

Parameters:

value (PositionSize)

Return type:

AdjustmentAmount

static absolute(value)

Create an absolute-type adjustment amount.

Parameters:

value (PositionSize)

Return type:

AdjustmentAmount

property is_delta: bool

True when the adjustment is a signed delta.

property is_absolute: bool

True when the adjustment sets an absolute value.

property as_delta: PositionSize | None

Inner position size when delta, otherwise None.

property as_absolute: PositionSize | None

Inner position size when absolute, otherwise None.

class openpit.param.Asset(value)

Validated asset identifier string.

Parameters:

value (str)

Return type:

Asset

exception openpit.param.AssetError

Error type for asset validation failures.

class openpit.param.CashFlow(value)

Signed cash-flow amount expressed in the settlement currency.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only CashFlow operands of the same type. Cross-type arithmetic (for example CashFlow + Fee) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use from_pnl() and from_fee() for explicit domain conversions. Positive values represent inflow and negative values represent outflow.

ZERO = CashFlow(Decimal('0'))
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_fee(fee)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_pnl(pnl)
static from_string(value)
static from_string_rounded(value, scale, strategy)
static from_volume_inflow(volume)
static from_volume_outflow(volume)
to_json_value()
openpit.param.DEFAULT_ACCOUNT_GROUP: AccountGroupId = AccountGroupId(value=0)

The account group an account belongs to until assigned to another.

Reserved identifier (value 0). Every account starts in this group; it becomes a member of another group only through engine.accounts().register_group(...). No constructor produces it - AccountGroupId.from_int(0) raises and AccountGroupId.from_string never hashes to it - so this constant (also exposed as AccountGroupId.DEFAULT) is the only way to name it.

class openpit.param.Fee(value)

Execution fee or rebate expressed in the settlement currency.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Fee operands of the same type. Cross-type arithmetic (for example Fee + Pnl) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use to_pnl() and to_position_size() for domain conversions.

ZERO = Fee(Decimal('0'))
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_cash_flow()
to_json_value()
to_pnl()
to_position_size()
class openpit.param.FillType(value)

Type of fill event reported by the venue.

TRADE = 'TRADE'
LIQUIDATION = 'LIQUIDATION'
AUTO_DELEVERAGE = 'AUTO_DELEVERAGE'
SETTLEMENT = 'SETTLEMENT'
FUNDING = 'FUNDING'
class openpit.param.Kind(value)

Stable identifiers for numeric domain value categories.

QUANTITY = 'Quantity'
VOLUME = 'Volume'
NOTIONAL = 'Notional'
PRICE = 'Price'
PNL = 'Pnl'
CASH_FLOW = 'CashFlow'
POSITION_SIZE = 'PositionSize'
FEE = 'Fee'
LEVERAGE = 'Leverage'
class openpit.param.Leverage(multiplier)

Per-order leverage multiplier with 0.1 step and range 1..=3000.

Use Leverage(10) or Leverage(10.1) for direct multiplier construction. from_int and from_float remain available when explicit constructor intent is preferred.

The normalized multiplier is exposed through value. Use this type for explicit leverage overrides on margin orders and margin-parameter objects.

MAX = 3000
MIN = 1
SCALE = 10
STEP = 0.10000000149011612
calculate_margin_required(notional)
static from_float(multiplier)
static from_int(multiplier)
value
class openpit.param.Notional(value)

Monetary position exposure in the settlement currency.

Represents the absolute face value of a position: |price| × quantity. Always non-negative. Used to calculate required margin and evaluate risk.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Notional operands of the same type. Cross-type arithmetic (for example Notional + Volume) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use from_price_quantity() to compute notional from a trade; use calculate_margin_required() to derive the required margin.

ZERO = Notional(Decimal('0'))
calculate_margin_required(leverage)
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_price_quantity(price, quantity)
static from_string(value)
static from_string_rounded(value, scale, strategy)
static from_volume(volume)
to_json_value()
to_volume()
exception openpit.param.ParamError
class openpit.param.Pnl(value)

Signed profit-and-loss amount expressed in the settlement currency.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Pnl operands of the same type. Cross-type arithmetic (for example Pnl + Fee) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use to_cash_flow() and to_position_size() for domain conversions. Positive values represent realized profit and negative values represent realized loss.

ZERO = Pnl(Decimal('0'))
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_fee(fee)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_cash_flow()
to_json_value()
to_position_size()
class openpit.param.PositionEffect(value)

Whether an execution opens or closes exposure.

OPEN = 'OPEN'
CLOSE = 'CLOSE'
class openpit.param.PositionMode(value)

Netting vs hedged position mode.

NETTING = 'netting'
HEDGED = 'hedged'
class openpit.param.PositionSide(value)

Hedge-mode leg for derivatives positions.

LONG = 'LONG'
SHORT = 'SHORT'
is_long()

Return True when the position side is long.

Return type:

bool

is_short()

Return True when the position side is short.

Return type:

bool

opposite()

Return the opposite hedge-mode leg.

Return type:

PositionSide

class openpit.param.PositionSize(value)

Signed position size in instrument units.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only PositionSize operands of the same type. Cross-type arithmetic (for example PositionSize + Quantity) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use from_quantity_and_side(), to_open_quantity(), to_close_quantity(), and checked_add_quantity() for directional position workflows.

ZERO = PositionSize(Decimal('0'))
checked_add_quantity(qty, side)
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_fee(fee)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_pnl(pnl)
static from_quantity_and_side(quantity, side)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_close_quantity()
to_json_value()
to_open_quantity()
class openpit.param.Price(value)

Per-unit instrument price.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Price operands of the same type. Cross-type arithmetic (for example Price + Quantity) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use Price.calculate_volume(quantity) to derive notional volume through the same exact arithmetic as the SDK core instead of multiplying raw numbers.

ZERO = Price(Decimal('0'))
calculate_position_size(quantity)
calculate_volume(quantity)
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_json_value()
class openpit.param.Quantity(value)

Unsigned order or fill size in instrument units.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Quantity operands of the same type. Cross-type arithmetic (for example Quantity + Price) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use Quantity.calculate_volume(price) to derive notional volume through the engine’s domain arithmetic rather than manual number math.

ZERO = Quantity(Decimal('0'))
calculate_volume(price)
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_json_value()
to_position_size()
class openpit.param.RoundingStrategy(value)

Named rounding strategies used by the SDK value-type layer.

MIDPOINT_NEAREST_EVEN = 'MidpointNearestEven'
MIDPOINT_AWAY_FROM_ZERO = 'MidpointAwayFromZero'
UP = 'Up'
DOWN = 'Down'
DEFAULT = 'MidpointNearestEven'
BANKER = 'MidpointNearestEven'
CONSERVATIVE_PROFIT = 'Down'
CONSERVATIVE_LOSS = 'Down'
class openpit.param.Side(value)

Trade direction for orders and execution reports.

BUY = 'BUY'
SELL = 'SELL'
is_buy()

Return True when the side is buy.

Return type:

bool

is_sell()

Return True when the side is sell.

Return type:

bool

opposite()

Return the opposite side.

Return type:

Side

sign()

Return +1 for buy and -1 for sell.

Return type:

int

class openpit.param.Trade(*args, **kwargs)

Last executed trade details.

Parameters:
  • args (object)

  • kwargs (object)

Return type:

Trade

property price: Price
property quantity: Quantity
class openpit.param.TradeAmount(*args, **kwargs)

Quantity- or volume-based trade amount wrapper.

Use factory methods quantity() and volume() to construct. Factory arguments accept either value objects (Quantity / Volume) or primitive numeric/string literals.

inspect the variant with is_quantity / is_volume and extract the inner value with as_quantity / as_volume.

Parameters:
  • args (object)

  • kwargs (object)

Return type:

TradeAmount

static quantity(value)

Create a quantity-based trade amount.

Parameters:

value (Quantity | str | int | float)

Return type:

TradeAmount

static volume(value)

Create a volume-based trade amount.

Parameters:

value (Volume | str | int | float)

Return type:

TradeAmount

property is_quantity: bool

True when the amount is expressed as quantity.

property is_volume: bool

True when the amount is expressed as volume.

property as_quantity: Quantity | None

Inner quantity, or None when volume-based.

property as_volume: Volume | None

Inner volume, or None when quantity-based.

class openpit.param.Volume(value)

Unsigned notional volume in the settlement currency.

Behaves like decimal.Decimal with domain-type safety: arithmetic accepts only Volume operands of the same type. Cross-type arithmetic (for example Volume + Quantity) returns TypeError.

Constructor accepts Decimal, str, int, or float.

WARNING: float is inherently imprecise. The same numeric literal passed as float can differ from its str/Decimal representation by one ULP and may produce platform-dependent results. For external monetary inputs, prefer str or Decimal values.

Use .decimal to access the underlying decimal.Decimal and .to_json_value() for canonical JSON serialization.

Use calculate_quantity(), to_cash_flow_inflow(), and to_cash_flow_outflow() for domain conversions.

ZERO = Volume(Decimal('0'))
calculate_quantity(price)
decimal
static from_decimal(value)
static from_decimal_rounded(value, scale, strategy)
static from_float(value)

WARNING: float values are inherently imprecise. Use decimal/string inputs for external monetary data.

static from_float_rounded(value, scale, strategy)
static from_int(value)
static from_string(value)
static from_string_rounded(value, scale, strategy)
to_cash_flow_inflow()
to_cash_flow_outflow()
to_json_value()
to_position_size()

Market data

The openpit.marketdata module exposes the live market-data service used by built-in policies that require real-time price feeds.

Live market-data service bindings.

exception openpit.marketdata.AlreadyRegistered

Raised when an instrument is already registered.

class openpit.marketdata.InstrumentId(value)

Identifier assigned to a registered market-data instrument.

value
class openpit.marketdata.MarketDataBuilder

Builder for a market-data service.

Obtain via SyncedEngineBuilder.market_data(default_ttl) or ReadyEngineBuilder.market_data(default_ttl). The synchronization mode is derived from the engine builder’s sync policy:

  • no_sync() engine -> no-sync mode (no-op locks, zero overhead).

  • full_sync() or account_sync() engine -> Full mode (real locks,

    safe for a concurrent quote feed).

Call .full_sync() on the builder to upgrade a no-sync builder to Full, or .no_sync() to explicitly downgrade to no-op locks (zero overhead, single-threaded use only), before calling .build().

build()
full_sync()

Upgrades the builder to use full synchronization.

If the builder was derived from a no_sync() engine (no-sync mode), this switches it to Full so the resulting service is safe for a concurrent quote feed. No-op when the builder is already Full.

no_sync()

Downgrades the builder to no-sync mode (no-op locks, zero overhead).

Use only when the market-data service is written from a single thread and never read concurrently. No-op when the builder is already None.

exception openpit.marketdata.MarketDataError

Base exception for market-data read failures.

class openpit.marketdata.MarketDataService

Thread-shareable live market-data service.

Reads are performed with get(instrument_id, account_id, account_info, resolution) and get_or_err(...). account_info is any object that exposes an account_group property returning an AccountGroupId or None — engine contexts (e.g. PreTradeContext, PostTradeContext) satisfy this automatically. The group is resolved lazily: the service only reads account_group when the per-account bucket misses and the resolution mode needs the group.

clear(instrument_id)
clear_account_group_ttl(account_group_id)

Clears the TTL override for the given account group.

Passing AccountGroupId.DEFAULT targets the service-level default-group TTL (the “everyone-else” bucket that accounts without an explicit group assignment fall into).

clear_account_ttl(account_id)
clear_instrument_account_group_ttl(instrument_id, account_group_id)

Clears the per-instrument TTL override for the given account group.

Passing AccountGroupId.DEFAULT targets the instrument-level default-group TTL (the “everyone-else” bucket for this instrument).

clear_instrument_account_ttl(instrument_id, account_id)
clear_instrument_ttl(instrument_id)
get(instrument_id, account_id, account_info, resolution)
get_or_err(instrument_id, account_id, account_info, resolution)
push(instrument_id, quote)
push_by_instrument(instrument, quote)
push_by_instrument_patch(instrument, quote)
push_for(instrument_id, quote, account_ids, account_group_ids)

Push a full quote snapshot to specific accounts and/or groups.

To target the default (“everyone-else”) bucket, include AccountGroupId.DEFAULT in account_group_ids.

push_for_patch(instrument_id, quote, account_ids, account_group_ids)

Push a partial quote patch to specific accounts and/or groups.

To target the default (“everyone-else”) bucket, include AccountGroupId.DEFAULT in account_group_ids.

push_patch(instrument_id, quote)
register(instrument)
register_with_id(instrument, id)
register_with_id_and_ttl(instrument, id, ttl)
register_with_ttl(instrument, ttl)
resolve(instrument)
set_account_group_ttl(account_group_id, ttl)

Sets the TTL override for the given account group.

Passing AccountGroupId.DEFAULT targets the service-level default-group TTL (the “everyone-else” bucket that accounts without an explicit group assignment fall into).

set_account_ttl(account_id, ttl)
set_instrument_account_group_ttl(instrument_id, account_group_id, ttl)

Sets the per-instrument TTL override for the given account group.

Passing AccountGroupId.DEFAULT targets the instrument-level default-group TTL (the “everyone-else” bucket for this instrument).

set_instrument_account_ttl(instrument_id, account_id, ttl)
set_instrument_ttl(instrument_id, ttl)
class openpit.marketdata.Quote(*, mark=None, bid=None, ask=None)

Market snapshot with optional mark, bid, and ask prices.

ask
bid
mark
class openpit.marketdata.QuoteResolution

Controls which quote buckets a read may fall through to.

Variants (in order of breadth):

  • ACCOUNT_ONLY — only the per-account bucket.

  • ACCOUNT_THEN_GROUP — per-account, then the account’s group bucket.

  • ACCOUNT_THEN_GROUP_THEN_DEFAULT — per-account, then group, then the

    default (“everyone-else”) bucket.

ACCOUNT_ONLY = QuoteResolution.ACCOUNT_ONLY
ACCOUNT_THEN_GROUP = QuoteResolution.ACCOUNT_THEN_GROUP
ACCOUNT_THEN_GROUP_THEN_DEFAULT = QuoteResolution.ACCOUNT_THEN_GROUP_THEN_DEFAULT
class openpit.marketdata.QuoteTtl

Quote lifetime policy: infinite or within a finite duration.

static infinite()
static within(duration)
exception openpit.marketdata.QuoteUnavailable

Raised when no usable quote is available.

exception openpit.marketdata.RegistrationError

Raised when an explicit id registration conflicts.

exception openpit.marketdata.UnknownInstrument

Raised when a market-data id is not registered.

exception openpit.marketdata.UnknownInstrumentId

Raised when an operation references an unknown id.

Core order and report models

Core models group order, execution-report, and mutation payloads. Order and ExecutionReport are intentionally extensible: applications may subclass them to carry project metadata into policy callbacks.

class openpit.core.AccountAdjustmentContext

Opaque context object passed to account-adjustment check callbacks.

The object identifies the current account-adjustment evaluation context. Treat it as read-only and do not instantiate it directly.

account_control is an openpit.AccountControl handle to the engine’s account-block facility for the evaluated account. A policy may use it to block the account directly or capture it into a openpit.Mutation rollback/commit closure to block on a deferred failure. The handle is valid only within the processing of this account-adjustment request (through its commit or rollback); using it afterwards is unspecified.

account_control
account_group
class openpit.core.AccountControl

Handle that records a kill-switch block against the account bound to a callback context.

It is valid to use only within the pre-trade processing of the request it belongs to — from the callback that produced it through the commit or rollback of that request’s reservation (so it may be retained and used from a deferred mutation commit/rollback callback). Recording a block through it after that pre-trade transaction has completed is unspecified and must not be relied upon.

block(block)
class openpit.core.ExecutionReport(*args, **kwargs)

Extensible execution-report model consumed by post-trade policies.

All groups are optional. Policies that need specific data validate group presence at runtime.

Snapshot semantics: When Engine.apply_execution_report(...) is called, a snapshot of the report groups is captured for processing. Mutating the same object after the call does not alter the already-submitted report.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

ExecutionReport

property operation: ExecutionReportOperation | None

Main operation parameters group.

property financial_impact: FinancialImpact | None

Financial impact parameters group.

property fill: ExecutionReportFillDetails | None

Fill details group.

property position_impact: ExecutionReportPositionImpact | None

Position impact data group.

class openpit.core.ExecutionReportFillDetails(*args, **kwargs)

Trade reported by the execution.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

ExecutionReportFillDetails

property last_trade: Trade | None

Actual execution trade.

property leaves_quantity: Quantity | None

Remaining order quantity after this fill.

property lock: Lock

Order lock payload.

property is_final: bool | None

Whether this report closes the order’s report stream.

The order is filled, cancelled, or rejected.

class openpit.core.ExecutionReportOperation(*args, **kwargs)

Main operation parameters reported by the execution.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

ExecutionReportOperation

property instrument: Instrument

Traded instrument.

property account_id: AccountId

Account identifier associated with the execution report.

property side: Side

Economic direction of the reported execution event.

class openpit.core.ExecutionReportPositionImpact(*args, **kwargs)

Position impact parameters reported by the execution.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

ExecutionReportPositionImpact

property position_effect: PositionEffect | None

Whether this execution opened or closed exposure.

property position_side: PositionSide | None

Hedge-mode leg affected by this execution, when provided.

class openpit.core.FinancialImpact(*args, **kwargs)

Financial impact parameters reported by the execution.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

FinancialImpact

property pnl: Pnl

Realized trading result contributed by this report.

Positive values for gains, negative values for losses.

property fee: Fee

Fee or rebate associated with this report event.

Negative values for fees, positive values for rebates.

class openpit.core.Instrument(underlying_asset, settlement_asset)

Trading instrument definition.

underlying_asset is the asset that is actually bought or sold. Order quantity, position size, and exposure are expressed in this asset.

settlement_asset is the asset used for monetary settlement. P&L, fees, and cash flows are expressed in this asset.

Parameters:
  • underlying_asset (Asset)

  • settlement_asset (Asset)

property underlying_asset: Asset

Returns the asset that is bought or sold.

This is the asset in which order quantity and resulting position are measured.

property settlement_asset: Asset

Returns the asset used for monetary settlement.

This is the asset in which cash flow, fees, and P&L are measured.

class openpit.core.Order(*args, **kwargs)

Extensible order model accepted by openpit.Engine.start_pre_trade.

All groups are optional. The engine’s built-in policies validate at runtime that the groups they need are present and produce a standard MissingRequiredField reject when they are not.

Snapshot semantics: When an order is submitted to the engine, an internal snapshot of its current group fields is created for policy evaluation. Later mutations of the same Order object do not affect that in-flight evaluation.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Order

property operation: OrderOperation | None

Main operation parameters group.

property position: OrderPosition | None

Position management parameters group.

property margin: OrderMargin | None

Margin configuration parameters group.

class openpit.core.OrderMargin(*args, **kwargs)

Margin configuration parameters.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

OrderMargin

property leverage: Leverage | None

Per-order leverage target used for margin requirement calculation.

None means “use integration/account default leverage configuration”.

property collateral_asset: Asset | None

Collateral currency intended to fund this specific order.

None means “use default collateral asset selected by integration”.

property auto_borrow: bool

Whether temporary collateral shortage may be covered by auto-borrow.

Defaults to False.

class openpit.core.OrderOperation(*args, **kwargs)

Main operation parameters that describe side, instrument, price, and amount.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

OrderOperation

property instrument: Instrument

Traded instrument.

property account_id: AccountId

Account identifier associated with the order.

property side: Side

Order side.

property trade_amount: TradeAmount

Requested trade amount; context is determined by value type.

property price: Price | None

Requested worst execution price used for size translation and price-sensitive checks.

None means the order should execute at market price.

class openpit.core.OrderPosition(*args, **kwargs)

Position management parameters.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

OrderPosition

property position_side: PositionSide | None

Hedge-mode leg targeted by the order.

None uses one-way mode semantics.

property reduce_only: bool

Restricts the order to exposure-reducing execution only.

property close_position: bool

Marks intent to close the entire open position for the targeted leg/symbol.

Pre-trade results and handles

These classes model the two-stage pre-trade lifecycle. StartResult contains a deferred request handle. ExecuteResult contains either rejects or a reservation that must be committed or rolled back.

Pre-trade pipeline components: policies, rejects, requests, and reservations.

class openpit.pretrade.Context

Opaque context object passed to Python policy callbacks.

The object identifies the current engine evaluation context. Treat it as read-only. Future releases may expose additional query methods on this object; policies should not create instances directly.

account_control is an AccountControl when the engine exposes the account-block facility for the evaluated account, otherwise None. A policy may capture it into a openpit.Mutation rollback/commit closure to block the account on a deferred failure. The handle is valid only within this request’s pre-trade processing (through its reservation’s commit or rollback); using it afterwards is unspecified.

class openpit.pretrade.Lock(*args, **kwargs)

Pre-trade price lock payload: grouped (policy_group_id, price) records.

Parameters:
  • args (object)

  • kwargs (object)

Return type:

Lock

class openpit.pretrade.RejectCode(value)

Stable machine-readable reject codes used across built-in and custom policies.

MISSING_REQUIRED_FIELD = 'MissingRequiredField'
INVALID_FIELD_FORMAT = 'InvalidFieldFormat'
INVALID_FIELD_VALUE = 'InvalidFieldValue'
UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType'
UNSUPPORTED_TIME_IN_FORCE = 'UnsupportedTimeInForce'
UNSUPPORTED_ORDER_ATTRIBUTE = 'UnsupportedOrderAttribute'
DUPLICATE_CLIENT_ORDER_ID = 'DuplicateClientOrderId'
TOO_LATE_TO_ENTER = 'TooLateToEnter'
EXCHANGE_CLOSED = 'ExchangeClosed'
UNKNOWN_INSTRUMENT = 'UnknownInstrument'
UNKNOWN_ACCOUNT = 'UnknownAccount'
UNKNOWN_VENUE = 'UnknownVenue'
UNKNOWN_CLEARING_ACCOUNT = 'UnknownClearingAccount'
UNKNOWN_COLLATERAL_ASSET = 'UnknownCollateralAsset'
INSUFFICIENT_FUNDS = 'InsufficientFunds'
INSUFFICIENT_MARGIN = 'InsufficientMargin'
INSUFFICIENT_POSITION = 'InsufficientPosition'
CREDIT_LIMIT_EXCEEDED = 'CreditLimitExceeded'
RISK_LIMIT_EXCEEDED = 'RiskLimitExceeded'
ORDER_EXCEEDS_LIMIT = 'OrderExceedsLimit'
ORDER_QTY_EXCEEDS_LIMIT = 'OrderQtyExceedsLimit'
ORDER_NOTIONAL_EXCEEDS_LIMIT = 'OrderNotionalExceedsLimit'
POSITION_LIMIT_EXCEEDED = 'PositionLimitExceeded'
CONCENTRATION_LIMIT_EXCEEDED = 'ConcentrationLimitExceeded'
LEVERAGE_LIMIT_EXCEEDED = 'LeverageLimitExceeded'
RATE_LIMIT_EXCEEDED = 'RateLimitExceeded'
PNL_KILL_SWITCH_TRIGGERED = 'PnlKillSwitchTriggered'
ACCOUNT_BLOCKED = 'AccountBlocked'
ACCOUNT_NOT_AUTHORIZED = 'AccountNotAuthorized'
COMPLIANCE_RESTRICTION = 'ComplianceRestriction'
INSTRUMENT_RESTRICTED = 'InstrumentRestricted'
JURISDICTION_RESTRICTION = 'JurisdictionRestriction'
WASH_TRADE_PREVENTION = 'WashTradePrevention'
SELF_MATCH_PREVENTION = 'SelfMatchPrevention'
SHORT_SALE_RESTRICTION = 'ShortSaleRestriction'
RISK_CONFIGURATION_MISSING = 'RiskConfigurationMissing'
REFERENCE_DATA_UNAVAILABLE = 'ReferenceDataUnavailable'
ORDER_VALUE_CALCULATION_FAILED = 'OrderValueCalculationFailed'
SYSTEM_UNAVAILABLE = 'SystemUnavailable'
MARK_PRICE_UNAVAILABLE = 'MarkPriceUnavailable'
ACCOUNT_ADJUSTMENT_BOUNDS_EXCEEDED = 'AccountAdjustmentBoundsExceeded'
ARITHMETIC_OVERFLOW = 'ArithmeticOverflow'
CUSTOM = 'Custom'
OTHER = 'Other'
class openpit.pretrade.RejectScope(value)

Scope of a business reject returned by a policy.

ORDER = 'order'
ACCOUNT = 'account'
class openpit.pretrade.StartResult

Result of Engine.start_pre_trade.

Attributes:

  • ok: True when start-stage checks accepted the order.

  • request: Deferred Request on success, otherwise None.

  • rejects: Merged start-stage reject list when ok is False.

class openpit.pretrade.ExecuteResult

Result of Request.execute or Engine.execute_pre_trade.

Attributes:

  • ok: True when all evaluated stages accepted the order.

  • reservation: Reservation on success, otherwise None.

  • rejects: Ordered list of business rejects when ok is False.

Successful results must be finalized by committing or rolling back the reservation. Failed results never contain a reservation.

class openpit.pretrade.PostTradeResult(*, account_blocks=None, account_adjustments=None)

Result of openpit.Engine.apply_execution_report.

Post-trade processing is not atomic: account_adjustments reflect storage mutations that have already been applied, so callers must propagate them downstream even when account_blocks is non-empty.

Attributes:

  • account_blocks: List of account blocks reported by policies. Non-empty when at least one policy entered a blocked state after the report.

  • account_adjustments: List of per-asset position outcomes reported by policies, in policy registration order.

class openpit.pretrade.PostTradeContext
class openpit.pretrade.AccountOutcomeEntry(*, asset, balance=None, held=None, incoming=None)
class openpit.pretrade.AccountAdjustmentBatchResult

Result of Engine.apply_account_adjustment.

Attributes:

  • ok: True when the whole adjustment batch passed.

  • failed_index: Zero-based index of the first rejected adjustment, or None on success.

  • rejects: Reject list returned for the failed adjustment.

class openpit.pretrade.Request

Deferred main-stage request handle produced by Engine.start_pre_trade.

The handle is single-use. Calling execute more than once raises RuntimeError. Keep the handle only while the caller is ready to enter the main stage; it represents a snapshot of the submitted order.

class openpit.pretrade.Reservation

Single-use reservation handle returned by successful main-stage execution.

Call commit only after the order has been accepted by the downstream venue or transport. Call rollback when submission fails or the caller decides not to send the order. Calling either finalizer more than once raises RuntimeError.

class openpit.pretrade.Reject

Business reject returned by start-stage or main-stage checks.

Rejects are normal policy outcomes, not exceptional failures.

Attributes:

  • code: Stable machine-readable reject code.

  • reason: Short human-readable reason.

  • details: Diagnostic text intended for logs and operators.

  • policy: Name of the policy that produced the reject.

  • scope: RejectScope.ORDER or RejectScope.ACCOUNT.

  • user_data: Opaque caller-defined integer token copied from custom rejects.

Policy interfaces

Use these interfaces to implement custom business checks. Policy rejects are normal outcomes and should be returned, not raised.

Python policy interfaces and decision types exposed by openpit.

The recommended integration style is to derive boundary models directly from the engine contracts and add project-specific fields in subclasses:

import typing

import openpit

if not hasattr(typing, "override"):
    def _override(method):
        return method

    typing.override = _override  # type: ignore[attr-defined]


class BrokerOrder(openpit.Order):
    @typing.override
    def __init__(
        self,
        *,
        instrument: openpit.Instrument,
        side: openpit.param.Side,
        trade_amount: openpit.param.TradeAmount,
        account_id: openpit.param.AccountId,
        price: openpit.param.Price | None = None,
    ) -> None:
        super().__init__(
            operation=openpit.OrderOperation(
                instrument=instrument,
                side=side,
                trade_amount=trade_amount,
                account_id=account_id,
                price=price,
            )
        )
        self.strategy = "broker-default"


class BrokerReport(openpit.ExecutionReport):
    @typing.override
    def __init__(
        self,
        *,
        instrument: openpit.Instrument,
        side: openpit.param.Side,
        account_id: openpit.param.AccountId,
        pnl: openpit.param.Pnl,
        fee: openpit.param.Fee,
    ) -> None:
        super().__init__(
            operation=openpit.ExecutionReportOperation(
                instrument=instrument,
                side=side,
                account_id=account_id,
            ),
            financial_impact=openpit.FinancialImpact(
                pnl=pnl,
                fee=fee,
            ),
        )
        self.source = "broker-fill"

This keeps custom metadata on the same object that reaches policy callbacks and preserves one explicit engine-facing contract.

class openpit.pretrade.policy.PolicyReject(code, reason, details, scope=RejectScope.ORDER, user_data=0)

Business reject produced by a custom policy.

Canonical reject model for policy interfaces. Field semantics match the engine reject payload: code, reason, details, and scope.

This type models a normal reject path. Do not raise exceptions for normal risk decisions. Return this object instead.

Attributes:

  • code: Stable machine-readable reject code string from openpit.pretrade.RejectCode.

  • reason: Short human-readable reason.

  • details: Detailed context for logs/diagnostics.

  • scope: Reject scope, either "order" or "account".

  • user_data: Opaque caller-defined integer token copied through reject flows. 0 means “not set”. The SDK never inspects it; lifetime and thread-safety are caller-managed (see pit.wiki/Threading-Contract.md).

Parameters:
  • code (str)

  • reason (str)

  • details (str)

  • scope (RejectScope)

  • user_data (int)

code: str
reason: str
details: str
scope: RejectScope = 'order'
user_data: int = 0
class openpit.pretrade.policy.PolicyDecision(rejects=(), mutations=())

Return type of Policy.perform_pre_trade_check().

Attributes:

  • rejects: Rejects produced by the policy.

  • mutations: Mutations registered by the policy.

Parameters:
  • rejects (tuple[PolicyReject, ...])

  • mutations (tuple[Mutation, ...])

rejects: tuple[PolicyReject, ...] = ()
mutations: tuple[Mutation, ...] = ()
classmethod accept(mutations=())

Build a successful decision.

Args:

  • mutations: Optional mutations to register.

Returns:

  • PolicyDecision: Decision with empty rejects.

Parameters:

mutations (Iterable[Mutation])

Return type:

PolicyDecision

classmethod reject(rejects, mutations=())

Build a rejecting decision.

Args:

  • rejects: One or more business rejects.

  • mutations: Optional mutations produced before reject decision.

Returns:

  • PolicyDecision: Decision with non-empty rejects.

Parameters:
  • rejects (Iterable[PolicyReject])

  • mutations (Iterable[Mutation])

Return type:

PolicyDecision

class openpit.pretrade.policy.PolicyPreTradeResult(rejects=(), mutations=(), account_adjustments=(), lock_prices=())

Return type of Policy.perform_pre_trade_check().

Attributes:

  • rejects: Rejects produced by the policy.

  • mutations: Mutations registered by the policy.

  • account_adjustments: Per-asset outcome entries produced by the policy.

  • lock_prices: Prices to store under this policy’s policy_group_id.

Parameters:
rejects: tuple[PolicyReject, ...] = ()
mutations: tuple[Mutation, ...] = ()
account_adjustments: tuple[AccountOutcomeEntry, ...] = ()
lock_prices: tuple[Price, ...] = ()
classmethod accept(mutations=(), account_adjustments=(), lock_prices=())

Build a successful pre-trade result.

Parameters:
Return type:

PolicyPreTradeResult

classmethod reject(rejects, mutations=(), account_adjustments=(), lock_prices=())

Build a rejecting pre-trade result.

Parameters:
Return type:

PolicyPreTradeResult

class openpit.pretrade.policy.Policy

Unified Python pre-trade policy interface.

Stage semantics:

  • check_pre_trade_start is called during engine.start_pre_trade

  • perform_pre_trade_check is called during request.execute()

  • apply_execution_report applies post-trade feedback

  • apply_account_adjustment validates account-adjustment batches

Implementation rule:

  • override the methods needed by the registration path used by the policy

  • return PolicyPreTradeResult for main-stage outcomes

  • return openpit.pretrade.PostTradeResult for post-trade outcomes

  • return account outcome entries for account-adjustment outcomes

  • raise exceptions only for programming/runtime failures

abstract property name: str

Return a stable, unique policy name.

The name must be non-empty and unique within one engine config.

property policy_group_id: int

Return the policy group tag.

The engine stores pre-trade lock prices and account-adjustment outcomes under this group. 0 is the default group.

check_pre_trade_start(ctx, order)

Evaluate an order in start stage.

Args:

  • ctx: Context of the current pre-trade operation. ctx.account_control is an openpit.pretrade.AccountControl when the engine exposes the account-block facility for the order’s account, otherwise None. A policy may block the account directly or capture the handle into a openpit.Mutation rollback/commit closure to block on a deferred failure. The handle is valid only within this request’s pre-trade processing (through its reservation’s commit or rollback); using it afterwards is unspecified.

  • order: Incoming order candidate. This must be openpit.Order or one of its subclasses.

Returns:

  • Iterable[PolicyReject]: - empty iterable if the order passes this policy - one or more PolicyReject if this policy rejects

Parameters:
Return type:

collections.abc.Iterable[PolicyReject]

perform_pre_trade_check(ctx, order)

Evaluate order context in main stage.

Args:

  • ctx: Context of the current pre-trade operation. ctx.account_control is an openpit.pretrade.AccountControl when the engine exposes the account-block facility for the order’s account, otherwise None. A policy may block the account directly or capture the handle into a openpit.Mutation rollback/commit closure to block on a deferred failure. The handle is valid only within this request’s pre-trade processing (through its reservation’s commit or rollback); using it afterwards is unspecified.

  • order: Incoming order candidate.

Returns:

  • PolicyPreTradeResult: - use PolicyPreTradeResult.accept(...) for pass path - use PolicyPreTradeResult.reject(...) for business rejects

Parameters:
Return type:

PolicyPreTradeResult

apply_execution_report(ctx, report)

Apply post-trade feedback to policy state.

Args:

  • ctx: Post-trade context. ctx.account_group is the openpit.param.AccountGroupId of the report’s account, or None when the account is absent or unregistered.

  • report: Execution report produced after fill/close.

Returns:

PostTradeResult | None: Result with account blocks and account adjustments, or None if the report caused no visible post-trade outcome.

Parameters:
Return type:

PostTradeResult | None

apply_account_adjustment(ctx, account_id, adjustment)

Evaluate one account adjustment from an atomic batch.

Args:

  • ctx: Read-only engine context for the current batch operation. ctx.account_control is always an openpit.pretrade.AccountControl handle to the engine’s account-block facility. A policy may block the account directly or capture the handle into a openpit.Mutation rollback/commit closure to block on a deferred failure. The handle is valid only within this batch operation’s processing (through its commit or rollback); using it afterwards is unspecified.

  • account_id: Account affected by the batch.

  • adjustment: Current adjustment item.

Returns:

Iterable of account outcome entries for success with outcomes, None or PolicyDecision.accept() for success without outcomes, an iterable of PolicyReject objects for business rejection, or a tuple of Mutation objects to register rollback work.

Parameters:
Return type:

collections.abc.Iterable[AccountOutcomeEntry] | PolicyDecision | collections.abc.Iterable[PolicyReject] | tuple[Mutation, …] | None

Built-in policies

Built-in policies are registered through EngineBuilder like custom policies. They produce standard RejectCode values.

Built-in pre-trade policy builders for the Python binding.

class openpit.pretrade.policies.OrderSizeLimit(*, max_quantity, max_notional)

Order-size limits (quantity and notional cap).

Args:

  • max_quantity: Maximum allowed order quantity.

  • max_notional: Maximum allowed notional volume.

Use as limit inside OrderSizeBrokerBarrier, OrderSizeAssetBarrier, or OrderSizeAccountAssetBarrier.

class openpit.pretrade.policies.OrderSizeBrokerBarrier(limit)

Order size limit applied across the entire broker.

Args:

  • limit: Quantity and notional caps.

Parameters:

limit (OrderSizeLimit)

limit: OrderSizeLimit
class openpit.pretrade.policies.OrderSizeAssetBarrier(limit, settlement_asset)

Order size limit applied per settlement asset.

Args:

  • limit: Quantity and notional caps.

  • settlement_asset: Settlement asset symbol this barrier tracks.

Parameters:
limit: OrderSizeLimit
settlement_asset: str
class openpit.pretrade.policies.OrderSizeAccountAssetBarrier(limit, account_id, settlement_asset)

Order size limit applied per (account, settlement asset) pair.

Args:

  • limit: Quantity and notional caps.

  • account_id: Account this barrier applies to.

  • settlement_asset: Settlement asset symbol this barrier tracks.

Parameters:
limit: OrderSizeLimit
account_id: param.AccountId
settlement_asset: str
class openpit.pretrade.policies.OrderSizeLimitReadyBuilder

Fully-configured order-size-limit policy builder.

Obtain via build_order_size_limit() followed by broker_barrier(). All axis methods return self for chaining. Pass to SyncedEngineBuilder.builtin() or ReadyEngineBuilder.builtin().

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

OrderSizeLimitReadyBuilder

broker_barrier(barrier)

Set or replace the broker-wide order-size limit.

Parameters:

barrier (OrderSizeBrokerBarrier)

Return type:

OrderSizeLimitReadyBuilder

asset_barriers(*barriers)

Append per-settlement-asset order-size barriers.

Parameters:

barriers (OrderSizeAssetBarrier)

Return type:

OrderSizeLimitReadyBuilder

account_asset_barriers(*barriers)

Append per-(account, settlement-asset) order-size barriers.

Parameters:

barriers (OrderSizeAccountAssetBarrier)

Return type:

OrderSizeLimitReadyBuilder

class openpit.pretrade.policies.OrderSizeLimitBuilder

Entry point for the order-size-limit policy builder.

Call build_order_size_limit() to obtain an instance. Call broker_barrier() to obtain an OrderSizeLimitReadyBuilder that can be passed to builtin(). Additional axes (asset_barriers(), account_asset_barriers()) stage barriers before the broker barrier is set.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

OrderSizeLimitBuilder

broker_barrier(barrier)

Set the broker-wide order-size limit and return a ready builder.

Parameters:

barrier (OrderSizeBrokerBarrier)

Return type:

OrderSizeLimitReadyBuilder

asset_barriers(*barriers)

Add per-settlement-asset barriers and return a ready builder.

Parameters:

barriers (OrderSizeAssetBarrier)

Return type:

OrderSizeLimitReadyBuilder

account_asset_barriers(*barriers)

Add per-(account, settlement-asset) barriers and return a ready builder.

Parameters:

barriers (OrderSizeAccountAssetBarrier)

Return type:

OrderSizeLimitReadyBuilder

openpit.pretrade.policies.build_order_size_limit()

Return a new order-size-limit policy builder.

Return type:

OrderSizeLimitBuilder

class openpit.pretrade.policies.PnlBoundsBrokerBarrier(settlement_asset, lower_bound=None, upper_bound=None)

Broker-level P&L bounds barrier.

Args:

  • settlement_asset: Settlement asset tracked by this barrier.

  • lower_bound: Optional lower P&L bound (typically a negative loss limit).

  • upper_bound: Optional upper P&L bound (typically a positive profit limit).

At least one of lower_bound or upper_bound must be provided.

Parameters:
settlement_asset: str
lower_bound: param.Pnl | None = None
upper_bound: param.Pnl | None = None
class openpit.pretrade.policies.PnlBoundsAccountAssetBarrier(account_id, settlement_asset, initial_pnl, lower_bound=None, upper_bound=None)

Per-account P&L bounds barrier.

Args:

  • account_id: Account this barrier applies to.

  • settlement_asset: Settlement asset tracked by this barrier.

  • initial_pnl: Initial P&L offset loaded at construction.

  • lower_bound: Optional lower P&L bound.

  • upper_bound: Optional upper P&L bound.

At least one of lower_bound or upper_bound must be provided.

Parameters:
account_id: param.AccountId
settlement_asset: str
initial_pnl: param.Pnl
lower_bound: param.Pnl | None = None
upper_bound: param.Pnl | None = None
class openpit.pretrade.policies.PnlBoundsKillswitchReadyBuilder

Fully-configured P&L bounds kill-switch policy builder.

Obtain via build_pnl_bounds_killswitch() and one axis method. All axis methods return self for chaining. Pass to SyncedEngineBuilder.builtin() or ReadyEngineBuilder.builtin().

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

PnlBoundsKillswitchReadyBuilder

broker_barriers(*barriers)

Append broker-level P&L bounds barriers.

Parameters:

barriers (PnlBoundsBrokerBarrier)

Return type:

PnlBoundsKillswitchReadyBuilder

account_barriers(*barriers)

Append per-account P&L bounds barriers.

Parameters:

barriers (PnlBoundsAccountAssetBarrier)

Return type:

PnlBoundsKillswitchReadyBuilder

class openpit.pretrade.policies.PnlBoundsKillswitchBuilder

Entry point for the P&L bounds kill-switch policy builder.

Call build_pnl_bounds_killswitch() to obtain an instance, then call one of the axis methods to obtain a PnlBoundsKillswitchReadyBuilder.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

PnlBoundsKillswitchBuilder

broker_barriers(*barriers)

Add broker-level barriers and return a ready builder.

Parameters:

barriers (PnlBoundsBrokerBarrier)

Return type:

PnlBoundsKillswitchReadyBuilder

account_barriers(*barriers)

Add per-account barriers and return a ready builder.

Parameters:

barriers (PnlBoundsAccountAssetBarrier)

Return type:

PnlBoundsKillswitchReadyBuilder

openpit.pretrade.policies.build_pnl_bounds_killswitch()

Return a new P&L bounds kill-switch policy builder.

Return type:

PnlBoundsKillswitchBuilder

class openpit.pretrade.policies.SpotFundsPricingSource(value)

Market-data quote field used for market-order pricing.

MARK = 'Mark'
BOOK_TOP = 'BookTop'
class openpit.pretrade.policies.SpotFundsOverride(instrument, account_id=None, account_group_id=None, slippage_bps=None)

Spot-funds slippage override for a registered instrument, optionally narrowed to a single account or an account group (mutually exclusive).

When slippage_bps is None the entry is ignored. Resolution order: (instrument, account_id) -> (instrument, account_group_id) -> (instrument) -> global.

Parameters:
instrument: marketdata.InstrumentId
account_id: param.AccountId | None = None
account_group_id: param.AccountGroupId | None = None
slippage_bps: int | None = None
class openpit.pretrade.policies.SpotFundsReadyBuilder

Fully-configured spot funds policy builder.

Obtain via build_spot_funds(). Pass to SyncedEngineBuilder.builtin() or ReadyEngineBuilder.builtin() to register on an engine.

Initial balances are seeded through the account-adjustment pipeline, not via the builder.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

SpotFundsReadyBuilder

market_data(service, default_slippage_bps, pricing_source=SpotFundsPricingSource.MARK, overrides=())

Enable market orders through a live market-data service.

Overrides narrow slippage per instrument, optionally scoped to an account or account group (mutually exclusive). Resolution order: (instrument, account_id) -> (instrument, account_group_id) -> (instrument) -> global.

Calling it more than once replaces the service handle and all market-data bundle parameters.

Parameters:
Return type:

SpotFundsReadyBuilder

class openpit.pretrade.policies.SpotFundsBuilder

Entry point for the spot funds policy.

By default, market orders (orders without a limit price, executed at the prevailing market price) are rejected with UnsupportedOrderType and the policy operates in limit-only mode. Call market_data() to enable market orders through a live market-data service.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

SpotFundsBuilder

market_data(service, default_slippage_bps, pricing_source=SpotFundsPricingSource.MARK, overrides=())

Enable market orders through a live market-data service.

Overrides narrow slippage per instrument, optionally scoped to an account or account group (mutually exclusive).

Parameters:
Return type:

SpotFundsReadyBuilder

openpit.pretrade.policies.build_spot_funds()

Return a new spot funds policy builder.

Initial balances are seeded through the account-adjustment pipeline, not via the builder.

Return type:

SpotFundsBuilder

class openpit.pretrade.policies.RateLimit(max_orders, window)

Maximum orders within a sliding time window.

Args:

  • max_orders: Maximum number of orders accepted within window.

  • window: Length of the sliding time window.

Parameters:
  • max_orders (int)

  • window (timedelta)

max_orders: int
window: timedelta
class openpit.pretrade.policies.RateLimitBrokerBarrier(limit)

Rate limit applied across the entire broker.

Args:

  • limit: The rate limit definition.

Parameters:

limit (RateLimit)

limit: RateLimit
class openpit.pretrade.policies.RateLimitAssetBarrier(limit, settlement_asset)

Rate limit applied per settlement asset.

Args:

  • limit: The rate limit definition.

  • settlement_asset: Settlement asset symbol this barrier tracks.

Parameters:
limit: RateLimit
settlement_asset: str
class openpit.pretrade.policies.RateLimitAccountBarrier(limit, account_id)

Rate limit applied per account.

Args:

  • limit: The rate limit definition.

  • account_id: Account this barrier applies to.

Parameters:
limit: RateLimit
account_id: param.AccountId
class openpit.pretrade.policies.RateLimitAccountAssetBarrier(limit, account_id, settlement_asset)

Rate limit applied per (account, settlement asset) pair.

Args:

  • limit: The rate limit definition.

  • account_id: Account this barrier applies to.

  • settlement_asset: Settlement asset symbol this barrier tracks.

Parameters:
limit: RateLimit
account_id: param.AccountId
settlement_asset: str
class openpit.pretrade.policies.RateLimitReadyBuilder

Fully-configured rate-limit policy builder.

Obtain an instance via build_rate_limit() and one of its axis methods. All axis methods return self so they can be chained. Pass to SyncedEngineBuilder.builtin() or ReadyEngineBuilder.builtin() to register on an engine.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

RateLimitReadyBuilder

broker_barrier(barrier)

Set or replace the broker-wide rate limit.

Parameters:

barrier (RateLimitBrokerBarrier)

Return type:

RateLimitReadyBuilder

asset_barriers(*barriers)

Append per-settlement-asset rate-limit barriers.

Parameters:

barriers (RateLimitAssetBarrier)

Return type:

RateLimitReadyBuilder

account_barriers(*barriers)

Append per-account rate-limit barriers.

Parameters:

barriers (RateLimitAccountBarrier)

Return type:

RateLimitReadyBuilder

account_asset_barriers(*barriers)

Append per-(account, settlement-asset) rate-limit barriers.

Parameters:

barriers (RateLimitAccountAssetBarrier)

Return type:

RateLimitReadyBuilder

class openpit.pretrade.policies.RateLimitBuilder

Entry point for the rate-limit policy builder.

Call build_rate_limit() to obtain an instance, then call one of the axis methods to obtain a RateLimitReadyBuilder.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

RateLimitBuilder

broker_barrier(barrier)

Set the broker-wide rate limit and return a ready builder.

Parameters:

barrier (RateLimitBrokerBarrier)

Return type:

RateLimitReadyBuilder

asset_barriers(*barriers)

Add per-settlement-asset barriers and return a ready builder.

Parameters:

barriers (RateLimitAssetBarrier)

Return type:

RateLimitReadyBuilder

account_barriers(*barriers)

Add per-account barriers and return a ready builder.

Parameters:

barriers (RateLimitAccountBarrier)

Return type:

RateLimitReadyBuilder

account_asset_barriers(*barriers)

Add per-(account, settlement-asset) barriers and return a ready builder.

Parameters:

barriers (RateLimitAccountAssetBarrier)

Return type:

RateLimitReadyBuilder

openpit.pretrade.policies.build_rate_limit()

Return a new rate-limit policy builder.

Return type:

RateLimitBuilder

class openpit.pretrade.policies.OrderValidationBuilder

Order-validation policy builder.

Pass to SyncedEngineBuilder.builtin() or ReadyEngineBuilder.builtin() to register on an engine.

with_policy_group_id(policy_group_id)

Assign the policy group tag.

Parameters:

policy_group_id (int)

Return type:

OrderValidationBuilder

openpit.pretrade.policies.build_order_validation()

Return an order-validation policy builder.

Return type:

OrderValidationBuilder

Account adjustments

Account-adjustment models and policies validate administrative balance or position changes outside the normal order flow.

class openpit.account_adjustment.Adjustment(*args, **kwargs)

Extensible non-trading account-adjustment model.

Snapshot semantics: On Engine.apply_account_adjustment(...), each adjustment item is snapshotted at submission time for policy evaluation. Mutations of adjustment objects after submission do not affect the in-flight batch.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Adjustment

property operation: BalanceOperation | PositionOperation | None

Adjustment operation details group.

property amount: Amount | None

Adjustment amount deltas group.

property bounds: Bounds | None

Optional post-adjustment bounds group.

class openpit.account_adjustment.Amount(*args, **kwargs)

Grouped balance/held/incoming adjustment payload.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Amount

property balance: AdjustmentAmount | None

Actual resulting balance/position value.

property held: AdjustmentAmount | None

Amount earmarked for outgoing settlement.

Unavailable for immediate use.

property incoming: AdjustmentAmount | None

Amount in-flight for incoming acquisition and not yet finalized.

class openpit.account_adjustment.BalanceOperation(*args, **kwargs)

Direct physical balance adjustment.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

BalanceOperation

property asset: Asset

Adjusted balance asset.

property average_entry_price: Price | None

Optional cost basis for the adjusted physical balance.

class openpit.account_adjustment.Bounds(*args, **kwargs)

Optional post-adjustment inclusive limits.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Bounds

property balance_upper: PositionSize | None

Allowed post-adjustment inclusive upper bound for balance.

property balance_lower: PositionSize | None

Allowed post-adjustment inclusive lower bound for balance.

property held_upper: PositionSize | None

Allowed post-adjustment inclusive upper bound for held.

property held_lower: PositionSize | None

Allowed post-adjustment inclusive lower bound for held.

property incoming_upper: PositionSize | None

Allowed post-adjustment inclusive upper bound for incoming.

property incoming_lower: PositionSize | None

Allowed post-adjustment inclusive lower bound for incoming.

class openpit.account_adjustment.PositionOperation(*args, **kwargs)

Direct derivatives-like position adjustment.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

PositionOperation

property instrument: Instrument

Adjusted position instrument.

property collateral_asset: Asset

Collateral asset used by the adjusted position.

property average_entry_price: Price

Average entry price for the adjusted position state.

property mode: PositionMode

Netting vs hedged position representation.

property leverage: Leverage | None

Optional leverage snapshot/setting carried with the position adjustment.