Repository navigation
Policies
Pit exposes two policy stages:
-
Start stage: cheap checks that must see every request and do not need rollback support -
Main stage: deeper checks that may emit multiple rejects or register reversible mutations
Exact interface names differ by SDK and are listed in the language-specific sections below.
The current built-in policies are all start-stage policies.
Current behavior:
- Rejects zero quantity trade amount
- Rejects zero volume trade amount
- Allows missing
trade amount - Allows missing price
- Allows zero price
- Allows negative price
Required fields to populate:
-
Order:trade_amount -
Execution Report: none
Rejects:
- Zero quantity
Code:
InvalidFieldValueReason:order quantity must be non-zero - Zero volume
Code:
InvalidFieldValueReason:order volume must be non-zero
Current behavior:
- Tracks realized P&L by settlement asset
- Triggers when realized P&L reaches or crosses the configured loss barrier
- Stays triggered until
reset_pnlis called - Requires a positive barrier
- Rejects orders immediately when the settlement asset has no configured barrier
Post-trade behavior:
- Uses the report settlement asset
- Starts from report
pnl - Accepts two valid ways to pass trading result:
- Separate:
pnlis net trading P&L before fees,feeis provided separately. The engine appliesfeeas a negative P&L contribution before the barrier check. - Combined:
pnlalready includes fees,feereturnsNoneorFee::ZERO. In that case the fee is not counted twice.
- Separate:
- If the report also includes a fee, the fee is applied as a negative P&L contribution before the barrier check
Required fields to populate:
-
Order:instrument -
Execution Report:instrument,pnl,fee
Rejects:
- Missing barrier for the settlement asset
Code:
RiskConfigurationMissingReason:pnl barrier missing - Active kill switch
Code:
PnlKillSwitchTriggeredScope:accountReason:pnl kill switch triggered
Current behavior:
- Counts
start stageattempts inside a sliding time window - Counts rejected attempts as well as successful ones
- Never rolls the counter back
- Drops expired timestamps when a new request arrives
Required fields to populate:
-
Order: none -
Execution Report: none
Reject:
- Code:
RateLimitExceeded - Scope:
order - Reason:
rate limit exceeded
Current behavior:
- Configures limits per settlement asset
- Requires a configured limit for the order settlement asset
- Uses
volumedirectly for notional checks when it is provided - Derives notional from
|price| × quantitywhen only quantity is provided - Derives quantity from
volume / |price|when only volume is provided - Rejects with
OrderValueCalculationFailedwhenpriceis needed but missing - Returns a single combined reject when both quantity and notional exceed the configured limits
Required fields to populate:
-
Order:instrument,trade_amount,price -
Execution Report: none
Rejects:
- Missing limit for the settlement asset
Code:
RiskConfigurationMissingReason:order size limit missing - Quantity exceeded
Code:
OrderQtyExceedsLimitReason:order quantity exceeded - Notional exceeded
Code:
OrderNotionalExceedsLimitReason:order notional exceeded - Missing
priceor failed size translation Code:OrderValueCalculationFailedReason:order value calculation failed - Both exceeded
Code:
OrderExceedsLimitReason:order size exceeded
Rust exposes first-class traits for custom policies and caller-defined order contracts.
Start-stage policies implement:
CheckPreTradeStartPolicy<O, R>
Main-stage policies implement:
Policy<O, R>
Main-stage policies receive:
-
Context<'_, O>for read-only access to the order -
Mutationsfor reversible state changes -
Vec<Reject>for one or more business rejects
Context currently exposes the original order through ctx.order(). It does
not provide a precomputed notional value.
Python exposes matching high-level policy interfaces over the fixed
record-style openpit.Order and openpit.ExecutionReport models:
openpit.pretrade.CheckPreTradeStartPolicyopenpit.pretrade.Policy
Python business outcomes are returned, not raised:
- Start stage returns
PolicyReject | None - Main stage returns
PolicyDecision
Main-stage Python policies can register:
Mutation.reserve_notional(...)Mutation.kill_switch(...)
Rust
use openpit::param::{Volume, TradeAmount};
use openpit::pretrade::{Context, Mutations, Policy, Reject, RejectCode, RejectScope};
use openpit::{HasOrderPrice, HasTradeAmount};
struct NotionalCapPolicy {
max_abs_notional: Volume,
}
impl<O, R> Policy<O, R> for NotionalCapPolicy
where
O: HasTradeAmount + HasOrderPrice,
{
fn name(&self) -> &'static str {
"NotionalCapPolicy"
}
fn perform_pre_trade_check(
&self,
ctx: &Context<'_, O>,
_mutations: &mut Mutations,
rejects: &mut Vec<Reject>,
) {
let order = ctx.order();
let trade_amount = match order.trade_amount() {
Ok(trade_amount) => trade_amount,
Err(error) => {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::MissingRequiredField,
"required order field missing",
error.to_string(),
));
return;
}
};
let price = match order.price() {
Ok(price) => price,
Err(error) => {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::MissingRequiredField,
"required order field missing",
error.to_string(),
));
return;
}
};
let requested_notional = match (trade_amount, price) {
(TradeAmount::Volume(volume), _) => volume,
(TradeAmount::Quantity(quantity), Some(price)) => match price.calculate_volume(quantity)
{
Ok(v) => v,
Err(_) => {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::OrderValueCalculationFailed,
"order value calculation failed",
"price and quantity could not be used to evaluate notional",
));
return;
}
},
(TradeAmount::Quantity(_), None) => {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::OrderValueCalculationFailed,
"order value calculation failed",
"price not provided for evaluating cash flow/notional/volume",
));
return;
}
_ => {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::UnsupportedOrderType,
"unsupported order type",
"custom trade amount variant is not supported by this policy",
));
return;
}
};
if requested_notional > self.max_abs_notional {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::RiskLimitExceeded,
"strategy cap exceeded",
format!(
"requested notional {}, max allowed: {}",
requested_notional, self.max_abs_notional
),
));
}
}
fn apply_execution_report(&self, _report: &R) -> bool {
false
}
}Python
import typing
import openpit
class NotionalCapPolicy(openpit.pretrade.Policy):
@typing.override
def __init__(self, max_abs_notional: openpit.param.Volume) -> None:
self._max_abs_notional = max_abs_notional
@property
@typing.override
def name(self) -> str:
return "NotionalCapPolicy"
@typing.override
def perform_pre_trade_check(
self,
*,
context: openpit.pretrade.PolicyContext,
) -> openpit.pretrade.PolicyDecision:
assert context.order.operation is not None
trade_amount = context.order.operation.trade_amount
if isinstance(trade_amount, openpit.param.Volume):
requested_notional = trade_amount
else:
assert isinstance(trade_amount, openpit.param.Quantity)
assert context.order.operation.price is not None
requested_notional = context.order.operation.price.calculate_volume(
trade_amount
)
if requested_notional > self._max_abs_notional:
return openpit.pretrade.PolicyDecision.reject(
rejects=[
openpit.pretrade.PolicyReject(
code=openpit.pretrade.RejectCode.RISK_LIMIT_EXCEEDED,
reason="strategy cap exceeded",
details=(
"requested notional "
f"{requested_notional.value}, "
f"max allowed: {self._max_abs_notional.value}"
),
scope=openpit.pretrade.RejectScope.ORDER,
)
]
)
return openpit.pretrade.PolicyDecision.accept(
mutations=[
openpit.pretrade.Mutation.reserve_notional(
settlement_asset=context.order.operation.instrument.settlement_asset,
commit_amount=requested_notional,
rollback_amount=openpit.param.Volume("0"),
)
]
)
@typing.override
def apply_execution_report(
self,
*,
report: openpit.ExecutionReport,
) -> bool:
_ = report
return FalseRust
Rust project part uses capability traits (Has*) and can compose
OrderOperation with project-only fields plus Deref to inherit required
capabilities.
See Custom Rust Types for the full companion derive setup, manual trait implementations, and finer-grained wrapper composition of custom order and execution-report models.
use std::ops::Deref;
use openpit::param::{AccountId, Asset, Fee, Pnl, Price, Quantity, Side, TradeAmount};
use openpit::pretrade::{Context, Mutations, Policy, Reject, RejectCode, RejectScope};
use openpit::{
Engine, ExecutionReportOperation, FinancialImpact, HasTradeAmount, Instrument,
OrderOperation, WithExecutionReportOperation, WithFinancialImpact,
};
type PitExecutionReport = WithExecutionReportOperation<WithFinancialImpact<()>>;
#[derive(Clone)]
struct StrategyOrder {
base: OrderOperation,
// Project field: this field is added by the host application, not by the SDK.
strategy_tag: &'static str,
}
impl Deref for StrategyOrder {
type Target = OrderOperation;
fn deref(&self) -> &Self::Target {
&self.base
}
}
struct StrategyExecutionReport {
base: PitExecutionReport,
// Project field: this field is added by the host application, not by the SDK.
report_tag: &'static str,
}
impl Deref for StrategyExecutionReport {
type Target = PitExecutionReport;
fn deref(&self) -> &Self::Target {
&self.base
}
}
trait HasStrategyTag {
fn strategy_tag(&self) -> &'static str;
}
impl HasStrategyTag for StrategyOrder {
fn strategy_tag(&self) -> &'static str {
self.strategy_tag
}
}
struct StrategyTagPolicy;
impl<O, R> Policy<O, R> for StrategyTagPolicy
where
O: HasStrategyTag + HasTradeAmount,
{
fn name(&self) -> &'static str {
"StrategyTagPolicy"
}
fn perform_pre_trade_check(
&self,
ctx: &Context<'_, O>,
_mutations: &mut Mutations,
rejects: &mut Vec<Reject>,
) {
let order = ctx.order();
if order.strategy_tag() == "blocked" {
rejects.push(Reject::new(
<Self as Policy<O, R>>::name(self),
RejectScope::Order,
RejectCode::ComplianceRestriction,
"strategy blocked",
"project strategy tag blocked",
));
}
}
fn apply_execution_report(&self, _report: &R) -> bool {
false
}
}
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let engine = Engine::<StrategyOrder, StrategyExecutionReport>::builder()
.pre_trade_policy(StrategyTagPolicy)
.build()?;
let order = StrategyOrder {
base: OrderOperation {
instrument: Instrument::new(
Asset::new("AAPL")?,
Asset::new("USD")?,
),
account_id: AccountId::from_u64(99224416),
side: Side::Buy,
trade_amount: TradeAmount::Quantity(
Quantity::from_str("10")?
),
price: Some(Price::from_str("25")?),
},
// Set this to "blocked" to trigger the same policy reject path as in Python.
strategy_tag: "allowed",
};
let request = engine.start_pre_trade(order)?;
let reservation = request.execute()?;
reservation.commit();
# Ok(())
# }Python
Python custom models inherit from openpit.Order or openpit.ExecutionReport,
and the original subclass instance reaches policy callbacks unchanged.
import typing
import openpit
class StrategyOrder(openpit.Order):
@typing.override
def __init__(self, *, strategy_tag: str) -> None:
super().__init__(
operation=openpit.OrderOperation(
instrument=openpit.Instrument(
openpit.param.Asset("AAPL"),
openpit.param.Asset("USD"),
),
side=openpit.param.Side.BUY,
account_id=openpit.param.AccountId.from_u64(99224416),
trade_amount=openpit.param.Quantity("10"),
price=openpit.param.Price("25"),
),
)
# Project field: this field is added by the host application,
# not by the SDK.
self.strategy_tag = strategy_tag
class StrategyReport(openpit.ExecutionReport):
@typing.override
def __init__(self, *, report_tag: str) -> None:
super().__init__(
operation=openpit.ExecutionReportOperation(
instrument=openpit.Instrument(
openpit.param.Asset("AAPL"),
openpit.param.Asset("USD"),
),
side=openpit.param.Side.BUY,
account_id=openpit.param.AccountId.from_u64(99224416),
),
financial_impact=openpit.FinancialImpact(
pnl=openpit.param.Pnl("5"),
fee=openpit.param.Fee("1"),
),
)
# Project field: this field is added by the host application,
# not by the SDK.
self.report_tag = report_tag
class StrategyTagPolicy(openpit.pretrade.Policy):
@property
@typing.override
def name(self) -> str:
return "StrategyTagPolicy"
@typing.override
def perform_pre_trade_check(
self,
*,
context: openpit.pretrade.PolicyContext,
) -> openpit.pretrade.PolicyDecision:
order = typing.cast(StrategyOrder, context.order)
if order.strategy_tag == "blocked":
return openpit.pretrade.PolicyDecision.reject(
rejects=[
openpit.pretrade.PolicyReject(
code=openpit.pretrade.RejectCode.COMPLIANCE_RESTRICTION,
reason="strategy blocked",
details="project strategy tag blocked",
scope=openpit.pretrade.RejectScope.ORDER,
)
]
)
return openpit.pretrade.PolicyDecision.accept()
@typing.override
def apply_execution_report(
self,
*,
report: openpit.ExecutionReport,
) -> bool:
strategy_report = typing.cast(StrategyReport, report)
_ = strategy_report
return False
engine = openpit.Engine.builder().pre_trade_policy(policy=StrategyTagPolicy()).build()
order = StrategyOrder(strategy_tag="allowed")
start_result = engine.start_pre_trade(order=order)
if not start_result.ok:
raise RuntimeError(start_result.reject.reason)
execute_result = start_result.request.execute()
if not execute_result.ok:
raise RuntimeError(execute_result.rejects[0].reason)
execute_result.reservation.commit()
report = StrategyReport(report_tag="fill-1")
post_trade = engine.apply_execution_report(report=report)
assert post_trade.kill_switch_triggered is False- Pre-trade Pipeline: Request and reservation semantics
- Domain Types: Value types used by built-in and custom policies
- Reject Codes: Standard business reject codes
- Architecture: Public integration model