Skip to content

Review Mode

Eugene Palchukovsky edited this page Nov 24, 2026 · 5 revisions

Review Mode

A review mark is a policy result that requires a human decision before the caller sends the order. Register a policy instance in a review mode to turn its ordinary rejects into review marks. The policy can use the same code, settings, and keys in any mode. For a stateless check with a hard cap and a separate review threshold on the same target, register two instances. Each instance has its own settings and policy state.

A stateless policy whose instance mode alone decides the verdict is Review Rules: it matches orders by account, group, or instrument and returns that instance's verdict.

A policy that counts attempts, such as RateLimit, uses one instance with a mode per threshold. Reject and review thresholds on the same target keep separate counters within that instance.

A policy that keeps its own state - Spot Funds, the rate limit, the P&L bounds kill switch, or a custom policy that holds funds or counts - is registered in Reject mode; a custom one that needs review sets a review mode on the reject records it returns, as described below.

Registered in a review mode, the changes it records as main-stage mutations for an order it marks in pre-trade are rolled back, also after the reviewer confirms that order; changes it makes at once, such as rate-limit counters, stay. For Spot Funds this means nothing is held, no lock price is recorded, balances and positions are not updated, and a later fill or cancel of that order can block the account for a missing lock price.

The rejects and account blocks it returns become marks or are dropped unless their code is an evaluation failure, so a P&L kill switch registered this way does not block the account on a fill; a block it writes directly through the account control and a block from an accepted account adjustment latch in any mode.

Rule Modes

Reject is the default instance mode. Every instance has a unique name that defaults to the policy name. Use the instance name for runtime reconfiguration. Rejects and marks retain the policy's own name.

Binding Reject Review with hold Review without hold
Go reject.RuleModeReject reject.RuleModeReviewWithHold reject.RuleModeReviewWithoutHold
Python RuleMode.REJECT RuleMode.REVIEW_WITH_HOLD RuleMode.REVIEW_WITHOUT_HOLD
JavaScript RuleMode.Reject RuleMode.ReviewWithHold RuleMode.ReviewWithoutHold
C++ RuleMode::Reject RuleMode::ReviewWithHold RuleMode::ReviewWithoutHold
Rust RuleMode::Reject RuleMode::ReviewWithHold RuleMode::ReviewWithoutHold
C OPENPIT_PRETRADE_RULE_MODE_REJECT OPENPIT_PRETRADE_RULE_MODE_REVIEW_WITH_HOLD OPENPIT_PRETRADE_RULE_MODE_REVIEW_WITHOUT_HOLD

Python and JavaScript use the case-sensitive string values Reject, ReviewWithHold, and ReviewWithoutHold.

Surface Registration with a name and mode
Go PreTrade(policy, openpit.InstanceName(name), openpit.InstanceMode(mode)), one policy per call. An empty name uses the policy name. An invalid mode is reported by Build().
Python pre_trade(policy, name=None, mode=None) or builtin(policy, name=None, mode=None) with keyword arguments. An invalid mode string raises ValueError.
JavaScript preTrade(policy, { name, mode }) or builtin(policy, { name, mode }) with optional final options. An invalid mode raises EngineBuildError with kind InvalidConfiguration during registration.
C++ builder.Add(policy, openpit::PolicyInstance{name, mode}) with an optional final argument. An empty name uses the policy name. A mode cast to 0 selects Reject. A mode above 3 raises openpit::Error during registration.
Rust pre_trade_instance(policy, PolicyInstance { name, mode }). Use pre_trade(policy) for the default name and mode.
C ABI Pass const OpenPitPolicyInstance *instance to any of the seven openpit_engine_builder_add_* functions. A null instance or mode 0 selects Reject. A null or empty name uses the policy name. A mode above 3 reports an error through out_error.

A custom policy can also set an explicit review mode on a returned reject record. The record mode is optional on every surface and defaults to Reject. This lets a stateful custom policy compare review and reject thresholds using one set of counters or balances. See Policy API for the record constructors.

Instance mode Record mode Effective outcome
Reject Reject Reject
Review Reject Mark in the instance's review mode
Any Explicit review mode Mark in the record's review mode

An evaluation failure always remains a reject and is reported with mode Reject.

