---
title: "Review Rules"
description: "ReviewRulePolicy turns every order that matches a rule into a verdict. Rules belong to one account, one account group, or all accounts, and cover all."
---

<!-- markdownlint-disable MD013 -->
# Review Rules

`ReviewRulePolicy` turns every order that matches a rule into a verdict. Rules
belong to one account, one account group, or all accounts, and cover all
instruments or an exact list. The verdict is not part of the rule: it is the
mode of the policy instance the rule sits in - a reject, or a
[review mark](Review-Mode.md) that asks for a human decision before the order is
sent.

Use it to route a class of orders to a person, or to block it outright, without
writing a custom policy: new clients on a desk, a restricted instrument for one
account, a freeze on one instrument for everyone.

## Levels and Instruments

| Level | Covers | Key |
| --- | --- | --- |
| Account | One account | Account ID |
| Account group | Every member of an [account group](Account-Groups.md) | Group ID |
| Global | Every account | None: at most one global rule |

Each rule selects either all instruments or an exact list of instruments.
An exact list must not be empty and must not repeat an instrument; an empty
list is an error, not "all". A group or account key may appear only once per
level.

An instance may hold no rules at all. It admits every order and can be
configured later.

## The Mode Belongs to the Instance

A rule carries no mode. The registration of the policy instance sets it, as for
any policy, and every rule in that instance gets that verdict. To send one set
of orders to review and another set to a hard reject, register two instances
with distinct names, one per mode, and put each rule in the instance whose
verdict it needs. Moving a rule between modes means removing it from one
instance and adding it to the other at runtime. See
[Review Mode](Review-Mode.md#rule-modes) for the modes and the registration
options.

## Matching

- An order is matched against the account rule, the group rule of its account's
  group, and the global rule together. The levels combine as a union: an account
  rule never hides a group or global rule, and an account rule that does not
  cover the order's instrument does not hide a matching group or global rule.
- Each instance returns one record per order, naming the most specific matching
  rule: account, then group, then global. It reads the order's account when the
  instance has rules, and its instrument only when an exact list is reached.
- The record is a `ComplianceRestriction` at `order` scope. It never blocks the
  account. See [Reject Codes](Reject-Codes.md).
- Between instances the engine applies its usual precedence: an effective
  reject beats every review mark, and the review modes are combined as
  described in [Review Mode](Review-Mode.md#pre-trade-outcomes).

## Stage and What Still Runs

The policy runs in the main stage. Every other main-stage policy, including
[Spot Funds](Spot-Funds.md), still runs on the order whatever the rule decides.

- A [dry run](Non-Mutating-Dry-Run.md) gives the same rejects and review marks as
  a live run.
- [Drop copy](Review-Mode.md#dry-run-drop-copy-and-account-adjustment) is skipped:
  the order has already been executed.
- On a confirmed rerun the policy is evaluated again and the engine drops its
  review marks, so a reviewed order passes. An instance in `Reject` mode still
  rejects. See [Review Mode](Review-Mode.md#order-confirmation).
- A failure to read the order's account, or its instrument when an exact list
  needs it, is a `MissingRequiredField` reject in every mode. It is never turned
  into a review mark.

## Account Retirement

[Account retirement](Account-Retirement.md) is refused while an account rule
references the account. Remove the account rule first. Group and global rules do
not hold accounts.

## Runtime Configuration

Retune a registered instance by name with
[Dynamic Policy Reconfiguration](Dynamic-Policy-Reconfiguration.md). The instance
name defaults to `ReviewRulePolicy`. Each level is updated independently:

- not supplied keeps the level;
- a list replaces the whole level;
- an empty list clears it;
- the global rule is set or cleared.

A failed update changes nothing, and a level keeps unique keys.

| Surface | Registration | Update |
| --- | --- | --- |
| Go | `policies.BuildReviewRule()` with `GlobalRule`, `AccountGroupRules` or `AccountRules`, passed to `Builtin` | `engine.Configure().ReviewRule(name, global, groups, accounts)`. `global` is an `optional.Option[*policies.ReviewRuleGlobalRule]`: `optional.Some(&rule)` sets it, `optional.Some[*policies.ReviewRuleGlobalRule](nil)` clears it, and `optional.None` keeps it. A `nil` slice keeps its level and an empty non-nil slice clears it. |
| Python | `build_review_rule()` with `global_rule`, `account_group_rules` or `account_rules`, passed to `builtin` | `engine.configure().review_rule(name, global_rule=..., clear_global_rule=..., account_group_rules=..., account_rules=...)`. `None` keeps a level; `clear_global_rule=True` removes the global rule. |
| JavaScript | `buildReviewRule()` with `globalRule`, `accountGroupRules` or `accountRules`, passed to `builtin` | `engine.configure().reviewRule(name, { globalRule, clearGlobalRule, accountGroupRules, accountRules })`. An omitted or `null` option keeps a level; `clearGlobalRule: true` removes the global rule. An unknown option key throws `TypeError` and changes nothing. |
| C++ | `ReviewRulePolicy{}` with `GlobalRule`, `AccountGroupRule` or `AccountRule`, passed to `builder.Add` | `engine.Configure().ReviewRule(name, global, groups, accounts)`. `global` is `ReviewRuleGlobalRuleUpdate::Unchanged()`, `Clear()` or `Set(instruments)`; `std::nullopt` keeps a level. |
| Rust | `ReviewRulePolicy::new(ReviewRuleSettings::new(global, group_rules, account_rules)?)` with `pre_trade_instance` | `engine.configure().review_rule(name, \|settings\| ...)` with `set_global`, `set_account_group_rules` and `set_account_rules`. |
| C | `openpit_engine_builder_add_builtin_review_rule_policy` | `openpit_engine_configure_review_rule`, with a `has_*` flag per level. |

Go, C++, and C use a separate rule type per level; Python and JavaScript use one
`ReviewRule` whose IDs select the level, and a rule with the wrong IDs for its
level is refused.

## Errors

Invalid rules are refused when the instance is registered and when it is
reconfigured. The causes are the same everywhere: a repeated group or account
key, an empty exact list, and an instrument repeated inside a list.

| Surface | Registration | Update |
| --- | --- | --- |
| Go | The error returned by `Build()` | `*configure.Error` |
| Python | `ValueError` | `PolicyConfigureError`; `ValueError` for a rule at the wrong level or for `global_rule` together with `clear_global_rule` |
| JavaScript | `EngineBuildError` with kind `InvalidConfiguration` | `PolicyConfigureError`; `ParamError` for a rule at the wrong level or for `globalRule` together with `clearGlobalRule`; `TypeError` for an unknown option key |
| C++ | `openpit::Error` | `openpit::ConfigureError` |
| Rust | `ReviewRulePolicyError` from `ReviewRuleSettings::new` | `ConfigureError::Validation` carrying the rendered `ReviewRulePolicyError` message |
| C | `out_error` of the builder function | `OpenPitConfigureError` |

`ReviewRulePolicyError` has the variants `DuplicateAccountGroupRule`,
`DuplicateAccountRule`, `DuplicateInstrument`, and `EmptyInstruments`.

## Examples

Two instances share one engine. `new-clients-review` runs in `ReviewWithHold`
mode and holds every order of the accounts in group 7. `restricted-instruments`
runs in `Reject` mode and refuses MSFT for account 1002. A dry run shows a
review mark for a group member, a reject for the restricted pair, and a pass
for the same account on another instrument. Then the global rule of
`restricted-instruments` is set at runtime, which rejects TSLA for every
account.

### Go

<!-- Test mirror: https://github.com/openpitkit/pit/blob/main/bindings/go/examples_wiki_test.go -->

```go
package main

import (
 "log"

 "go.openpit.dev/openpit"
 "go.openpit.dev/openpit/model"
 "go.openpit.dev/openpit/param"
 "go.openpit.dev/openpit/pkg/optional"
 "go.openpit.dev/openpit/pretrade/policies"
 "go.openpit.dev/openpit/reject"
)

func main() {
 group, err := param.NewAccountGroupIDFromUint32(7)
 if err != nil {
  log.Fatal(err)
 }
 newClient := param.NewAccountIDFromUint64(1001)
 restricted := param.NewAccountIDFromUint64(1002)
 usd, err := param.NewAsset("USD")
 if err != nil {
  log.Fatal(err)
 }
 newInstrument := func(base string) param.Instrument {
  asset, err := param.NewAsset(base)
  if err != nil {
   log.Fatal(err)
  }
  return param.NewInstrument(asset, usd)
 }
 aapl := newInstrument("AAPL")
 msft := newInstrument("MSFT")
 tsla := newInstrument("TSLA")

 engine, err := openpit.NewEngineBuilder().NoSync().
  Builtin(
   policies.BuildReviewRule().AccountGroupRules(policies.ReviewRuleAccountGroupRule{
    AccountGroupID: group,
    Instruments:    policies.ReviewRuleAllInstruments(),
   }),
   openpit.InstanceName("new-clients-review"),
   openpit.InstanceMode(reject.RuleModeReviewWithHold),
  ).
  Builtin(
   policies.BuildReviewRule().AccountRules(policies.ReviewRuleAccountRule{
    AccountID:   restricted,
    Instruments: policies.ReviewRuleExactInstruments(msft),
   }),
   openpit.InstanceName("restricted-instruments"),
   openpit.InstanceMode(reject.RuleModeReject),
  ).
  Build()
 if err != nil {
  log.Fatal(err)
 }
 defer engine.Stop()
 if err := engine.Accounts().RegisterGroup([]param.AccountID{newClient}, group); err != nil {
  log.Fatal(err)
 }

 run := func(account param.AccountID, instrument param.Instrument) ([]reject.Reject, []reject.Reject) {
  order := model.NewOrder()
  op := order.EnsureOperationView()
  op.SetAccountID(account)
  op.SetInstrument(instrument)
  op.SetSide(param.SideBuy)
  quantity, err := param.NewQuantityFromString("10")
  if err != nil {
   log.Fatal(err)
  }
  op.SetTradeAmount(param.NewQuantityTradeAmount(quantity))
  price, err := param.NewPriceFromString("25")
  if err != nil {
   log.Fatal(err)
  }
  op.SetPrice(price)
  report, err := engine.ExecutePreTradeDryRun(order)
  if err != nil {
   log.Fatal(err)
  }
  defer report.Close()
  rejects, err := report.Rejects()
  if err != nil {
   log.Fatal(err)
  }
  reviews, err := report.Reviews()
  if err != nil {
   log.Fatal(err)
  }
  return rejects, reviews
 }
 rejects, reviews := run(newClient, aapl)
 if len(rejects) != 0 || len(reviews) != 1 || reviews[0].Mode != reject.RuleModeReviewWithHold {
  log.Fatalf("new client: rejects = %v, reviews = %v", rejects, reviews)
 }
 checkRejected := func(account param.AccountID, instrument param.Instrument) {
  rejects, reviews := run(account, instrument)
  if len(rejects) != 1 || rejects[0].Code != reject.CodeComplianceRestriction || len(reviews) != 0 {
   log.Fatalf("restricted order: rejects = %v, reviews = %v", rejects, reviews)
  }
 }
 checkRejected(restricted, msft)
 if rejects, reviews := run(restricted, aapl); len(rejects) != 0 || len(reviews) != 0 {
  log.Fatalf("unrestricted order: rejects = %v, reviews = %v", rejects, reviews)
 }

 if err := engine.Configure().ReviewRule("restricted-instruments",
  optional.Some(&policies.ReviewRuleGlobalRule{Instruments: policies.ReviewRuleExactInstruments(tsla)}),
  nil, nil); err != nil {
  log.Fatal(err)
 }
 checkRejected(param.NewAccountIDFromUint64(1003), tsla)
 checkRejected(restricted, msft)
}
```

### Python

<!-- Test mirror: https://github.com/openpitkit/pit/blob/main/bindings/python/tests/integration/test_examples_wiki.py -->

```python
import openpit
from openpit.pretrade.policies import ReviewRule, build_review_rule

group = openpit.param.AccountGroupId.from_int(7)
new_client = openpit.param.AccountId.from_int(1001)
restricted = openpit.param.AccountId.from_int(1002)
aapl = openpit.Instrument("AAPL", "USD")
msft = openpit.Instrument("MSFT", "USD")
tsla = openpit.Instrument("TSLA", "USD")
engine = (
    openpit.Engine.builder()
    .no_sync()
    .builtin(
        build_review_rule().account_group_rules(ReviewRule(account_group_id=group)),
        name="new-clients-review",
        mode=openpit.pretrade.RuleMode.REVIEW_WITH_HOLD,
    )
    .builtin(
        build_review_rule().account_rules(
            ReviewRule(account_id=restricted, instruments=[msft])
        ),
        name="restricted-instruments",
        mode=openpit.pretrade.RuleMode.REJECT,
    )
    .build()
)
engine.accounts().register_group([new_client], group)


def run(account: openpit.param.AccountId, instrument: openpit.Instrument):
    return engine.execute_pre_trade_dry_run(
        openpit.Order(
            operation=openpit.OrderOperation(
                account_id=account,
                instrument=instrument,
                side=openpit.param.Side.BUY,
                trade_amount=openpit.param.TradeAmount.quantity("10"),
                price=openpit.param.Price("25"),
            )
        )
    )


review = run(new_client, aapl)
assert review.is_pass
assert not review.rejects
assert [mark.mode for mark in review.reviews] == [
    openpit.pretrade.RuleMode.REVIEW_WITH_HOLD
]


def check_rejected(account: openpit.param.AccountId, instrument: openpit.Instrument):
    result = run(account, instrument)
    assert result.rejects
    assert [reject.code for reject in result.rejects] == [
        openpit.pretrade.RejectCode.COMPLIANCE_RESTRICTION
    ]
    assert not result.reviews


check_rejected(restricted, msft)
passed = run(restricted, aapl)
assert passed.is_pass and not passed.rejects and not passed.reviews

engine.configure().review_rule(
    "restricted-instruments", global_rule=ReviewRule(instruments=[tsla])
)
check_rejected(openpit.param.AccountId.from_int(1003), tsla)
check_rejected(restricted, msft)
```

### JavaScript

<!-- Test mirror: https://github.com/openpitkit/pit/blob/main/bindings/js/tests/examples_wiki.test.ts -->

```ts
import { Engine } from "@openpit/engine";
import { Instrument, TradeAmount } from "@openpit/engine/param";
import {
  buildReviewRule,
  ReviewRule,
} from "@openpit/engine/pretrade/policies";
import { RuleMode } from "@openpit/engine/reject";

const aapl = new Instrument("AAPL", "USD");
const msft = new Instrument("MSFT", "USD");
const tsla = new Instrument("TSLA", "USD");
const builder = Engine.builder().builtin(
  buildReviewRule().accountGroupRules([new ReviewRule({ accountGroupId: 7 })]),
  { name: "new-clients-review", mode: RuleMode.ReviewWithHold },
);
builder.builtin(
  buildReviewRule().accountRules([
    new ReviewRule({ accountId: 1002, instruments: [msft] }),
  ]),
  { name: "restricted-instruments", mode: RuleMode.Reject },
);
const engine = builder.build();
engine.accounts().registerGroup([1001], 7);

const run = (accountId: number, instrument: Instrument) =>
  engine.executePreTradeDryRun({
    operation: {
      accountId,
      underlyingAsset: instrument.underlyingAsset,
      settlementAsset: instrument.settlementAsset,
      side: "BUY",
      tradeAmount: TradeAmount.quantity("10"),
      price: "25",
    },
  });

// A group member: no rejects and one ReviewWithHold mark.
const review = run(1001, aapl);
console.log(review.isPass, review.rejects.length, review.reviews[0]?.mode);

// A restricted pair: one ComplianceRestriction reject and no marks.
const checkRejected = (accountId: number, instrument: Instrument) => {
  const result = run(accountId, instrument);
  console.log(result.rejects.map((reject) => reject.code), result.reviews.length);
};
checkRejected(1002, msft);
// The same account on another instrument passes with no marks.
const passed = run(1002, aapl);
console.log(passed.isPass, passed.rejects.length, passed.reviews.length);

engine.configure().reviewRule("restricted-instruments", {
  globalRule: new ReviewRule({ instruments: [tsla] }),
});
checkRejected(1003, tsla);
checkRejected(1002, msft);
```

### C++

<!-- Test mirror: https://github.com/openpitkit/pit/blob/main/bindings/cpp/test/wiki/review_rules_test.cpp -->

```cpp
#include <openpit/openpit.hpp>

#include <cassert>
#include <stdexcept>

int main() {
  using namespace openpit;
  using namespace openpit::pretrade::policies;
  using openpit::reject::RejectCode;
  using openpit::reject::RuleMode;

  const auto group = param::AccountGroupId::FromUint32(7);
  const auto newClient = param::AccountId::FromUint64(1001);
  const auto restricted = param::AccountId::FromUint64(1002);
  const auto instrument = [](const char* symbol) {
    return model::Instrument(param::Asset(symbol), param::Asset("USD"));
  };
  const auto aapl = instrument("AAPL");
  const auto msft = instrument("MSFT");
  const auto tsla = instrument("TSLA");

  EngineBuilder builder(SyncPolicy::None);
  builder.Add(ReviewRulePolicy{}.AccountGroupRule(
                  {group, ReviewRuleInstruments::All()}),
              {"new-clients-review", RuleMode::ReviewWithHold});
  builder.Add(ReviewRulePolicy{}.AccountRule(
                  {restricted, ReviewRuleInstruments::Exact({msft})}),
              {"restricted-instruments", RuleMode::Reject});
  const auto engine = builder.Build();
  if (auto error = engine.Accounts().RegisterGroup({newClient}, group)) {
    throw std::runtime_error(error->message);
  }

  const auto run = [&](param::AccountId account,
                       const model::Instrument& symbol) {
    model::Order order;
    auto& operation = order.operation.emplace();
    operation.accountId = account;
    operation.instrument = symbol;
    operation.side = model::Side::Buy;
    operation.tradeAmount =
        model::TradeAmount::OfQuantity(param::Quantity::FromString("10"));
    operation.price = param::Price::FromString("25");
    return engine.ExecutePreTradeDryRun(order);
  };
  auto review = run(newClient, aapl);
  assert(review.Passed());
  assert(review.Rejects().empty());
  const auto marks = review.Reviews();
  assert(marks.size() == 1u);
  assert(marks.front().mode == RuleMode::ReviewWithHold);

  const auto checkRejected = [&](param::AccountId account,
                                 const model::Instrument& symbol) {
    auto result = run(account, symbol);
    assert(!result.Passed());
    assert(result.Rejects().size() == 1u);
    assert(result.Rejects().front().code == RejectCode::ComplianceRestriction);
    assert(result.Reviews().empty());
  };
  checkRejected(restricted, msft);
  auto pass = run(restricted, aapl);
  assert(pass.Passed());
  assert(pass.Rejects().empty());
  assert(pass.Reviews().empty());

  engine.Configure().ReviewRule(
      "restricted-instruments",
      ReviewRuleGlobalRuleUpdate::Set(ReviewRuleInstruments::Exact({tsla})));
  checkRejected(param::AccountId::FromUint64(1003), tsla);
  checkRejected(restricted, msft);
}
```

### Rust

<!-- Test mirror: https://github.com/openpitkit/pit/blob/main/crates/openpit/tests/examples_wiki.rs -->

A review mode needs the order-review reader: call `with_order_review()` on the
builder, as in
[Review Mode](Review-Mode.md#enabling-the-order-review-reader-in-rust).

```rust
use openpit::param::{AccountGroupId, AccountId, Asset, Price, Quantity, Side, TradeAmount};
use openpit::pretrade::policies::{
    ReviewRuleAccountGroupRule, ReviewRuleAccountRule, ReviewRuleInstruments, ReviewRulePolicy,
    ReviewRuleSettings,
};
use openpit::pretrade::{RejectCode, RuleMode};
use openpit::{Engine, Instrument, OrderOperation, OrderReview, PolicyInstance, WithOrderReview};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let group = AccountGroupId::from_u32(7)?;
    let new_client = AccountId::from_u64(1001);
    let restricted = AccountId::from_u64(1002);
    let usd = Asset::new("USD")?;
    let aapl = Instrument::new(Asset::new("AAPL")?, usd.clone());
    let msft = Instrument::new(Asset::new("MSFT")?, usd.clone());
    let tsla = Instrument::new(Asset::new("TSLA")?, usd);
    let client_rules = ReviewRuleSettings::new(
        None,
        [ReviewRuleAccountGroupRule {
            account_group_id: group,
            instruments: ReviewRuleInstruments::All,
        }],
        [],
    )?;
    let instrument_rules = ReviewRuleSettings::new(
        None,
        [],
        [ReviewRuleAccountRule {
            account_id: restricted,
            instruments: ReviewRuleInstruments::Exact(vec![msft.clone()]),
        }],
    )?;

    let engine = Engine::builder::<WithOrderReview<OrderOperation>, (), ()>()
        .with_order_review()
        .no_sync()
        .pre_trade_instance(
            ReviewRulePolicy::new(client_rules),
            PolicyInstance {
                name: Some("new-clients-review".to_owned()),
                mode: RuleMode::ReviewWithHold,
            },
        )
        .pre_trade_instance(
            ReviewRulePolicy::new(instrument_rules),
            PolicyInstance {
                name: Some("restricted-instruments".to_owned()),
                mode: RuleMode::Reject,
            },
        )
        .build()?;
    engine.accounts().register_group(&[new_client], group)?;

    let quantity = Quantity::from_str("10")?;
    let price = Price::from_str("25")?;
    let run = |account_id, instrument| {
        engine.execute_pre_trade_dry_run(WithOrderReview {
            inner: OrderOperation {
                account_id,
                instrument,
                side: Side::Buy,
                trade_amount: TradeAmount::Quantity(quantity),
                price: Some(price),
            },
            review: OrderReview {
                confirmed: false,
                already_held: false,
            },
        })
    };
    let review = run(new_client, aapl.clone());
    assert!(review.is_pass());
    assert_eq!(review.reviews().len(), 1);
    assert_eq!(review.reviews()[0].mode, RuleMode::ReviewWithHold);

    let check_rejected = |account, instrument| {
        let result = run(account, instrument);
        let rejects = result.rejects().expect("order must be rejected");
        assert_eq!(rejects.len(), 1);
        assert_eq!(rejects[0].code, RejectCode::ComplianceRestriction);
        assert!(result.reviews().is_empty());
    };
    check_rejected(restricted, msft.clone());
    let pass = run(restricted, aapl);
    assert!(pass.is_pass());
    assert!(pass.reviews().is_empty());

    engine
        .configure()
        .review_rule("restricted-instruments", |settings| {
            settings.set_global(Some(ReviewRuleInstruments::Exact(vec![tsla.clone()])))
        })?;
    check_rejected(AccountId::from_u64(1003), tsla);
    check_rejected(restricted, msft);
    Ok(())
}
```

## Related Pages

- [Review Mode](Review-Mode.md): Review marks, confirmation, and the instance modes
- [Policies](Policies.md#reviewrulepolicy): The policy among the built-ins
- [Dynamic Policy Reconfiguration](Dynamic-Policy-Reconfiguration.md): Retune
  rules at runtime
- [Account Groups](Account-Groups.md): Group membership that group rules use
- [Account Retirement](Account-Retirement.md): Retiring an account that has rules
- [Reject Codes](Reject-Codes.md): `ComplianceRestriction` and the other codes
