Python SDK
Example — SMA cross
A complete moving-average crossover backtest in ~40 lines.
This mirrors sdk/python/examples/sma_cross.py: long when the 20-period
SMA crosses above the 50-period SMA, flat on the reverse cross.
import os
from openbacktest import OpenBacktest
client = OpenBacktest(api_key=os.environ["OPENBACKTEST_API_KEY"])
candles = client.get_candles("BTCUSDT", "1h", count=1500)
candles["sma20"] = candles["close"].rolling(20).mean()
candles["sma50"] = candles["close"].rolling(50).mean()
project = client.create_project("SMA cross docs", "BTCUSDT", "1h")
session = client.create_session(
project.id, "sma 20/50", initial_balance=10_000,
fees={"entryFee": 0.1, "exitFee": 0.1, "type": "percent"},
)
for time, row in candles.dropna().iterrows():
above = row["sma20"] > row["sma50"]
if above and session.position is None:
session.buy(qty=0.1, price=row["close"], time=time)
elif not above and session.position is not None:
session.close(price=row["close"], time=time)
# Close any dangling position on the last bar
if session.position is not None:
last = candles.iloc[-1]
session.close(price=last["close"], time=candles.index[-1])
stats = session.finish()
print(f"trades : {stats.trade_count}")
print(f"winrate : {stats.winrate:.1%}")
print(f"net P&L : {stats.pl_net:,.2f}")
print(f"max drawdown: {stats.max_drawdown:,.2f}")Open the session in the web app afterwards — the equity curve, trade list and distribution charts are all there, just like a manual replay.