Pre-trade Outcomes

  • Any effective reject takes precedence over every review mark. The run returns rejects alone, discards even earlier start-stage marks, and produces no reservation.
  • Marks alone return a reservation. A policy instance registered in a review mode that marks the order in its main-stage check has its own mutations rolled back and its policy result discarded. A start-stage mark alone triggers no per-instance rollback. A Reject-mode instance that returns only explicit review marks keeps its contributions under the same reservation rules as a successful instance.
  • If every mark is ReviewWithHold, the reservation keeps the remaining holds and policy results, including their lock prices and account adjustments. Any ReviewWithoutHold mark makes the engine roll back the run and return a reservation with none of those effects. A rollback failure is reported as a SystemUnavailable reject.
  • A start-stage ReviewWithoutHold mark skips the main stage after the execute-time account-block check. The reservation carries marks from the stages that ran.
  • A review mark never sets an account block, including during pre-trade, execution-report handling, and runtime configuration. Evaluation failures retain their usual blocking behavior.

Reading the Result

Read the execute result before deciding whether to send. The start result and request expose only start-stage marks. The execute result and reservation expose marks from the stages that ran.

Binding Start result Request Execute result Reservation Dry-run report
Go Returned request Reviews() Returned reservation Reviews() Reviews()
Python reviews reviews reviews reviews reviews
JavaScript reviews reviews() reviews reviews() reviews
C++ request->Reviews() Reviews() reservation->Reviews() Reviews() Reviews()
Rust Ok(request) reviews() Ok(reservation) reviews() reviews()
C Returned request handle openpit_pretrade_pre_trade_request_get_reviews Returned reservation handle openpit_pretrade_pre_trade_reservation_get_reviews openpit_pretrade_pre_trade_dry_run_report_get_reviews

A passing verdict means the evaluated stages found no effective rejects. Live calls indicate this with a returned handle in Go, ok in Python and JavaScript, Passed() in C++, Result::is_ok() in Rust, and OpenPitPretradeStatus_Passed in C. Dry-run reports use IsPass() in Go, is_pass in Python, isPass in JavaScript, Passed() in C++, is_pass() in Rust, and openpit_pretrade_pre_trade_dry_run_report_is_pass in C.

If the live execute result contains any marks, commit its reservation immediately and leave the order unsent for a human decision. Use this one branch for both modes. The commit retains any holds still in the reservation. Committing a reservation with no holds or policy results is harmless. After approval, run the same order through pre-trade from the start with confirmed set, adding already_held only if Spot Funds kept its own hold in the committed review. Send only after a run passes and returns an empty review list. See Review With Hold for the lock and release steps.

Order Confirmation

The engine reads confirmed and already_held from the optional OrderReview group. Both flags are false when the group is absent. On a confirmed run, every registered instance still runs and the engine drops all review marks. Effective rejects, including evaluation failures, still apply. A review-mode instance that marks the order in its main-stage check still loses its own contributions. A start-stage mark cannot skip the main stage on a confirmed order.

already_held carries the caller's assertion that Spot Funds already holds this order's funds from an earlier committed review. The engine passes the flag to policies through the pre-trade context without verifying the hold. Register a custom policy that holds funds and reads this flag in Reject mode. A review-mode instance that marks the order in its main-stage check keeps no hold of its own, and the shared flag cannot describe which policies kept theirs.

  • Go uses order.EnsureReviewView(), then review.SetConfirmed(true) and, if applicable, review.SetAlreadyHeld(true).
  • Python uses openpit.OrderReview(confirmed=True, already_held=...).
  • JavaScript uses OrderReview or an object with confirmed and alreadyHeld boolean fields.
  • C++ uses openpit::model::OrderReview with std::optional<bool> fields confirmed and alreadyHeld.
  • Rust uses OrderReview { confirmed, already_held } in WithOrderReview<T>.
  • C uses the OpenPitTriBool fields confirmed and already_held in OpenPitOrderReview. OPENPIT_TRI_BOOL_NOT_SET means false for either flag.

Enabling the Order-Review Reader in Rust

Call EngineBuilder::with_order_review() on the builder before choosing the sync mode. The order type must implement HasConfirmed and HasAlreadyHeld. A review-mode instance requires this reader, so building without it returns EngineBuildError::OrderReviewRequired.

Without the reader, a live or dry-run stage that would otherwise return marks alone returns an order-scoped MissingRequiredField reject from Engine with reason order review flags unavailable. This can happen when a reject-mode instance sets a review mode on a reject record. Drop copy is exempt.

