Howwise RSS
Trading Software7 min read

Backtrader Order Margin Rejected: Why It Happens, Fixes

Short answer

A backtrader order margin rejected status means the broker found too little cash when the order executed. The order was sized at bar N's close but filled at bar N+1's open, and a gap plus commission pushed the cost above cash.

Key takeaways
  • Market orders are sized on bar N but cash-checked against bar N+1's open plus commission, so a gap-up can turn a valid size into a Margin order.
  • Margin means insufficient cash or margin; Rejected is a separate status, so test order.status in [order.Margin, order.Rejected, order.Canceled] and log both cash and value.
  • Sizing with int(cash/close) uses 100% of cash and ignores the gap and commission; a buffer or a custom sizer fixes it.
  • Cheat-on-open (cerebro.broker.set_coo(True) plus next_open) sizes with the real open, but reading data.close[0] there is look-ahead.
  • Track one pending order in self.order, because a second order in the same bar sees the same unreserved cash.

Reproduce a Margin order with a gap-up

The failure is easiest to understand with a deterministic example. This script builds four daily bars where the second bar opens 10% above the prior close, sizes the order as int(cash/close), and logs every status change.

With 10,000 cash and a close of 100, the strategy buys 100 shares. The fill is attempted at the next open of 110, which costs 11,000, so the broker cannot complete it.

import backtrader as bt
import pandas as pd

df = pd.DataFrame({
    'open':   [100, 110, 111, 112],
    'high':   [101, 112, 113, 114],
    'low':    [ 99, 109, 110, 111],
    'close':  [100, 111, 112, 113],
    'volume': [1000]*4,
}, index=pd.date_range('2024-01-02', periods=4, freq='B'))

class S(bt.Strategy):
    def next(self):
        if not self.position and len(self) == 1:
            size = int(self.broker.getcash() / self.data.close[0])
            self.buy(size=size)          # 100 shares sized at close 100

    def notify_order(self, order):
        print(self.data.datetime.date(0), order.getstatusname(),
              'size', order.created.size, 'cash', self.broker.getcash())

cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df))
cerebro.addstrategy(S)
cerebro.broker.setcash(10000)
cerebro.broker.setcommission(commission=0.001)
cerebro.run()
# Expected log: Submitted, Accepted, Margin

Why does backtrader set the order status to Margin?

Backtrader's event order is: strategy.next() runs on bar N, creates the order, and the broker processes it when bar N+1 arrives. A market order is executed at the open of N+1, not at the close you used for sizing.

At execution the broker computes size * open plus commission and compares it with available cash. If it is higher, the order gets status Margin, which is the status for insufficient cash (or margin for futures-style instruments). The order is dead; backtrader does not retry it with a smaller size.

Two things make int(cash/close) fail even without a large gap. The size consumes all cash, so any upward open difference breaks it, and commission is charged on top of the price. With a 0.1% commission, a 0.5% gap is already enough.

StatusMeaningTypical cause
SubmittedOrder sent to brokerNormal, ignore
AcceptedBroker queued itNormal, ignore
CompletedFully filledNormal, read executed price, size, comm
CanceledCanceled by you, by an OCO, or by the brokerself.cancel(), expired parent or bracket sibling
Expiredvalid= limit passedLimit or stop with valid= date reached
MarginNot enough cash or margin at executionSizing ignores next open and commission
RejectedBroker refused the orderBroker-side validation, for example a live or store rejection
Tip: Margin and Rejected are different statuses. Do not test only for Rejected, or Margin orders will pass silently through your handler.

How do I write a notify_order that detects Margin and Rejected?

Ignore Submitted and Accepted, log fills with the real execution numbers, and log failures together with cash and portfolio value. Comparing cash with value tells you whether the money is tied up in a position (value high, cash low) or the account is simply small.

Always compare against the class constants such as order.Margin, and use order.getstatusname() for readable logs. Clear self.order on every terminal status, otherwise a strategy that guards on it will stall forever.

def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
        return

    dt = self.data.datetime.date(0)
    if order.status == order.Completed:
        side = 'BUY' if order.isbuy() else 'SELL'
        print(f'{dt} {side} done price={order.executed.price:.2f} '
              f'size={order.executed.size} comm={order.executed.comm:.2f}')
    elif order.status in [order.Margin, order.Rejected, order.Canceled]:
        print(f'{dt} {order.getstatusname()} requested={order.created.size} '
              f'cash={self.broker.getcash():.2f} '
              f'value={self.broker.getvalue():.2f}')

    self.order = None   # allow a new order after any terminal status

Which sizing fix should I use?

The built-in default is bt.sizers.FixedSize with stake=1, which is what self.buy() uses when no size is given. The common bug is overriding it with int(cash/close), which assumes the fill happens at the close you saw.

Four patterns fix the problem. They differ in how much of the gap and commission they cover and in how much extra code they need.

