Backtesting and history
Write a strategy in Python under Automation → Backtest, run it on stored history and read the trades, curves and statistics.
A first strategy
This is a textbook moving-average example that shows the shape of the code. The page has more examples and a reference of every call.
from btengine import Algorithm
class SmaCross(Algorithm):
def initialize(self):
self.set_lookback(days=21)
self.btc = self.add_perp("BTC", venue="binance", resolution="1h")
self.fast, self.slow = self.sma(self.btc, 20), self.sma(self.btc, 50)
self.set_warmup(50)
def on_data(self, data):
if self.fast.value > self.slow.value and not self.portfolio[self.btc].invested:
self.set_holdings(self.btc, 0.95)
elif self.fast.value < self.slow.value and self.portfolio[self.btc].invested:
self.liquidate(self.btc)A strategy can add perpetual and spot markets, place market, limit, stop, stop-limit and trailing orders, schedule functions and plot its own series. Strategies can be saved by name, and the newest 50 runs are kept. One run works at a time and the rest wait.
How fills are simulated
| Subject | Rule |
|---|---|
| Timing | The strategy decides at a bar's close. Its orders are first tested by the next bar. |
| Market orders | Next open, slipped 2 bp against you unless you set another model, at the taker fee. |
| Limit orders | Fill when the bar's range reaches them, at the maker fee. |
| Stop and target in one bar | The stop fills first. |
| Fees | Each exchange's base rates, or a percentage you set. |
| Funding | Paid at the exchange's funding times from stored rates. Where a rate is missing, a flat one is used and the result says how often. |
| Liquidation | Isolated margin, with a 0.5% maintenance rate unless you set one. |
What history there is
- Candles: one-minute bars, with longer bars built from them. By default they reach back about 30 days.
- Funding rate, mark, index and open interest, sampled each minute and served in buckets of five minutes or more.
- Archive: best prices, depth and funding by exchange, symbol and day. It only holds what was recorded while recording was on for your deployment. Ask us to turn it on if you need it, because it cannot be filled in later.
Missing minutes are not invented. A slot without trades has no bar, and the result names the holes. The page lists the markets and resolutions available now.
Limits of a run
A run has no network access, 1 GB of memory and 120 seconds by default. Imports are limited to btengine and a short list of standard modules such as math, statistics and datetime. Errors come back with the line number in your code.
From a test to trading
Backtest code does not trade. Run a strategy covers the paper market and going live.