Review With Hold

When the live result contains review marks, save the reservation's lock, commit the reservation immediately, and keep the order unsent. The commit keeps only the contributions left after the pre-trade outcome rules. See Pre-Trade Lock for how to persist a lock.

On approval, rerun the order from the start with confirmed set. Set already_held too only if Spot Funds kept its own hold in the committed review: every mark was with-hold and no Spot Funds instance registered in a review mode marked the order. If any mark was without-hold or a Spot Funds review-mode instance marked the order, rerun with confirmed alone. The engine trusts the flag. Setting it when Spot Funds kept no hold leaves the order without a Spot Funds hold.

With already_held set, Spot Funds checks the current balance with this order's own hold temporarily given back. It adds no hold, account adjustment, rollback, or lock price to the rerun.

Keep a passing rerun's reservation open until the venue accepts the order, then commit it. For every execution report after committing an already-held rerun, use the rerun's lock supplemented with each Spot Funds group's prices from the first lock. Merging the whole first lock duplicates prices for groups recorded in both runs. If Spot Funds is the only policy that locks prices, use the first lock directly. Using only the rerun's lock blocks the account with MissingRequiredField. See Account Blocking.

Binding Read the group's prices from the first lock Append them to the rerun's lock
Go Lock.PricesOf Lock.PushMany with grouped Entry values
Python Lock.prices_of Lock.push_many
JavaScript Lock.pricesOf Lock.pushMany
C++ PreTradeLock::PricesOf PreTradeLock::PushMany with grouped LockEntry values
Rust PreTradeLock::prices_of PreTradeLock::push_many
C openpit_pretrade_pre_trade_lock_prices_of openpit_pretrade_pre_trade_lock_push_many with grouped OpenPitPretradePreTradeLockEntry values

If Spot Funds kept a hold and the order ends without a committed rerun, send a final cancel execution report carrying the remaining reserved quantity and the first run's lock. This releases the hold when the reviewer declines the order, the rerun rejects it, or you roll back the rerun because the order was never sent or the venue did not accept it. Rejecting or rolling back the rerun leaves the original hold in place.

A without-hold review needs no cancel report because it holds nothing. A Spot Funds review-mode instance that marked the order also holds nothing. A final cancel report carrying the first run's lock and a remaining reserved quantity blocks the account with MissingRequiredField in that case because the lock has no price for that instance.

Dry Run, Drop Copy, and Account Adjustment

A dry run reports marks with the same precedence and stage rules as a live run. Drop copy keeps policy mutations and results accompanying marks in either review mode, suppresses the marks themselves, and aborts on evaluation failures. Account adjustment ignores both modes. Any entry rejects the batch, and every entry in the failed batch is reported with mode Reject.

After its required fields are read, every live rate-limit start spends one unit on every applicable threshold, in every mode. A confirmed rerun starts again and spends another unit. Execute does not charge it a second time. A dry run spends no units.

Examples

Each custom policy returns an ordinary main-stage reject requiring approval. The engine registers it in ReviewWithoutHold mode. The caller finalizes the empty reservation and leaves the order unsent. After approval, the engine runs the same policy again and discards its mark, so the caller can send the order.

Go

package main

import (
 "fmt"
 "log"

 "go.openpit.dev/openpit"
 "go.openpit.dev/openpit/accountadjustment"
 "go.openpit.dev/openpit/model"
 "go.openpit.dev/openpit/param"
 "go.openpit.dev/openpit/pretrade"
 "go.openpit.dev/openpit/reject"
 "go.openpit.dev/openpit/tx"
)

type ApprovalPolicy struct{}

func (*ApprovalPolicy) Close() {}

func (*ApprovalPolicy) Name() string { return "ApprovalPolicy" }

func (*ApprovalPolicy) PolicyGroupID() model.PolicyGroupID {
 return model.DefaultPolicyGroupID
}

func (*ApprovalPolicy) CheckPreTradeStart(pretrade.Context, model.Order) []reject.Reject {
 return nil
}

func (p *ApprovalPolicy) PerformPreTradeCheck(
 _ pretrade.Context,
 _ model.Order,
 _ tx.Mutations,
 _ pretrade.Result,
) []reject.Reject {
 return reject.NewSingleItemList(
  reject.CodeComplianceRestriction,
  p.Name(),
  "approval required",
  "obtain a human decision before sending",
  reject.ScopeOrder,
 )
}

