Repository navigation
Policies
OpenPit 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.
Built-in policies use an axis-based configuration model. Each policy has one or more axes - dimensions along which a limit or barrier is applied. An axis becomes active only when a barrier is explicitly configured for it.
Common axes across built-in policies:
- Broker axis: applies to all orders regardless of account or asset.
-
Asset axis: usually applies to all orders with a given settlement asset.
OrderSizeLimitPolicyis the exception: it resolves quantity by underlying asset and notional by settlement asset; see OrderSizeLimitPolicy. - Account axis: applies to all orders from a given account.
-
Account+Asset axis: usually applies to orders from a specific account and
settlement asset pair.
OrderSizeLimitPolicyapplies the same underlying / settlement split within the account; see OrderSizeLimitPolicy.
An axis without a matching barrier never rejects the order. At least one axis must be configured; constructors return an error if all axes are empty.
The sync policy is chosen on the engine builder. It controls how stateful built-in policies synchronize their internal storage and defines the engine handle's threading capability (see Threading Contract for the per-mode contract).
| Mode | Behavior | Use case |
|---|---|---|
| Full sync | Thread-safe handle; concurrent invocation on the same handle is safe. | Engine is shared across threads, or migration patterns make sequential pinning impractical. |
| No sync | Single-threaded handle; calls must stay on the OS thread that created the engine. | Single-threaded embedding; zero synchronization overhead. |
| Account sync | Concurrent calls for distinct accounts; caller pins each account to one processing chain and runs exclusive operations alone. | Account-sharded workloads where one worker / queue owns each account. |
Storage owned by a built-in or custom policy is always account-keyed
when used through binding-facing storage contracts: the top-level key
carries an account id, and the per-account value can be any structure the
policy needs. The choice of sync mode does not change this rule.
Method names per language:
Go
openpit.NewEngineBuilder().FullSync()openpit.NewEngineBuilder().NoSync()openpit.NewEngineBuilder().AccountSync()
If you are unsure, start with FullSync(): goroutines migrate between OS
threads at any await point, so even a single goroutine calling the engine
sequentially can wake up on a different OS thread than the one it suspended on.
FullSync() is the safe default.
AccountSync() only requires that calls for the same account are never
concurrent and that the
exclusive operations run alone - it
does not require a fixed OS thread. The standard Go pattern is
a sharded worker pool: hash the account ID to one of N channels; one goroutine
drains each channel, so the same account always lands on the same worker.
const shards = 256
type task struct {
accountID string
order model.Order
}
// One channel per shard, one goroutine draining each channel: the same
// account always lands on the same worker, so AccountSync holds.
workers := make([]chan task, shards)
for i := range workers {
ch := make(chan task, 1024)
workers[i] = ch
go func(ch <-chan task) {
for t := range ch {
req, _, _ := engine.ExecutePreTrade(t.order)
if req != nil {
req.Close()
}
}
}(ch)
}
// fnv32 hashes the account ID; the modulo pins each account to one shard.
dispatch := func(t task) {
workers[fnv32(t.accountID)%shards] <- t
}Different shards run in parallel; all orders for the same account always go to the same shard and are processed sequentially.
Python
openpit.Engine.builder().full_sync()openpit.Engine.builder().no_sync()openpit.Engine.builder().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() only when you actually share the engine
across threads concurrently. Use account_sync() for sharded sequential
workloads where each account is pinned to one processing chain.
JavaScript
Engine.builder()
The WebAssembly binding is single-threaded and exposes no user-selectable sync mode. One engine instance runs synchronously on the calling thread; use one engine per worker or isolate when you need parallelism.
C++
openpit::EngineBuilder(openpit::SyncPolicy::Full)openpit::EngineBuilder(openpit::SyncPolicy::None)openpit::EngineBuilder(openpit::SyncPolicy::Account)
The sync policy is a constructor argument on openpit::EngineBuilder; the SDK
does not impose a default. Prefer SyncPolicy::None for a single-threaded
embedding with zero synchronization overhead. Use SyncPolicy::Full only when
the engine handle is actually shared across threads concurrently, and
SyncPolicy::Account for sharded sequential workloads where each account is
pinned to one processing chain.
Rust
Engine::builder::<OrderOperation, (), ()>().full_sync()Engine::builder::<OrderOperation, (), ()>().no_sync()Engine::builder::<OrderOperation, (), ()>().account_sync()
The choice depends on the embedding; the SDK does not impose a default.
The engine maintains an internal blocked-accounts registry next to the policy chain. An effective account-scoped reject or an effective account block records the affected account. The engine short-circuits subsequent ordinary pre-trade requests for that account before any policy runs.
The block is owned by the engine, not by the policy. A policy must not keep its own "this account is blocked" flag and must not re-check the condition on every order - returning the reject once is the entire contract. Once a block is recorded, the engine guarantees the policy is not invoked again for an ordinary pre-trade request on that account until the block is cleared. Drop copy still invokes the policy because it records an order that already happened.
- A start-stage or main-stage callback returns an effective account-scoped reject. A review mark cannot latch a block. An evaluation failure remains eligible in any mode.
- A policy reports an effective
AccountBlockduring execution-report handling or runtime configuration. For a review instance, only blocks with evaluation-failure codes are effective. - In Go, an
ApplyExecutionReportpolicy callback panics; the binding recovers it as aSystemUnavailableaccount block. - A mutation commit or rollback callback reports a failure. That finalizer had no
right to fail, so the engine arms a
SystemUnavailablekill switch rather than dropping the failure; see Account Blocking - Mutation Finalizer Contract.
Use scope = order when an effective reject should affect only the current
order, for example for a transient condition. Lift an engine-recorded block
with accounts().unblock(account); see Account Blocking.
Only the first AccountBlock recorded for an account is kept. Later
recordings for the same account are no-ops - first cause wins. When
apply execution report is dispatched across policies, the engine records
only the first effective block. PostTradeResult reports all effective blocks
from that call.
- If the offending order or report exposes an
account id, only that account is blocked, across every settlement asset and instrument. - If an execution report cannot produce an
account id, the engine activates an engine-wide block and rejects every subsequent pre-trade request, regardless of account. The report describes exposure that already exists and the engine cannot attribute it, so it stops everything. - If a pre-trade order cannot produce an
account id, nothing is recorded. The order is still rejected, but a rejected request created no exposure, so it never justifies stopping every account. - If a mutation finalizer fails, the reach follows the mutation's provenance, not the pipeline: a built-in policy's mutation blocks the pipeline's account, while a custom policy's mutation - which every mutation registered through a binding is - blocks every account. See Account Blocking - Mutation Finalizer Contract.
- Drop copy never reaches this decision: an order whose
account idcannot be read is rejected withMissingRequiredFieldbefore any policy runs, because the account is the engine's routing and account-control key. No block of either kind is recorded.
Existing account and account-group blocks do not gate drop copy. Effective account-scoped rejects remain non-enforcing for the historical order. On the accepted path, the engine applies their ordered account-control operations before returning the operation. Those effects persist across caller rollback, so later ordinary pre-trade requests are stopped. The accepted operation reports the first block requested by that call and a snapshot of the effective state when apply returned, which can reflect an earlier block. A fatal evaluation failure returns rejects instead of an operation and abandons the recorded account-control operations.
- For blocks triggered by start-stage or main-stage rejects, future rejects on
that account carry
code = AccountBlockedand replay thepolicy,reason, anddetailsfrom the original reject. - For blocks triggered by
apply execution report, future rejects replay thecode,reason, anddetailsfrom theAccountBlockthe policy emitted (for examplePnlKillSwitchTriggered). - While any block is active and an order arrives without an
account id, the engine rejects it withMissingRequiredFieldand the order scope.
A blocked account stays blocked until it is explicitly unblocked or the engine
is rebuilt. There is no implicit unblock: rerunning the original check,
replaying the order, retrying the request, or letting time pass does not lift
the block. A block recorded by the engine can also be lifted explicitly without
a rebuild by calling accounts().unblock(account) on the engine's accounts
handle. An engine-wide block is cleared by its own call, unblock all, which
leaves accounts and account groups blocked individually intact; see
Account Blocking for the full admin API and the per-language
names.
The descriptions below use the default Reject instance mode. See
Review Mode for how the engine classifies other modes.
It tracks per-account spendable funds and rejects orders an account cannot
afford. Each (account, asset) slot holds three buckets - available, held,
and incoming. A reserve moves the outflow amount from available to held
and simultaneously records the expected inflow on the acquiring leg as
incoming (buy: base asset quantity; priced sell: settlement proceeds). A fill
consumes held and credits the acquired asset to available, reducing
incoming by the filled amount. A final report releases the reservation
remainder the caller supplies on it, from both held and incoming; the engine
derives no remainder of its own. The incoming bucket never enters the
solvency check; it gates orders only through a configured position limit.
Balances are seeded only through the account adjustment
pipeline.
For configuration depth - market-order pricing, slippage, per-instrument overrides, and the holdings lifecycle - see the dedicated Spot Funds page. To keep your own ledger aligned with the funds the policy moves, see Balance Reconciliation.
What it controls:
- Rejects orders whose cost exceeds
availableplusheldfunds under the default Enforce mode; review modes produce a review mark instead - see Spot Funds - Funds Limit Mode - Prices market orders from a market data bundle when configured
- Optionally blocks an account when its single engine-computed realized account
PnL moves outside a configured bound or becomes halted; PnL barriers carry a
rule mode, so numeric breaches block only
for
Rejectbarriers. These bounds watch the account, but every barrier carries a currency. For an account with a known effective currency, an account barrier in another currency is a configuration fault: it blocks that account withPnlKillSwitchTriggeredand reasonpnl barrier currency mismatch, without falling through to group or global. Group and global barriers in another currency are skipped; if no account barrier exists and neither fallback matches, the account has no control at all. Without an effective currency, no level is filtered by currency and the first in-scope barrier is effective. Bounds are never FX-converted. When missing FX halts the account PnL while an effective barrier applies, the post-trade report is processed and the account is then blocked; subsequent pre-trade requests are rejected - see Spot Funds - Self-Computed PnL Kill Switch - Also supports runtime bounds on account unrealized and total PnL and on each position's unrealized and total PnL, using the same tier and currency rules; see Unrealized and Total PnL Bounds.
- Optionally caps how far an order may push an account's worst-case position
per asset, long or short, working orders included. Each limit carries a rule
mode: a
Rejectlimit's breach rejects the order without blocking the account; a review limit's breach produces a review mark - see Spot Funds - Position Limit
Required fields to populate:
-
Order:instrument,account id,side,trade amount, optionalprice -
Execution Report:instrument,account id,side, fill details -
Account Adjustment:balance operation,amount,bounds
Rejects:
- Insufficient spendable funds under the default Enforce mode; review modes
produce a review mark instead - see
Spot Funds - Funds Limit Mode
Code:
InsufficientFunds, Scope:order - Projected position beyond a configured
Reject-mode position limit Code:PositionLimitExceeded, Scope:order - Market order with no market-data bundle configured
Code:
UnsupportedOrderType, Scope:order - Market order priced from a stale or missing quote field; or a sell order with
no order price and no market-data price
Code:
MarkPriceUnavailable, Scope:order - Execution report (fill or cancel) arrives without its lock price
Code:
MissingRequiredField, Scope:account
Go
engine, err := openpit.NewEngineBuilder().
NoSync().
Builtin(policies.BuildSpotFunds()).
Build()Python
import openpit
import openpit.pretrade.policies
# Limit-only spot funds, registered first in the policy list.
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(openpit.pretrade.policies.build_spot_funds())
.build()
)JavaScript
import { Engine } from "@openpit/engine";
import { buildSpotFunds } from "@openpit/engine/pretrade/policies";
// Limit-only spot funds, registered first in the policy list.
const engine = Engine.builder().builtin(buildSpotFunds()).build();C++
namespace policies = openpit::pretrade::policies;
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
// Limit-only mode: no market-data service handle.
builder.Add(policies::SpotFundsPolicy{});
const openpit::Engine engine = builder.Build();Rust
use openpit::pretrade::policies::{SpotFundsPolicy, SpotFundsSettings};
use openpit::{
Engine, FullSync, OrderOperation, SpotFundsMarketData, SpotFundsPricingSource,
WithAccountAdjustmentAmount, WithAccountAdjustmentBalanceOperation,
WithAccountAdjustmentBounds, WithExecutionReportFillDetails, WithExecutionReportOperation,
};
// Report and account-adjustment shapes composed from public SDK wrappers.
type SpotReport = WithExecutionReportOperation<WithExecutionReportFillDetails<()>>;
type SpotAdjustment = WithAccountAdjustmentAmount<
WithAccountAdjustmentBounds<
WithAccountAdjustmentBalanceOperation<openpit::AccountAdjustmentAmount>,
>,
>;
let builder = Engine::builder::<OrderOperation, SpotReport, SpotAdjustment>().full_sync();
// Limit-only mode: no market-data bundle.
let policy = SpotFundsPolicy::<FullSync, FullSync>::new(
SpotFundsSettings::new(0, SpotFundsPricingSource::Mark, [])?,
None::<SpotFundsMarketData<FullSync>>,
builder.storage_builder(),
);
let engine = builder.pre_trade(policy).build()?;Validates basic order structure before more expensive checks. Does not validate price, side, instrument, or account.
This is a live-admission policy and is intentionally inert for drop copy. A completed historical order is not revalidated, and missing validation-only fields do not abort its bookkeeping.
What it controls:
- Rejects zero quantity
trade amount - Rejects zero volume
trade amount
Required fields to populate:
-
Order:trade amount -
Execution Report: none
Rejects:
- Missing
trade amountCode:MissingRequiredField, Scope:orderReason:failed to access required field - Zero quantity
Code:
InvalidFieldValue, Scope:orderReason:order quantity must be non-zero - Zero volume
Code:
InvalidFieldValue, Scope:orderReason:order volume must be non-zero
Go
engine, err := openpit.NewEngineBuilder().
NoSync().
Builtin(
policies.BuildOrderValidation(),
).
Build()Python
import openpit
import openpit.pretrade.policies
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(
openpit.pretrade.policies.build_order_validation(),
)
.build()
)JavaScript
import { Engine } from "@openpit/engine";
import { buildOrderValidation } from "@openpit/engine/pretrade/policies";
const engine = Engine.builder()
.builtin(buildOrderValidation())
.build();C++
namespace policies = openpit::pretrade::policies;
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
builder.Add(policies::OrderValidationPolicy{});
const openpit::Engine engine = builder.Build();Rust
use openpit::pretrade::policies::OrderValidationPolicy;
use openpit::{Engine, OrderOperation};
let engine = Engine::builder::<OrderOperation, (), ()>()
.no_sync()
.pre_trade(OrderValidationPolicy::new())
.build()?;Counts start-stage attempts inside a time window. Flood semantics: rejected attempts count against the limit to prevent bypass by retrying.
One instance carries both reject and review thresholds. Every barrier on every
axis has a mode: Reject, ReviewWithHold, or ReviewWithoutHold. The mode is
part of the rule's key, so a target can have one barrier per mode, each with its
own counter. For example, a broker can reject above three attempts and request
review above one attempt in the same window.
An omitted mode means Reject: C mode 0, the Go zero value, the C++ member
default, Python mode=None, and an absent or null JavaScript mode. Rust
struct literals supply mode explicitly. Repeating the same target and mode
in one input is a configuration error, both at build and at runtime. Each
binding uses its existing error channel; a failed retune leaves all settings
unchanged.
Drop copy spends the same budget at the same start-stage point as an ordinary request. The attempt remains counted even if a later policy cannot evaluate the historical order or the caller rolls back the returned operation; rate-limit counters are not deferred or rolled back specially for drop copy.
What it controls (by axis):
- Broker axis: global limit across all orders. Uses an approximate fixed-window counter.
- Asset axis: limit per settlement asset. Uses an approximate fixed-window counter.
- Account axis: limit per account. Uses a precise sliding-window log.
- Account+Asset axis: limit per account and settlement asset pair. Uses a precise sliding-window log.
Every axis uses scope = order, including account and account+asset. A
Reject breach refuses the current request; a review breach produces a review
mark. No rate-limit axis records a block in the blocked-accounts registry.
The counter and its configured window decide when the target is back within
the threshold.
Choose an axis by what it should meter, not by how far its refusal reaches.
- After required fields are read, every live start spends one unit on every applicable threshold, in every mode. A confirmed rerun also spends a unit; the engine drops its review marks. Execute spends no second unit. A dry run spends nothing.
- A required-field access failure returns
MissingRequiredFieldbefore counting any threshold. - All applicable axes are counted before breaches are resolved. Within each mode the priority is broker -> asset -> account -> account+asset.
- Each run returns at most one mark per review mode, from that mode's highest-priority breached axis. Any effective reject wins over every mark.
The refusal and one-mark-per-review-mode statements above assume the default
Reject instance mode. In a review instance, a
Reject threshold breach instead becomes a mark of the instance mode and can
appear alongside a review-threshold mark of that same mode.
Limit parameters (RateLimit):
| Field | Type | Description |
|---|---|---|
max orders |
integer | maximum attempts in the window |
window |
duration | length of the time window |
Required fields to populate:
-
Order:instrument(when asset or account+asset axes are configured),account id(when account or account+asset axes are configured) -
Execution Report: none
Rejects:
- Code:
RateLimitExceeded, Scope:orderReason:rate limit exceeded: broker barrier - Code:
RateLimitExceeded, Scope:orderReason:rate limit exceeded: asset barrier - Code:
RateLimitExceeded, Scope:orderReason:rate limit exceeded: account barrier - Code:
RateLimitExceeded, Scope:orderReason:rate limit exceeded: account+asset barrier - Code:
MissingRequiredField, Scope:order(when a required field cannot be read)
Review marks use RateLimitExceeded, scope order, the breached barrier's
reason above, and its review mode. MissingRequiredField remains a reject.
The broker builder accepts a list, at most one barrier per mode: Go
BrokerBarriers(...), Python broker_barriers(*barriers), JavaScript
brokerBarriers([...]), repeated C++ BrokerBarrier(...) calls, and the
first iterable passed to Rust RateLimitSettings::new. Runtime replacement
uses a patch list.
Go
engine, err := openpit.NewEngineBuilder().
NoSync().
Builtin(
policies.BuildRateLimit().
BrokerBarriers(
policies.RateLimitBrokerBarrier{
Mode: reject.RuleModeReject,
Limit: policies.RateLimit{
MaxOrders: 100,
Window: time.Second,
},
},
),
).
Build()Python
import datetime
import openpit
import openpit.pretrade.policies
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(
openpit.pretrade.policies.build_rate_limit()
.broker_barriers(
openpit.pretrade.policies.RateLimitBrokerBarrier(
limit=openpit.pretrade.policies.RateLimit(
max_orders=100,
window=datetime.timedelta(seconds=1),
),
),
)
)
.build()
)JavaScript
import { Engine } from "@openpit/engine";
import {
buildRateLimit,
RateLimit,
RateLimitBrokerBarrier,
} from "@openpit/engine/pretrade/policies";
// windowMs is the rolling-window length in milliseconds (1 second here).
const engine = Engine.builder()
.builtin(
buildRateLimit().brokerBarriers([
new RateLimitBrokerBarrier(new RateLimit(100, 1000)),
]),
)
.build();C++
namespace policies = openpit::pretrade::policies;
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
builder.Add(policies::RateLimitPolicy{}.BrokerBarrier(
policies::RateLimitBrokerBarrier(policies::RateLimit(
/*maxOrders=*/100, /*windowNanoseconds=*/1'000'000'000))));
const openpit::Engine engine = builder.Build();Rust
use std::time::Duration;
use openpit::pretrade::policies::{
RateLimit,
RateLimitBrokerBarrier,
RateLimitPolicy,
RateLimitSettings,
};
use openpit::{
Engine, OrderOperation, WithExecutionReportOperation, WithFinancialImpact,
};
type Report = WithExecutionReportOperation<WithFinancialImpact<()>>;
let builder = Engine::builder::<OrderOperation, Report, ()>().no_sync();
let policy = RateLimitPolicy::new(
RateLimitSettings::new(
[RateLimitBrokerBarrier {
mode: openpit::pretrade::RuleMode::Reject,
limit: RateLimit {
max_orders: 100,
window: Duration::from_secs(1),
},
}],
[], // asset barriers
[], // account barriers
[], // account+asset barriers
)?,
builder.storage_builder(),
);
let engine = builder.pre_trade(policy).build()?;One policy has a one-hour broker window with Reject at three attempts and
ReviewWithoutHold at one. Order 1 passes without marks, order 2 passes with
one mark, and its confirmed rerun passes without marks while spending the
third unit. Order 3 is rejected.
Go
engine, err := openpit.NewEngineBuilder().NoSync().Builtin(
policies.BuildRateLimit().BrokerBarriers(
policies.RateLimitBrokerBarrier{
Mode: reject.RuleModeReject,
Limit: policies.RateLimit{MaxOrders: 3, Window: time.Hour},
},
policies.RateLimitBrokerBarrier{
Mode: reject.RuleModeReviewWithoutHold,
Limit: policies.RateLimit{MaxOrders: 1, Window: time.Hour},
},
),
).Build()
if err != nil {
return err
}
defer engine.Stop()
order := model.NewOrder()
// First order: accepted, no review marks.
request, rejects, err := engine.StartPreTrade(order)
if err != nil {
return err
}
if request == nil || len(rejects) != 0 {
return fmt.Errorf("first order rejects: %v", rejects)
}
reviews, err := request.Reviews()
request.Close()
if err != nil {
return err
}
fmt.Println(len(reviews)) // 0
// Second order: accepted, one review mark.
request, rejects, err = engine.StartPreTrade(order)
if err != nil {
return err
}
if request == nil || len(rejects) != 0 {
return fmt.Errorf("second order rejects: %v", rejects)
}
reviews, err = request.Reviews()
request.Close()
if err != nil {
return err
}
if len(reviews) != 1 {
return fmt.Errorf("second order reviews: %v, want one mark", reviews)
}
// Both comparisons print true.
fmt.Println(reviews[0].Code == reject.CodeRateLimitExceeded)
fmt.Println(reviews[0].Mode == reject.RuleModeReviewWithoutHold)
// Confirm the second order: no mark, but the attempt still counts.
review := order.EnsureReviewView()
review.SetConfirmed(true)
request, rejects, err = engine.StartPreTrade(order)
if err != nil {
return err
}
if request == nil || len(rejects) != 0 {
return fmt.Errorf("confirmed order rejects: %v", rejects)
}
reviews, err = request.Reviews()
request.Close()
if err != nil {
return err
}
fmt.Println(len(reviews)) // 0
// Third order: rejected after the confirmed attempt spent the third unit.
review.SetConfirmed(false)
request, rejects, err = engine.StartPreTrade(order)
if err != nil {
return err
}
if request != nil {
request.Close()
}
if request != nil || len(rejects) != 1 {
return fmt.Errorf("third order rejects: %v, want one reject", rejects)
}
// Both comparisons print true.
fmt.Println(rejects[0].Code == reject.CodeRateLimitExceeded)
fmt.Println(rejects[0].Mode == reject.RuleModeReject)Python
import datetime
import openpit
from openpit.pretrade import RuleMode, policies
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(
policies.build_rate_limit().broker_barriers(
policies.RateLimitBrokerBarrier(
limit=policies.RateLimit(3, datetime.timedelta(hours=1)),
mode=RuleMode.REJECT,
),
policies.RateLimitBrokerBarrier(
limit=policies.RateLimit(1, datetime.timedelta(hours=1)),
mode=RuleMode.REVIEW_WITHOUT_HOLD,
),
)
)
.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("1"),
price=openpit.param.Price("100"),
)
)
# The first order is accepted without review marks.
first = engine.execute_pre_trade(order=order)
assert first.ok and first.reviews == []
first.reservation.commit()
# The second order is accepted with one review mark.
second = engine.execute_pre_trade(order=order)
assert second.ok and len(second.reviews) == 1
assert second.reviews[0].mode == RuleMode.REVIEW_WITHOUT_HOLD
assert second.reviews[0].code == openpit.pretrade.RejectCode.RATE_LIMIT_EXCEEDED
second.reservation.commit()
# Confirm the second order: no mark, but the attempt still counts.
confirmed_order = openpit.Order(
operation=order.operation, review=openpit.OrderReview(confirmed=True)
)
confirmed = engine.execute_pre_trade(order=confirmed_order)
assert confirmed.ok and confirmed.reviews == []
confirmed.reservation.commit()
# The third order is rejected after the confirmed attempt spent a unit.
third = engine.execute_pre_trade(order=order)
assert not third.ok
assert third.rejects[0].mode == RuleMode.REJECT
assert third.rejects[0].code == openpit.pretrade.RejectCode.RATE_LIMIT_EXCEEDEDJavaScript
import { Engine } from "@openpit/engine";
import { type OrderInit } from "@openpit/engine/model";
import { TradeAmount } from "@openpit/engine/param";
import { RuleMode } from "@openpit/engine/reject";
import {
buildRateLimit,
RateLimit,
RateLimitBrokerBarrier,
} from "@openpit/engine/pretrade/policies";
const engine = Engine.builder()
.builtin(
buildRateLimit().brokerBarriers([
new RateLimitBrokerBarrier(
new RateLimit(3, 3_600_000),
RuleMode.Reject,
),
new RateLimitBrokerBarrier(
new RateLimit(1, 3_600_000),
RuleMode.ReviewWithoutHold,
),
]),
)
.build();
const order: OrderInit = {
operation: {
underlyingAsset: "AAPL",
settlementAsset: "USD",
accountId: 99224416,
side: "BUY",
tradeAmount: TradeAmount.quantity("1"),
price: "100",
},
};
// The first order is accepted without review marks.
const first = engine.startPreTrade(order);
if (!first.ok) {
throw new Error("unexpected rejects");
}
console.log(first.reviews.length); // 0
// The second order is accepted with one review mark.
const second = engine.startPreTrade(order);
if (!second.ok) {
throw new Error("unexpected rejects");
}
console.log(second.reviews.length); // 1
console.log(second.reviews[0]?.code); // "RateLimitExceeded"
console.log(second.reviews[0]?.mode === RuleMode.ReviewWithoutHold); // true
// Confirm the second order: no mark, but the attempt still counts.
order.review = { confirmed: true };
const confirmed = engine.startPreTrade(order);
if (!confirmed.ok) {
throw new Error("unexpected rejects");
}
console.log(confirmed.reviews.length); // 0
// The third order is rejected after the confirmed attempt spent a unit.
order.review = { confirmed: false };
const third = engine.startPreTrade(order);
if (third.ok) {
throw new Error("expected a rate-limit reject");
}
console.log(third.rejects[0]?.code); // "RateLimitExceeded"
console.log(third.rejects[0]?.mode === RuleMode.Reject); // trueC++
namespace policies = openpit::pretrade::policies;
using openpit::reject::RuleMode;
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
builder.Add(
policies::RateLimitPolicy{}
.BrokerBarrier(policies::RateLimitBrokerBarrier(
policies::RateLimit(3, 3'600'000'000'000), RuleMode::Reject))
.BrokerBarrier(policies::RateLimitBrokerBarrier(
policies::RateLimit(1, 3'600'000'000'000),
RuleMode::ReviewWithoutHold)));
const openpit::Engine engine = builder.Build();
openpit::model::Order order;
const auto first = engine.StartPreTrade(order);
std::cout << std::boolalpha << first.Passed() << "\n"; // true
if (!first.Passed()) {
throw std::runtime_error("unexpected first-order rejects");
}
std::cout << first.request->Reviews().empty() << "\n"; // true
const auto second = engine.StartPreTrade(order);
std::cout << std::boolalpha << second.Passed() << "\n"; // true
if (!second.Passed()) {
throw std::runtime_error("unexpected second-order rejects");
}
const auto reviews = second.request->Reviews();
std::cout << reviews.size() << "\n"; // 1
if (reviews.size() != 1) {
throw std::logic_error("expected one review mark");
}
std::cout << (reviews.front().code ==
openpit::pretrade::RejectCode::RateLimitExceeded)
<< "\n"; // true
std::cout << (reviews.front().mode == RuleMode::ReviewWithoutHold)
<< "\n"; // true
// Confirm the second order: no mark, but the attempt still counts.
order.review.emplace().confirmed = true;
const auto confirmed = engine.StartPreTrade(order);
std::cout << std::boolalpha << confirmed.Passed() << "\n"; // true
if (!confirmed.Passed()) {
throw std::runtime_error("unexpected confirmed-order rejects");
}
std::cout << confirmed.request->Reviews().empty() << "\n"; // true
// The third order is rejected after the confirmed attempt spent a unit.
order.review->confirmed = false;
const auto third = engine.StartPreTrade(order);
std::cout << third.Passed() << "\n"; // false
if (third.Passed()) {
throw std::logic_error("expected a rate-limit reject");
}
std::cout << third.rejects.size() << "\n"; // 1
if (third.rejects.size() != 1) {
throw std::logic_error("expected one rate-limit reject");
}
std::cout << (third.rejects.front().code ==
openpit::pretrade::RejectCode::RateLimitExceeded)
<< "\n"; // true
std::cout << (third.rejects.front().mode == RuleMode::Reject)
<< "\n"; // trueRust
use std::str::FromStr;
use std::time::Duration;
use openpit::param::{AccountId, Asset, Price, Quantity, Side, TradeAmount};
use openpit::pretrade::policies::{
RateLimit, RateLimitBrokerBarrier, RateLimitPolicy, RateLimitSettings,
};
use openpit::pretrade::{RejectCode, RuleMode};
use openpit::{Engine, Instrument, OrderOperation, OrderReview, WithOrderReview};
let builder = Engine::builder::<WithOrderReview<OrderOperation>, (), ()>()
.with_order_review()
.no_sync();
let policy = RateLimitPolicy::new(
RateLimitSettings::new(
[
RateLimitBrokerBarrier {
mode: RuleMode::Reject,
limit: RateLimit {
max_orders: 3,
window: Duration::from_secs(3600),
},
},
RateLimitBrokerBarrier {
mode: RuleMode::ReviewWithoutHold,
limit: RateLimit {
max_orders: 1,
window: Duration::from_secs(3600),
},
},
],
[],
[],
[],
)?,
builder.storage_builder(),
);
let engine = builder.pre_trade(policy).build()?;
let mut order = WithOrderReview {
inner: 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("1")?),
price: Some(Price::from_str("100")?),
},
review: OrderReview::default(),
};
// The first order is accepted without review marks.
let first = engine.start_pre_trade(order.clone())?;
assert!(first.reviews().is_empty());
first.execute()?.commit();
// The second order is accepted with one review mark.
let second = engine.start_pre_trade(order.clone())?;
assert_eq!(second.reviews().len(), 1);
assert_eq!(second.reviews()[0].code, RejectCode::RateLimitExceeded);
assert_eq!(second.reviews()[0].mode, RuleMode::ReviewWithoutHold);
second.execute()?.commit();
// Confirm the second order: no mark, but the attempt still counts.
order.review.confirmed = true;
let confirmed = engine.start_pre_trade(order.clone())?;
assert!(confirmed.reviews().is_empty());
confirmed.execute()?.commit();
// The third order is rejected after the confirmed attempt spent a unit.
order.review.confirmed = false;
let rejects = engine.start_pre_trade(order).unwrap_err();
assert_eq!(rejects.len(), 1);
assert_eq!(rejects[0].code, RejectCode::RateLimitExceeded);
assert_eq!(rejects[0].mode, RuleMode::Reject);Limits the size of a single order by quantity and notional value. Prevents fat-finger errors.
To enforce one size barrier and review another for the same target, register
two named instances with independent settings. For example, use a quantity
cap of 1,000 in a Reject instance and 500 in a ReviewWithoutHold instance.
An order for 750 units produces an order-scoped review mark with the policy's
OrderQtyExceedsLimit code. An order above 1,000 units is rejected. A failed
size calculation (OrderValueCalculationFailed) remains a reject in either
instance. See Review Mode for registration.
This is a live-admission policy and is intentionally inert for drop copy. It does not recalculate a size verdict or require quantity, notional, price, or instrument fields for an order that already executed.
What it controls (by axis):
- Broker axis: global hard caps applied to every order, in addition to the asset chains.
- Asset axis: quantity caps are keyed by the instrument's underlying asset; notional caps are keyed by its settlement asset.
- Account+Asset axis: the same two keys, additionally scoped by account.
There is no per-account (without asset) axis.
Quantity and notional resolve independently. Quantity checks (account, underlying asset) first and then underlying asset; notional checks (account, settlement asset) first and then settlement asset. In either chain, a
matching barrier that omits the metric is skipped and lookup continues. The
first barrier that carries the metric supplies that asset-chain cap, so omitting
a cap never removes a cap configured farther down the chain.
The broker axis is additive, not another level of either lookup chain. Each cap on the broker barrier remains in force for every order alongside the selected asset-chain cap. An asset or account+asset barrier therefore cannot widen a cap above the broker default for one asset.
When both an asset-chain axis and the broker axis reject the same order, only
the asset-chain reject is returned; the broker breach is not reported
separately. When both selected asset-chain metrics fail, their combined reject
names the asset that supplied each cap. Every barrier of this policy - broker,
asset, and account+asset - rejects with scope = order and never blocks the
account.
Limit parameters (OrderSizeLimit):
| Field | Type | Description |
|---|---|---|
max quantity |
Quantity (optional) | maximum quantity per order |
max notional |
Volume (optional) | maximum notional value per order |
The two caps are independent and at least one must be present in every limit. A capless limit is rejected during construction and by every runtime settings setter. An absent cap constrains nothing. A cap rejects an order whose value on that metric is above it, so a cap of zero rejects every order with a positive quantity or notional and admits one of exactly zero.
Duplicate keys within an axis are rejected: an asset may appear only once on
the asset axis, and an (account, asset) pair may appear only once on the
account+asset axis. Put both caps for one key in the same barrier.
For a quantity-based trade amount, quantity is taken directly and notional is
derived as |price| * quantity. For a volume-based trade amount, notional is
taken directly and quantity is derived from the volume and |price|. Only
metrics with an applicable asset-chain or broker limit are resolved, and
price must be provided only when one of those resolutions needs conversion.
Required fields to populate:
-
Order:instrument(only when the asset or account+asset axis is configured),account id(only when the account+asset axis is configured),trade amount(only when an applicable limit exists),price(only when an applicable limit needs quantity/notional conversion) -
Execution Report: none
Rejects:
- Quantity exceeded
Code:
OrderQtyExceedsLimitReason:order quantity exceeded - Notional exceeded
Code:
OrderNotionalExceedsLimitReason:order notional exceeded - Both exceeded within the asset-chain check or within the broker-axis check
Code:
OrderExceedsLimitReason:order size exceeded - Missing
priceor failed size translation Code:OrderValueCalculationFailedReason:order value calculation failed - Missing required field
Code:
MissingRequiredField
Go
aapl, err := param.NewAsset("AAPL")
usd, err := param.NewAsset("USD")
assetMaxQty, err := param.NewQuantityFromString("100")
assetMaxNotional, err := param.NewVolumeFromString("50000")
brokerMaxQty, err := param.NewQuantityFromString("500")
brokerMaxNotional, err := param.NewVolumeFromString("100000")
// Quantity is keyed by the underlying asset, notional by the
// settlement asset; broker caps apply on top.
engine, err := openpit.NewEngineBuilder().
NoSync().
Builtin(
policies.BuildOrderSizeLimit().
AssetBarriers(
policies.OrderSizeAssetBarrier{
Asset: aapl,
Limit: policies.OrderSizeLimit{
MaxQuantity: optional.Some(assetMaxQty),
MaxNotional: optional.None[param.Volume](),
},
},
policies.OrderSizeAssetBarrier{
Asset: usd,
Limit: policies.OrderSizeLimit{
MaxQuantity: optional.None[param.Quantity](),
MaxNotional: optional.Some(assetMaxNotional),
},
},
).
BrokerBarrier(
policies.OrderSizeBrokerBarrier{
Limit: policies.OrderSizeLimit{
MaxQuantity: optional.Some(brokerMaxQty),
MaxNotional: optional.Some(brokerMaxNotional),
},
},
),
).
Build()Python
import openpit
import openpit.pretrade.policies
# Quantity is keyed by the underlying asset, notional by the
# settlement asset; broker caps apply on top.
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(
openpit.pretrade.policies.build_order_size_limit()
.asset_barriers(
openpit.pretrade.policies.OrderSizeAssetBarrier(
limit=openpit.pretrade.policies.OrderSizeLimit(
max_quantity=openpit.param.Quantity(100),
max_notional=None,
),
asset="AAPL",
),
openpit.pretrade.policies.OrderSizeAssetBarrier(
limit=openpit.pretrade.policies.OrderSizeLimit(
max_quantity=None,
max_notional=openpit.param.Volume(50000),
),
asset="USD",
),
)
.broker_barrier(
openpit.pretrade.policies.OrderSizeBrokerBarrier(
limit=openpit.pretrade.policies.OrderSizeLimit(
max_quantity=openpit.param.Quantity(500),
max_notional=openpit.param.Volume(100000),
),
),
)
)
.build()
)JavaScript
import { Engine } from "@openpit/engine";
import {
buildOrderSizeLimit,
OrderSizeAssetBarrier,
OrderSizeBrokerBarrier,
OrderSizeLimit,
} from "@openpit/engine/pretrade/policies";
// Quantities and notionals cross as decimal strings.
// Quantity is keyed by the underlying asset, notional by the
// settlement asset; broker caps apply on top.
const engine = Engine.builder()
.builtin(
buildOrderSizeLimit()
.assetBarriers([
new OrderSizeAssetBarrier(
new OrderSizeLimit("100", undefined),
"AAPL",
),
new OrderSizeAssetBarrier(
new OrderSizeLimit(undefined, "50000"),
"USD",
),
])
.brokerBarrier(
new OrderSizeBrokerBarrier(new OrderSizeLimit("500", "100000")),
),
)
.build();C++
namespace policies = openpit::pretrade::policies;
const openpit::param::Quantity assetMaxQty = openpit::param::Quantity::FromString("100");
const openpit::param::Volume assetMaxNotional = openpit::param::Volume::FromString("50000");
const openpit::param::Quantity brokerMaxQty = openpit::param::Quantity::FromString("500");
const openpit::param::Volume brokerMaxNotional = openpit::param::Volume::FromString("100000");
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
// Quantity is keyed by the underlying asset, notional by the
// settlement asset; broker caps apply on top.
builder.Add(
policies::OrderSizeLimitPolicy{}
.AssetBarrier(policies::OrderSizeAssetBarrier(
policies::OrderSizeLimit::Quantity(assetMaxQty),
openpit::param::Asset("AAPL")))
.AssetBarrier(policies::OrderSizeAssetBarrier(
policies::OrderSizeLimit::Notional(assetMaxNotional),
openpit::param::Asset("USD")))
.BrokerBarrier(policies::OrderSizeBrokerBarrier(
policies::OrderSizeLimit::Both(brokerMaxQty, brokerMaxNotional))));
const openpit::Engine engine = builder.Build();Rust
use openpit::param::{Asset, Quantity, Volume};
use openpit::pretrade::policies::{
OrderSizeAssetBarrier,
OrderSizeBrokerBarrier,
OrderSizeLimit,
OrderSizeLimitPolicy,
OrderSizeLimitSettings,
};
use openpit::storage::NoLocking;
use openpit::{
Engine, OrderOperation, WithExecutionReportOperation, WithFinancialImpact,
};
type Report = WithExecutionReportOperation<WithFinancialImpact<()>>;
let engine = Engine::builder::<OrderOperation, Report, ()>()
.no_sync()
// Quantity is keyed by the underlying asset, notional by the
// settlement asset; broker caps apply on top.
.pre_trade(OrderSizeLimitPolicy::<NoLocking>::new(
OrderSizeLimitSettings::new(
Some(OrderSizeBrokerBarrier {
limit: OrderSizeLimit {
max_quantity: Some(Quantity::from_str("500")?),
max_notional: Some(Volume::from_str("100000")?),
},
}),
[
OrderSizeAssetBarrier {
limit: OrderSizeLimit {
max_quantity: Some(Quantity::from_str("100")?),
max_notional: None,
},
asset: Asset::new("AAPL")?,
},
OrderSizeAssetBarrier {
limit: OrderSizeLimit {
max_quantity: None,
max_notional: Some(Volume::from_str("50000")?),
},
asset: Asset::new("USD")?,
},
],
[],
)?,
))
.build()?;Tracks accumulated realized P&L against configured bounds. With the default
Reject instance mode, a Reject barrier breach
rejects the order in pre-trade and latches an account block across all
settlement assets. The same breach detected during execution-report processing
also blocks the account. With a review-mode registration, the same breach
yields a pre-trade mark of the instance's mode for an unconfirmed order, with
no account block on either path. See
Account Blocking by Engine for how blocks are
recorded and cleared.
In pre-trade, a ReviewWithHold or ReviewWithoutHold breach yields a review
mark with the barrier's mode and code PnlKillSwitchTriggered for an
unconfirmed order. Review barrier breaches never block the account, including
during execution-report processing. See
Review Mode for how the engine handles review marks.
This kill switch remains active during drop copy. A barrier breach does not
reject the historical order. If drop copy succeeds, a Reject barrier breach
in a Reject instance blocks later ordinary pre-trade requests.
Fields are required only after a configured barrier is found
to apply to that account and settlement asset.
What it controls (by axis):
-
Broker barrier: P&L bounds applied to all accounts with a given settlement
asset, keyed by
(settlement asset, mode). -
Account+Asset barrier: P&L bounds for a specific account and settlement
asset pair, keyed by
(account, settlement asset, mode).
Different modes can coexist for the same settlement asset or account and asset. Duplicate keys within an axis are rejected both at construction and during runtime reconfiguration. A failed retune leaves both axes as they were.
For each mode, a broker breach takes precedence over an account+asset breach. If no barrier matches, the policy passes the order.
All modes share one P&L accumulator per (account, settlement asset). At
construction, account+asset barriers for the same pair must supply the same
initial pnl to seed that accumulator. Unequal seeds fail construction.
Runtime barrier updates carry no seed.
Barrier parameters (PnlBoundsBrokerBarrier):
| Field | Type | Required | Description |
|---|---|---|---|
settlement asset |
Asset | yes | settlement asset for P&L tracking |
mode |
RuleMode | Rust only | enforcement mode and part of the key |
lower bound |
optional P&L | no | loss limit (typically negative) |
upper bound |
optional P&L | no | profit-taking limit (typically positive) |
- Rust requires
mode: RuleMode. - Go uses
Mode, whose zero value meansReject. - In the C ABI, each barrier DTO's
modeaccepts 0 and 1 forReject, 2 forReviewWithHold, and 3 forReviewWithoutHold. Values above 3 fail the call. - In C++,
modedefaults toRuleMode::Reject. A mode cast from 0 also selectsReject. Values above 3 throwopenpit::Error. - In Python,
mode=Noneis the default and selectsRuleMode.REJECT, which is the value of themodeattribute after construction. - In JavaScript, the optional trailing constructor argument defaults to
"Reject".
For account+asset barriers and updates, Rust, Go and Python carry the mode on the nested broker barrier. C, C++ and JavaScript carry it directly on each barrier or update.
At least one bound must be set. The constructor does not validate bound signs or
the order of lower bound <= upper bound. Bounds are exclusive: equality
with a configured lower or upper bound is accepted; only values below the lower
bound or above the upper bound breach.
P&L accumulation uses the account id from the execution report (not from the
original order). Each report contributes pnl + fee to the accumulated total.
A missing required order field rejects the order. A missing required
execution-report field or P&L that cannot be computed blocks the account.
Both outcomes apply in every mode, including review modes.
Post-trade behavior:
- 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. - Combined:
pnlalready includes fees,feereturnsNoneor zero. In that case the fee is not counted twice.
- Separate:
Required fields to populate:
-
Order:instrument,account id -
Execution Report:instrument,account id,pnl,fee
Rejects and review marks:
- First detection via broker barrier
Code:
PnlKillSwitchTriggered, Scope:accountReason:pnl kill switch triggered: broker barrier - First detection via account+asset barrier
Code:
PnlKillSwitchTriggered, Scope:accountReason:pnl kill switch triggered: account + asset barrier - The following account blocks occur only in a
Rejectinstance.- Later requests after a pre-trade
Rejectbarrier breach replay the account block recorded from the triggering reject Code:AccountBlocked, Scope:accountReason and details: those of the triggering reject - Later requests after a
Rejectbarrier breach inapply execution reportreplay theAccountBlockthe policy returned Code:PnlKillSwitchTriggered, Scope:accountReason:pnl kill switch triggered
- Later requests after a pre-trade
- Missing required order field
Code:
MissingRequiredField
Go
usd, err := param.NewAsset("USD")
lowerBound, err := param.NewPnlFromString("-1000")
upperBound, err := param.NewPnlFromString("500")
engine, err := openpit.NewEngineBuilder().
NoSync().
Builtin(
policies.BuildPnlBoundsKillSwitch().
BrokerBarriers(
policies.PnlBoundsBrokerBarrier{
SettlementAsset: usd,
LowerBound: optional.Some(lowerBound),
UpperBound: optional.Some(upperBound),
},
),
).
Build()Python
import openpit
import openpit.pretrade.policies
engine = (
openpit.Engine.builder()
.no_sync()
.builtin(
openpit.pretrade.policies.build_pnl_bounds_killswitch()
.broker_barriers(
openpit.pretrade.policies.PnlBoundsBrokerBarrier(
settlement_asset=openpit.param.Asset("USD"),
lower_bound=openpit.param.Pnl(-1000),
upper_bound=openpit.param.Pnl(500),
),
)
)
.build()
)JavaScript
import { Engine } from "@openpit/engine";
import {
buildPnlBoundsKillswitch,
PnlBoundsBrokerBarrier,
} from "@openpit/engine/pretrade/policies";
// Bounds cross as signed decimal strings; at least one bound must be set.
const engine = Engine.builder()
.builtin(
buildPnlBoundsKillswitch().brokerBarriers([
new PnlBoundsBrokerBarrier("USD", "-1000", "500"),
]),
)
.build();C++
namespace policies = openpit::pretrade::policies;
policies::PnlBoundsBrokerBarrier barrier(openpit::param::Asset("USD"));
barrier.lowerBound = openpit::param::Pnl::FromString("-1000");
barrier.upperBound = openpit::param::Pnl::FromString("500");
openpit::EngineBuilder builder(openpit::SyncPolicy::None);
builder.Add(
policies::PnlBoundsKillSwitchPolicy{}.BrokerBarrier(std::move(barrier)));
const openpit::Engine engine = builder.Build();Rust
use openpit::param::{Asset, Pnl};
use openpit::pretrade::policies::{
PnlBoundsBrokerBarrier,
PnlBoundsKillSwitchPolicy,
PnlBoundsKillSwitchSettings,
};
use openpit::{
Engine, OrderOperation, WithExecutionReportOperation, WithFinancialImpact,
};
type Report = WithExecutionReportOperation<WithFinancialImpact<()>>;
let builder = Engine::builder::<OrderOperation, Report, ()>().no_sync();
let policy = PnlBoundsKillSwitchPolicy::new(
PnlBoundsKillSwitchSettings::new(
[PnlBoundsBrokerBarrier {
mode: openpit::pretrade::RuleMode::Reject,
settlement_asset: Asset::new("USD")?,
lower_bound: Some(Pnl::from_str("-1000")?),
upper_bound: Some(Pnl::from_str("500")?),
}],
[],
)?,
builder.storage_builder(),
);
let engine = builder.pre_trade(policy).build()?;Use mode: openpit::pretrade::RuleMode::ReviewWithoutHold in this barrier to
request review without a hold at the same bounds. Enable the
Rust order-review reader
with EngineBuilder::with_order_review() when using review barriers.
Two PnL kill switches. This standalone policy trusts an externally supplied realized-PnL figure and watches it on the settlement-asset axis, with a scalar fee added to the accumulated total and no FX involved.
SpotFundsPolicyoffers a second kill switch that instead computes one account-wide realized PnL from the fills it already reconciles, with a structured fee and a fail-closed FX halt. It also supports runtime unrealized and total bounds for the account and individual positions. See Spot Funds - Two Ways to Watch PnL to choose between them.
It is a stateless policy that turns every order matching a configured rule into
the verdict of its instance mode: a reject under Reject, or a review mark
under ReviewWithHold or ReviewWithoutHold. A rule belongs to one account, one
account group, or all accounts, and selects all instruments or an exact list.
The policy keeps no counters and records no mutations; the mode is set when the
instance is registered, not on the rule.
For levels, instruments, matching, runtime configuration, and per-language examples, see the dedicated Review Rules page.
What it controls:
- Matches an order by the rules of its account, its account group, and the global rule together; the most specific matching rule is named on the record
- Selects all instruments or an exact, non-empty list of instruments per rule
- Returns one
ComplianceRestrictionrecord atorderscope per instance, without blocking the account; the engine classifies it by the instance mode - see Review Mode - Accepts runtime rule changes per level without rebuilding the engine - see Dynamic Policy Reconfiguration
Required fields to populate:
-
Order:account id(only when the instance holds at least one rule),instrument(only when an applicable rule with an exact list is reached). An instance with no rules reads no order fields.
Rejects:
- Order matches a review rule
Code:
ComplianceRestriction, Scope:order - Account or instrument cannot be read from the order, in every mode
Code:
MissingRequiredField, Scope:order
Custom policy interfaces, callbacks, and language-specific examples: Policy API.
- Pre-trade Pipeline: Request and reservation semantics
- Policy API: Custom policy interfaces and examples
- Dynamic Policy Reconfiguration: Retune built-in policies at runtime without rebuilding the engine
- Domain Types: Value types used by built-in and custom policies
- Reject Codes: Standard business reject codes
- Architecture: Public integration model
- Storage: Built-in synchronization-aware key-value storage