ApproachHowHandles gapHandles commissionCaveat
Fixed buffersize = int(cash * 0.95 / close)Up to about 5% gapYes, within the bufferA bigger gap still fails; the buffer is a guess
PercentSizercerebro.addsizer(bt.sizers.PercentSizer, percents=95, retint=True)Same as bufferSame as bufferPrices at close; retint=True gives whole shares
Custom sizerSubclass bt.Sizer, add gap and commission marginConfigurableExplicitMore code, but reusable and testable
Cheat-on-openset_coo(True) and next_open()ExactExplicitLook-ahead risk if you touch the current close
Warning: Fractional sizes: PercentSizer returns a float unless retint=True. A float size may fill, or may not match your assumptions about whole shares, so set retint=True when you model whole-share trading.

How do I build a custom sizer that survives gaps?

Subclass bt.Sizer and implement _getsizing(self, comminfo, cash, data, isbuy). The cash argument is the broker's current cash. The sizer must price the order with a gap allowance and the commission, then return a whole number.

Returning the position size when isbuy is False means a sell closes the entire position. The rate is estimated per share with comminfo.getcommission(1, price), which suits percentage commissions; a fixed per-order fee needs a small separate allowance.

This sample sizes long entries and exits only. With no open position, a sell returns 0, so it does not open shorts.

class SafeSizer(bt.Sizer):
    params = (('pct', 0.95), ('gap', 0.03))

    def _getsizing(self, comminfo, cash, data, isbuy):
        if not isbuy:
            return abs(self.broker.getposition(data).size)  # close it all
        worst_price = data.close[0] * (1 + self.p.gap)
        per_share = worst_price + comminfo.getcommission(1, worst_price)
        return max(int(cash * self.p.pct / per_share), 0)

cerebro.addsizer(SafeSizer, pct=0.95, gap=0.03)
# strategy just calls self.buy(); the sizer supplies size

How does cheat-on-open size with the real open?

Cheat-on-open makes the broker fill market orders at the current bar's open, and calls next_open() before next(). There you can read data.open[0], which is already known at that moment, and size exactly.

Enable both pieces: Cerebro(cheat_on_open=True) enables the next_open() callback, and cerebro.broker.set_coo(True) makes the broker match orders at that open.

The look-ahead trap is that data.close[0], data.high[0] and data.low[0] inside next_open() belong to the bar that has not finished yet in live terms. Use only data.open[0] and indicator values computed from earlier bars (index [-1] on the raw lines).

class COO(bt.Strategy):
    def next_open(self):
        if not self.position:
            price = self.data.open[0]               # known at the open
            comm = self.broker.getcommissioninfo(self.data)
            per_share = price + comm.getcommission(1, price)
            size = int(self.broker.getcash() * 0.98 / per_share)
            if size > 0:
                self.buy(size=size)

cerebro = bt.Cerebro(cheat_on_open=True)
cerebro.broker.set_coo(True)

What else triggers Margin or Rejected orders? A debugging checklist

Padding cash hides the cause. Work through these checks in order, because each one produces the same log line.

  1. Cash versus value: getcash() excludes open positions, getvalue() includes them. A sizer that sizes from value while holding a position asks for more cash than exists, so rebalancing code must size the difference and not the target.
  2. Pending orders reserve nothing: backtrader does not lock cash for an unfilled order. Two buys in the same bar both see the same cash and the second fails. Keep self.order and return if it is not None.
  3. Commission setup: setcommission(commission=0.001) is a percentage for stock-like instruments. For futures, setcommission(commission=2.0, margin=2500, mult=50) switches to futures accounting, where margin per contract, not price, limits the size, and the cost is size * margin.
  4. Fractional shares: stock-like fills expect whole units for realistic results, so cast with int() unless you supply a custom CommInfo that allows fractions.
  5. Shorting: a short order also needs cash or margin, but the sample SafeSizer does not handle shorts. With no position, isbuy is False and it returns 0, so a short would get size 0. To short, add a separate branch that checks cash or margin and applies the gap in the adverse direction, which for a short is upward (worst price = close * (1 + gap)).
  6. Order of calls: cerebro.broker.setcash() must run before cerebro.run(). Setting cash after the data was added is fine, but calling it after run, or resetting it in a loop of runs on a reused broker, leaves a different amount than you assume. Print getcash() in start().
  7. set_checksubmit(False): this skips the check at submit time. It does not create cash, so orders can still fail at execution, and it can mask a sizing bug that you would otherwise catch early. Use it only for a deliberate reason, for example margin-style modelling you handle yourself.
Warning: Do not 'fix' Margin by raising starting cash until the log goes quiet. The next gap larger than your padding reproduces it, and your results then depend on an arbitrary amount.

Common questions

Can I check an order's cash need before sending it?

Yes. Compute size * price plus comminfo.getcommission(size, price) using a worst-case price, and compare it with self.broker.getcash() before calling self.buy(). This is what a custom sizer does for you.

Why is my order Canceled and not Margin?

Canceled comes from self.cancel(), an expired or triggered OCO sibling, or a bracket parent that did not fill. Margin is specifically a cash or margin failure. Check where your code cancels before blaming cash.

Does a Margin order get retried on the next bar?

No. The order is terminal once it has Margin status. Your strategy must clear its pending-order reference and decide whether to submit a smaller one.

Why does the same code work with one stake and fail with another?

The FixedSize default of stake=1 costs one share, which fits in any cash balance. Larger sizes approach the cash limit, so the gap and commission start to matter. The failure is a property of how close the size is to all your cash.

Related topics:backtraderpythonbacktestingposition sizingorder status