Live Order Approval Hook

LumiBot provides an optional, strictly live-only order approval hook at Strategy.submit_order (covering Python strategies, submit_orders, multi-leg option spreads, and AI agent order tools). When enabled, proposed live orders are staged for explicit approval before LumiBot sends them to the broker.

Key invariants:

  • Default mode is auto (LUMIBOT_TRADE_APPROVAL_MODE=auto): zero behavior change for existing strategies.

  • Strictly live-only: the approval hook never runs during backtesting (is_backtesting=True or broker.IS_BACKTESTING_BROKER=True).

  • Universal coverage: intercepts every live order flowing through Strategy.submit_order, Strategy.submit_orders, multi-leg option packages, and AI agent order tools (orders_submit_order, orders_submit_orders, orders_submit_multileg, prediction_submit_order).

  • Fail-closed on error: if staging fails (HTTP 4xx/5xx or handler error), LumiBot marks the order Order.OrderStatus.ERROR and never submits an unapproved broker order.

  • No duplicate submission: when the external approval service executes the order directly (executed_by_approver=True / executedByPlatform=true), LumiBot maps the returned broker order ID and status without calling the broker a second time.

Two Ways to Enable Live Approval

1. Environment Variables (HTTP Webhook Handler)

Configure HttpOrderApprovalHandler without modifying strategy code:

export LUMIBOT_TRADE_APPROVAL_MODE=require_approval
export LUMIBOT_TRADE_APPROVAL_URL="https://your-approval-service.example.com/api/trade-approvals"
export LUMIBOT_TRADE_APPROVAL_TOKEN="your-bearer-token"
# Optional fallback when no bearer token is set:
# export LUMIBOT_TRADE_APPROVAL_API_KEY="your-api-key"
# Optional bounded polling timeout in seconds (default 600; 0 = stage and return immediately):
export LUMIBOT_TRADE_APPROVAL_POLL_TIMEOUT_SECONDS=600

When LUMIBOT_TRADE_APPROVAL_MODE=require_approval and LUMIBOT_TRADE_APPROVAL_URL are set in a live run, HttpOrderApprovalHandler.from_env() stages each proposed order via POST <url> using Python’s standard library urllib (zero extra dependencies).

If the approval service returns a pending status with an actionId and poll_timeout_seconds > 0, LumiBot polls GET <url>/<actionId> with bounded backoff (2s -> 3s -> 5s -> 10s) until a terminal decision arrives or the timeout expires. If the timeout expires while still pending, LumiBot returns the order with status = Order.OrderStatus.AWAITING_APPROVAL and attaches order.approval_action_id and order.approval_url.

2. Custom Python Callback (order_approval_handler)

Pass a custom callable via Strategy(..., order_approval_handler=handler) or assign self.order_approval_handler = handler inside initialize(). A custom handler takes precedence over environment variables and can return an OrderApprovalDecision dataclass or a plain dict.

from lumibot.strategies import Strategy
from lumibot.strategies.order_approval import OrderApprovalDecision


def require_small_notional(order, *, reason=None, is_multileg=False, strategy=None, kwargs=None):
    """Auto-approve small equity orders; block or route larger orders for review."""
    orders = order if isinstance(order, list) else [order]
    for item in orders:
        price = item.limit_price or strategy.get_last_price(item.asset) or 0
        if item.quantity * price > 5_000:
            return OrderApprovalDecision(
                decision="rejected",
                message="Order exceeds $5,000 automated live limit.",
            )
    return OrderApprovalDecision(decision="auto_approved")


class GuardedLiveStrategy(Strategy):
    def initialize(self):
        self.sleeptime = "1D"
        self.order_approval_handler = require_small_notional

    def on_trading_iteration(self):
        order = self.create_order("SPY", 5, "buy")
        result = self.submit_order(order, reason="Daily momentum signal")
        self.log_message(f"Order status: {result.status}")

Approval Decisions and Order Status Mapping

OrderApprovalDecision (from lumibot.strategies.order_approval) accepts:

OrderApprovalDecision outcomes

decision value

Resulting Order.status

Broker submission behavior

auto_approved

Broker status

LumiBot submits the order to the broker normally.

approved (executed_by_approver=False)

Broker status

LumiBot submits the approved order to the broker.

approved (executed_by_approver=True)

Mapped from broker_status (default SUBMITTED)

Approver already executed the order; LumiBot attaches broker_order_id and does not submit again.

pending

Order.OrderStatus.AWAITING_APPROVAL

Not yet submitted. order.approval_action_id and order.approval_url are attached.

rejected

Order.OrderStatus.CANCELED

Blocked. order.error carries the rejection message.

expired

Order.OrderStatus.EXPIRED

Blocked. Approval window expired before confirmation.

error

Order.OrderStatus.ERROR

Fail-closed. Order is never sent to the broker.

HTTP Payload Contract

serialize_order_for_approval(...) sends a JSON payload with:

{
  "trade": {
    "symbol": "SPY",
    "side": "buy",
    "quantity": 10.0,
    "assetType": "stock",
    "orderType": "limit",
    "orderClass": "simple",
    "timeInForce": "day",
    "limitPrice": 580.25
  },
  "idempotencyKey": "lumibot-...",
  "estimatedNotionalUsd": 5802.5,
  "reason": "Daily momentum signal"
}

For multi-leg option orders, trade contains "orderClass": "multileg" and a "legs" array with each leg’s symbol, side, quantity, expiration, strike, and right.

The approval endpoint can respond with fields decision (or status), executedByPlatform (or executed_by_approver), actionId, approvalUrl, orderId / brokerOrderId, brokerStatus, and message.

See Environment Variables for all LUMIBOT_TRADE_APPROVAL_* settings.