func (*ApprovalPolicy) ApplyExecutionReport(
 pretrade.PostTradeContext,
 model.ExecutionReport,
 pretrade.PostTradeAdjustments,
 pretrade.PostTradePnls,
) []reject.AccountBlock {
 return nil
}

func (*ApprovalPolicy) ApplyAccountAdjustment(
 accountadjustment.Context,
 param.AccountID,
 model.AccountAdjustment,
 tx.Mutations,
 pretrade.AccountOutcomes,
) (pretrade.PolicyAccountAdjustmentResult, []reject.Reject) {
 return pretrade.PolicyAccountAdjustmentResult{}, nil
}

func runReviewExample() error {
 policy := &ApprovalPolicy{}
 engine, err := openpit.NewEngineBuilder().FullSync().
  PreTrade(
   policy,
   openpit.InstanceName("approval"),
   openpit.InstanceMode(reject.RuleModeReviewWithoutHold),
  ).
  Build()
 if err != nil {
  return err
 }
 defer engine.Stop()

 aapl, err := param.NewAsset("AAPL")
 if err != nil {
  return err
 }
 usd, err := param.NewAsset("USD")
 if err != nil {
  return err
 }
 quantity, err := param.NewQuantityFromString("10")
 if err != nil {
  return err
 }
 price, err := param.NewPriceFromString("25")
 if err != nil {
  return err
 }
 order := model.NewOrder()
 operation := order.EnsureOperationView()
 operation.SetInstrument(param.NewInstrument(aapl, usd))
 operation.SetAccountID(param.NewAccountIDFromUint64(99224416))
 operation.SetSide(param.SideBuy)
 operation.SetTradeAmount(param.NewQuantityTradeAmount(quantity))
 operation.SetPrice(price)

 sent := 0
 run := func(order model.Order) ([]reject.Reject, error) {
  reservation, rejects, err := engine.ExecutePreTrade(order)
  if err != nil {
   return nil, err
  }
  if len(rejects) != 0 {
   return nil, fmt.Errorf("order rejected: %v", rejects)
  }
  defer reservation.Close()
  reviews, err := reservation.Reviews()
  if err != nil {
   return nil, err
  }
  if len(reviews) != 0 {
   reservation.CommitAndClose()
   return reviews, nil
  }

  // Stand-in for a successful venue send.
  sent++
  reservation.CommitAndClose()
  return nil, nil
 }

 reviews, err := run(order)
 if err != nil {
  return err
 }
 if len(reviews) != 1 || reviews[0].Mode != reject.RuleModeReviewWithoutHold {
  return fmt.Errorf("expected one review mark without hold, got %v", reviews)
 }
 if sent != 0 {
  return fmt.Errorf("expected an unsent order")
 }

 // A human approved the same order.
 review := order.EnsureReviewView()
 review.SetConfirmed(true)
 reviews, err = run(order)
 if err != nil {
  return err
 }
 if len(reviews) != 0 || sent != 1 {
  return fmt.Errorf("expected the confirmed order to pass and be sent once")
 }
 return nil
}

func main() {
 if err := runReviewExample(); err != nil {
  log.Fatal(err)
 }
}

Python

import openpit


class ApprovalPolicy(openpit.pretrade.Policy):
    @property
    def name(self) -> str:
        return "ApprovalPolicy"

    def perform_pre_trade_check(
        self, _ctx: openpit.pretrade.Context, _order: openpit.Order
    ) -> openpit.pretrade.PolicyPreTradeResult:
        return openpit.pretrade.PolicyPreTradeResult.reject(
            rejects=[
                openpit.pretrade.PolicyReject(
                    code=openpit.pretrade.RejectCode.COMPLIANCE_RESTRICTION,
                    reason="approval required",
                    details="obtain a human decision before sending",
                )
            ],
        )


policy = ApprovalPolicy()
engine = (
    openpit.Engine.builder()
    .no_sync()
    .pre_trade(
        policy=policy,
        name="approval",
        mode=openpit.pretrade.RuleMode.REVIEW_WITHOUT_HOLD,
    )
    .build()
)
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("10"),
    price=openpit.param.Price("25"),
)
sent_orders: list[openpit.Order] = []


