Backtesting vs live trading
Strategies run in two modes from the same code:- Backtesting (including forward-testing on real-time bars) runs against a built-in exchange emulator that simulates order fills, fees, and margin on historical and live bars.
- Live trading sends real orders to a real exchange and reacts to real fills.
Identical in both modes (strategy behavior)
These belong to the strategy itself, so they behave the same whether you backtest or trade live:- Order lifecycle and statuses — the states an order goes through (see Statuses and lifecycle).
- Execution delays — placing, updating, or canceling an order takes effect on the next tick, never instantly (see Order execution below).
intrabar_order_filter—NO_FILTER/ON_BAR_CLOSE/FIRST_IN_BAR/LAST_IN_BARgate order placements and cancels/amends identically (see Order filtering).- Capital, leverage, and margin — the strategy keeps its own books on
initial_capitalandleverage. A margin call (cannot open or increase the position) and a stop-out (all orders canceled, position force-closed, strategy halted) can happen to the strategy based on its own equity, independently of the state of your overall exchange account (see Margin trading).
Simulated only (backtesting)
The emulator has to invent things that a real exchange decides for you:- Fill prices and timing are simulated against each bar’s OHLC (limit/stop trigger logic, intrabar replay). In live trading, fills are real, asynchronous events from the exchange, so the exact fill price and the tick on which a fill arrives will differ from the simulation.
market_order_price(MARKET_PRICE/ORDER_CREATION_PRICE/BAR_OPEN_PRICE) affects backtesting only — it forces the simulated fill price. In live trading the fill price is whatever the exchange gives you and cannot be forced.- Commissions use the
commissionmodel you configure. In live trading the real exchange fees from each execution apply instead, so cash and equity evolve slightly differently even for identical fills.
Live only (real exchange)
- Order execution is the exchange’s job. Fills, partial fills, and the triggering of stop/limit and take-profit/stop-loss orders follow the real exchange’s rules and latency, not the emulator’s.
- Rejections and the automatic stop. The exchange can reject an order, an amend or a cancel, and a strategy whose commands keep being rejected is stopped (see Rejected orders and repeated errors).
- Take-profit / stop-loss are attached to the order and sent to the exchange. The position-level TP/SL behavior described in Take-profit and stop-loss orders is how the emulator models it (matching Bybit); other exchanges may handle brackets differently.
Live trading runs the same strategy code as backtesting, but a backtest is an approximation of live performance, not a guarantee. The differences above — simulated vs real fill prices, the configured commission vs real exchange fees, and exchange-side execution and latency — mean a live run can diverge from its backtest.
Order execution
When trading on a real exchange, your actions cannot be executed instantly. It takes time for a request to reach the exchange, for the order to be added to the order book, for it to be executed, and for the execution notification to return to you. When writing and backtesting strategies, traders often overlook these delays and fail to account for them. As a result, a strategy may behave very differently in live trading compared to backtesting. To address this, our backtesting engine simulates these real-world delays. This means that actions in your code do not take effect immediately. Instead, they are applied with a delay, and the results of those actions become visible only on the next price tick, when the strategy is recalculated. The following examples illustrate how these delays affect strategy behavior in different scenarios:Example 1: Order submission delay
When you create an order, it is not filled immediately. The order must first be sent to the exchange, accepted, and then executed. This example demonstrates that you cannot see the filled status immediately after callingsubmit():
Example 2: Order update delay
When you update an order’s parameters (e.g., limit price), the changes are not applied immediately. This example shows that the order properties reflect the update only on the nextcalc() call:
Example 3: Order cancellation delay
When you cancel an order, it is not canceled immediately. The cancellation request must be sent to the exchange and processed. This example demonstrates the delay:Example 4: Immediate update after creation
When you create and immediately update an order in the samecalc() call, the system applies the update locally before sending the order to the exchange. This means the order is sent with the updated parameters:
calc() call, not immediately. This behavior ensures your strategy works more consistently in both backtesting and live trading environments.
Fail-safe order operations
Some operations performed by a strategy — such as canceling or updating an order — are handled safely. This means the strategy will not fail if you call cancel or amend on an order that has already been canceled or executed. In such cases, the invalid operation is simply ignored. This simplifies your code and removes the need for additional if statements in situations where you want to “cancel an order if it hasn’t been executed or canceled yet” or “update an order if it’s still active”. The example below demonstrates a strategy that places sell limit orders and then cancels or updates them based on price movement — without checking the order status before each operation:cancel_order() and amend_order() without explicitly checking the order status beforehand. If the order has already been filled, canceled, or rejected, these operations will be safely ignored without throwing an exception. This simplifies your code by removing the need for defensive status checks.
Rejected orders and repeated errors
In live trading the exchange, or the trading platform before it, can refuse what a strategy sends: an order below the minimum size or value, a price outside the allowed range, not enough balance, or too many requests in a short time (exchange rate limits are per account).- A rejected placement ends with the order in the
REJECTEDstatus. The strategy sees it throughorder.status. The reason is shown in the strategy’s error messages, not passed to the script. - A rejected amend or cancel leaves the order as it was on the exchange: an amend keeps the old parameters, a cancel leaves the order active. The script is not notified of it; the error appears only in the strategy’s error messages.
REJECTED, so order.status alone does not tell them apart from exchange rejections:
- Warm-up. A live strategy first recalculates on history, and after a restart it also catches up on the bars it missed. Every order it places meanwhile is rejected without being sent.
- Intrabar order filter. An order that
intrabar_order_filterdoes not admit is rejected. With the default On Bar Close filter that is every order placed before the bar closes. - Own checks. An order below the instrument minimum, or one that the strategy’s margin does not cover (see Margin trading).
Automatic stop on repeated rejections
To protect your exchange account, a live strategy is stopped with an error when its commands (orders, amends, cancels) keep being rejected:- 10 rejections in a row with the same type of error (for example, invalid parameters or too many requests), with no order placed, filled or canceled in between; or
- 30 rejections within one minute, of any type.
Failed status, and the message names the last rejection. A failed strategy cannot be resumed: fix the cause and start a new one, for example with Duplicate & run on the bot’s card. Errors that mean the exchange or the trading platform is unavailable are not counted: they say nothing about the strategy.
An amend that changes nothing is not sent to the exchange at all. That includes a price change smaller than the instrument’s tick, because prices are rounded to the tick. So amending an order to the parameters it already has is harmless and does not count towards the limits above. The one exception is right after a command for that order was rejected: the exchange may still hold the old parameters, so the next amend is sent even if it repeats the last one.
Recommendations
React to every rejection, the first one included. A rejected order will be rejected again if it is sent unchanged, so a rejection is a signal to change what the strategy does, not to retry:- Fix the order, or stop sending it. Check what the strategy controls: the size against the instrument minimums, the price against the market, the side against the current position. If nothing can be fixed, don’t place that order again until something changes (a new signal, a new price level), and show it on the chart (for example, a marker or a background tint), so you can see why the strategy is idle.
- Never re-send an order unchanged on the next price update. That is the pattern the automatic stop exists for.
- Don’t count rejections or time them. The automatic stop is a safety net for your exchange account, not a budget to stay under; a strategy that handles each rejection reaches it only when something outside it goes wrong, such as another strategy using up the account’s request limit.
- Prevent the common rejections up front.
self.trading.instrument_infoholds the minimum order size and value (min_order_size,min_order_value); size orders above them. - Release the order once it is final. Treat
FILLED,CANCELED,PARTIALLY_FILLED_CLOSEDandREJECTEDas the end of an order; a strategy that waits only forFILLEDstops trading for good after a cancel. - Amend only when the parameters actually change. The order’s
limitandstopmay still show the values it was placed with, so keep the price you sent last and compare against it before callingamend_order.
order.status does not tell the local rejections above from the exchange’s. Every order of the warm-up ends in REJECTED, so a strategy that gives up for good after a rejection gives up before it starts trading live. Wait for the next change instead of stopping forever.
Order filtering (intrabar_order_filter parameter)
Inside a bar, the price moves. While the current candle is not finished, the strategy receives updates for the current candle. The strategy does not remember all intermediate values; only the latest, most actual value of the current candle is available in the strategy. If the logic of the strategy is based on comparing the current candle with the previous closed candle, then you may get false positive triggers. They can be avoided by additional checks in the code or by using our pre-configured filter intrabar_order_filter.
Possible values for intrabar_order_filter:
intrabar_order_filter.NO_FILTER: No intrabar filtering is applied. Orders can be placed or modified at any price update within a candle.intrabar_order_filter.ON_BAR_CLOSE: Orders can be placed or modified only at the close of the candle. Other submits ofplace_orderwill be rejected with theREJECTEDstatus.intrabar_order_filter.FIRST_IN_BAR: Only the first batch of orders within a bar is accepted. Orders can be placed on any price update, but once acalc()call places orders, all orders from subsequentcalc()calls within the same bar are ignored (rejected with theREJECTEDstatus).intrabar_order_filter.LAST_IN_BAR: Only the last batch of orders within a bar is applied. All orders placed during acalc()call are accepted, but if a newcalc()call places orders, the previous batch is replaced by the new one. The final batch is applied when the next bar starts.
Main function is called on each price update, not only on bar close. Since we compare the current price to the previous bar’s close, this will result in extra triggers:
Manual trigger filtering: previous price comparison
We can compare it not with the previous bar’s price but with the last received tick price, if you store it in a variable:Manual trigger filtering: trigger at bar close
We can detect the crossing and place an order only at bar close:Manual trigger filtering: only first trigger during bar
We can ensure that only one order is placed per bar (not necessarily at bar close):intrabar_order_filter.ON_BAR_CLOSE
To place orders only at bar close:
intrabar_order_filter.FIRST_IN_BAR
Only the first batch of orders within a bar is accepted. Orders can be placed on any price update, but once a calc() call places orders, all orders from subsequent calc() calls within the same bar are ignored until the next bar. You can place multiple orders in the same calc() call and they will all go through. The same rules apply to cancel_order and amend_order — see below.
intrabar_order_filter.LAST_IN_BAR
Only the last batch of orders within a bar is applied. You can place multiple orders in the same calc() call and they will all be accepted, but if a new calc() call places orders, the entire previous batch is replaced by the new one. The final batch is applied when the next bar starts. The same rules apply to cancel_order and amend_order — see below.
intrabar_order_filter.NO_FILTER
Finally, if none of these filters fit your needs and you want full control over when orders are placed, you can use the NO_FILTER setting, as shown in the examples above.
How filtering applies to cancel_order and amend_order
The intrabar_order_filter parameter controls not only place_order, but also cancel_order and amend_order commands. The filtering rules are the same as for order placement:
NO_FILTER:cancel_orderandamend_orderare accepted on any price update and applied on the next tick.ON_BAR_CLOSE:cancel_orderandamend_ordercalls are only accepted at bar close. Calls during intrabar ticks are silently ignored.FIRST_IN_BAR: The first batch ofcancel_order/amend_ordercalls in a bar is accepted. You can issue multiple commands in the samecalc()call and they will all go through. Commands from subsequentcalc()calls within the same bar are ignored.LAST_IN_BAR: Allcancel_order/amend_ordercalls within acalc()call are accepted as a batch. If a newcalc()call issues commands, the entire previous batch is replaced. The final batch is applied when the next bar starts.
FIRST_IN_BAR you can cancel two orders in a single calc() call and both will be canceled. But if you cancel one order on the first price update and try to cancel another on the next update, the second cancel will be ignored:
LAST_IN_BAR, if you cancel an order on one price update and then cancel a different order on the next update, the first cancel is replaced by the second — only the second cancel will be applied when the next bar starts.
Price for market orders (market_order_price parameter)
This parameter affects backtesting only. It forces the simulated fill price of market orders. In live trading the fill price is set by the real exchange and cannot be forced.
place_order() (see the Order execution section above). This behavior reflects real-world execution, but during backtesting traders sometimes want to force a specific execution price for testing purposes. You can configure which value will be used as the execution price for market orders.
There are three available options:
market_order_price.MARKET_PRICE: the actual market price at the time of execution (default)market_order_price.ORDER_CREATION_PRICE: the price at which the order was createdmarket_order_price.BAR_OPEN_PRICE: the opening price of the bar in which the order was created
Simulation of trading at market close
The configuration described above can be useful when you want to simulate trading at market close using a price close to the bar’s closing value. To achieve this, you should place an order right before the session ends, using the bar’s closing price. This can be done by combining themarket_order_price and intrabar_order_filter parameters.
Simulation of trading at market open
Similarly, by combining themarket_order_price and intrabar_order_filter parameters, you can execute an order at the current bar’s opening price to simulate trading at market open.
Margin trading (leverage parameter)
Margin is the strategy’s own accounting on
initial_capital and leverage, so it works the same in backtesting and live trading. A margin call (the strategy can no longer open or increase a position) and a stop-out (all its orders are canceled, the position is force-closed, and the strategy stops trading) can happen to the strategy from its own equity — even if your overall exchange account is fine.leverage parameter is greater than 1.0, the strategy can open positions larger than the available capital.
- Leverage: The ratio of the trader’s position size to their own capital. For example, a leverage of 2.0 means the trader can open positions twice the size of their capital.
- Initial margin: The minimum amount of the trader’s own funds required to open leveraged positions. If the portfolio value falls below the initial margin, the trader must reduce exposure. The trader cannot open new or increase existing uncovered positions.
- Maintenance Margin: The amount of collateral at which positions are forcibly closed. The maintenance margin is usually 1/2 of the initial margin.
- Equity: The trader’s total capital, including unrealized profits and losses, minus any liabilities.
- Margin Call: A warning issued when equity falls below the initial margin, requiring the trader to add funds or reduce exposure to avoid liquidation.
- Stop Out: The forced closure of positions when equity falls below the maintenance margin level.
- Amplified Losses: While leverage can increase profits, it also magnifies losses.
- Liquidation Risk: Failure to meet margin requirements can result in the forced closure of positions.
- Interest Costs: Borrowed funds may accrue interest, adding to the cost of trading.