def run(order: openpit.Order) -> list[openpit.pretrade.Reject]:
    result = engine.execute_pre_trade(order=order)
    reservation = result.reservation
    if not result.ok or reservation is None:
        raise RuntimeError(f"order rejected: {result.rejects}")
    reviews = result.reviews
    if reviews:
        reservation.commit()
        return reviews

    # Stand-in for a successful venue send.
    sent_orders.append(order)
    reservation.commit()
    return reviews


reviews = run(openpit.Order(operation=operation))
assert [review.mode for review in reviews] == [
    openpit.pretrade.RuleMode.REVIEW_WITHOUT_HOLD
]
assert not sent_orders

# A human approved the same order.
confirmed_order = openpit.Order(
    operation=operation, review=openpit.OrderReview(confirmed=True)
)
confirmed_reviews = run(confirmed_order)
assert not confirmed_reviews
assert len(sent_orders) == 1

JavaScript

import { Engine } from "@openpit/engine";
import { Order } from "@openpit/engine/model";
import { TradeAmount } from "@openpit/engine/param";
import { type Policy } from "@openpit/engine/pretrade";
import { RuleMode } from "@openpit/engine/reject";

const state = { sent: 0 };
const policy: Policy = {
  name: "ApprovalPolicy",
  checkPreTradeStart: () => [],
  performPreTradeCheck() {
    return {
      rejects: [
        {
          code: "ComplianceRestriction",
          reason: "approval required",
          details: "obtain a human decision before sending",
        },
      ],
    };
  },
};

const engine = Engine.builder()
  .preTrade(policy, { name: "approval", mode: RuleMode.ReviewWithoutHold })
  .build();
const order = new Order();
order.operation = {
  underlyingAsset: "AAPL",
  settlementAsset: "USD",
  accountId: 99_224_416n,
  side: "BUY",
  tradeAmount: TradeAmount.quantity("10"),
  price: "25",
};

function run(order: Order) {
  const result = engine.executePreTrade(order);
  const reservation = result.reservation;
  if (!result.ok || !reservation) {
    throw new Error(`order rejected: ${result.rejects[0]?.reason}`);
  }
  const reviews = result.reviews;
  if (reviews.length > 0) {
    reservation.commit();
    return reviews;
  }

  // Stand-in for a successful venue send.
  state.sent++;
  reservation.commit();
  return reviews;
}

const reviews = run(order);
if (reviews.length !== 1 || reviews[0]?.mode !== RuleMode.ReviewWithoutHold) {
  throw new Error("expected one review mark without hold");
}
const sentBeforeApproval = state.sent;
if (sentBeforeApproval !== 0) {
  throw new Error("expected an unsent order");
}

// A human approved the same order.
const confirmedOrder = order.clone();
confirmedOrder.review = { confirmed: true };
if (run(confirmedOrder).length !== 0 || state.sent !== 1) {
  throw new Error("expected the confirmed order to pass and be sent once");
}

C++

#include <openpit/openpit.hpp>
#include <openpit/pretrade/adapters.hpp>

#include <stdexcept>
#include <string_view>

struct ApprovalPolicy {
  [[nodiscard]] std::string_view Name() const { return "ApprovalPolicy"; }

  void PerformPreTradeCheck(
      const openpit::model::Order&, const openpit::pretrade::Context&,
      openpit::tx::Mutations&, openpit::pretrade::Result&,
      openpit::pretrade::PolicyDecision& decision) const {
    const openpit::pretrade::Reject entry(
        "ApprovalPolicy", openpit::pretrade::RejectScope::Order,
        openpit::pretrade::RejectCode::ComplianceRestriction,
        "approval required", "obtain a human decision before sending");
    openpit::pretrade::PushReject(decision, entry);
  }
};

int main() {
  using Adapter = openpit::pretrade::PolicyAdapterWithSafeSlowArgType<
      ApprovalPolicy, openpit::model::Order, openpit::ExecutionReport>;

  openpit::EngineBuilder builder(openpit::SyncPolicy::Full);
  const auto policy = openpit::pretrade::CustomPolicy<Adapter>(
      "ApprovalPolicy", Adapter{ApprovalPolicy{}});
  const openpit::PolicyInstance instance{
      "approval", openpit::reject::RuleMode::ReviewWithoutHold};
  builder.Add(policy, instance);
  const openpit::Engine engine = builder.Build();

  openpit::model::Order order;
  auto& operation = order.operation.emplace();
  operation.instrument = openpit::model::Instrument(
      openpit::param::Asset("AAPL"), openpit::param::Asset("USD"));
  operation.accountId = openpit::param::AccountId::FromUint64(99224416);
  operation.side = openpit::model::Side::Buy;
  operation.tradeAmount = openpit::model::TradeAmount::OfQuantity(
      openpit::param::Quantity::FromString("10"));
  operation.price = openpit::param::Price::FromString("25");

  unsigned sent = 0;
  const auto run = [&](const openpit::model::Order& orderToCheck) {
    auto result = engine.ExecutePreTrade(orderToCheck);
    if (!result.Passed()) {
      throw std::runtime_error(result.rejects.front().reason);
    }
    auto& reservation = *result.reservation;
    auto reviews = reservation.Reviews();
    if (!reviews.empty()) {
      reservation.Commit();
      return reviews;
    }

    // Stand-in for a successful venue send.
    ++sent;
    reservation.Commit();
    return reviews;
  };

  const auto reviews = run(order);
  if (reviews.size() != 1 ||
      reviews.front().mode != openpit::pretrade::RuleMode::ReviewWithoutHold) {
    throw std::logic_error("expected one review mark without hold");
  }
  if (sent != 0) {
    throw std::logic_error("expected an unsent order");
  }

  // A human approved the same order.
  order.review.emplace().confirmed = true;
  const auto confirmedReviews = run(order);
  if (!confirmedReviews.empty() || sent != 1) {
    throw std::logic_error(
        "expected the confirmed order to pass and be sent once");
  }
}

Rust

use std::cell::Cell;

use openpit::param::{AccountId, Asset, Price, Quantity, Side, TradeAmount};
use openpit::pretrade::{
    PolicyPreTradeResult, PreTradeContext, PreTradePolicy, Reject, RejectCode, RejectScope, Rejects,
    RuleMode,
};
use openpit::storage::NoLocking;
use openpit::{
    Engine, Instrument, LocalSync, Mutations, OrderOperation, OrderReview, PolicyInstance,
    WithOrderReview,
};

type ReviewOrder = WithOrderReview<OrderOperation>;

struct ApprovalPolicy;

impl PreTradePolicy<ReviewOrder, (), (), LocalSync> for ApprovalPolicy {
    fn name(&self) -> &str {
        "ApprovalPolicy"
    }

    fn perform_pre_trade_check(
        &self,
        _ctx: &PreTradeContext<NoLocking>,
        _order: &ReviewOrder,
        _mutations: &mut Mutations,
    ) -> Result<Option<PolicyPreTradeResult>, Rejects> {
        Err(Reject::new(
            self.name(),
            RejectScope::Order,
            RejectCode::ComplianceRestriction,
            "approval required",
            "obtain a human decision before sending",
        )
        .into())
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let engine = Engine::builder::<ReviewOrder, (), ()>()
        .with_order_review()
        .no_sync()
        .pre_trade_instance(
            ApprovalPolicy,
            PolicyInstance {
                name: Some("approval".to_owned()),
                mode: RuleMode::ReviewWithoutHold,
            },
        )
        .build()?;

    let mut order = ReviewOrder {
        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("10")?),
            price: Some(Price::from_str("25")?),
        },
        review: OrderReview {
            confirmed: false,
            already_held: false,
        },
    };

    let sent = Cell::new(0);
    let run = |order| -> Result<Vec<Reject>, Rejects> {
        let mut reservation = engine.execute_pre_trade(order)?;
        let reviews = reservation.reviews().to_vec();
        if !reviews.is_empty() {
            reservation.commit();
            return Ok(reviews);
        }

        // Stand-in for a successful venue send.
        sent.set(sent.get() + 1);
        reservation.commit();
        Ok(reviews)
    };

    let reviews = run(order.clone())?;
    assert_eq!(reviews.len(), 1);
    assert_eq!(reviews[0].mode, RuleMode::ReviewWithoutHold);
    assert_eq!(sent.get(), 0);

    // A human approved the same order.
    order.review.confirmed = true;
    let confirmed_reviews = run(order)?;
    assert!(confirmed_reviews.is_empty());
    assert_eq!(sent.get(), 1);
    Ok(())
}

Clone this wiki locally