Appearance

Personalize your experience

Mode
Accent Color
Direction
Python: Event-Driven Strategies

Python: Event-Driven Strategies

Python SDK

Subclass quatick.Strategy to trade bar by bar with real orders: brackets, trailing stops, limits, risk-based sizing and a drawdown kill switch. The same file backtests locally and on Quatick.

A complete strategy

breakout.py
from quatick import Strategy, ta, run, Barsclass Breakout(Strategy):    params = {"n": 20, "atr_mult": 2.0, "risk_pct": 1.0}    def init(self, ctx):                       # once, before the first bar        b = ctx.bars        self.hi = ta.highest(b.high, self.p.n)        self.atr = ta.atr(b.high, b.low, b.close, 14)    def on_bar(self, ctx):                     # after every bar closes        i = ctx.i        if ctx.position or ctx.open_orders or i == 0 or ta.is_na(self.hi[i - 1]):            return        if ctx.close > self.hi[i - 1]:            stop = ctx.close - self.p.atr_mult * self.atr[i]            qty = ctx.size_by_risk(self.p.risk_pct, ctx.close - stop)            ctx.buy(qty, sl=stop, tp_pct=6, tag="breakout")    def on_fill(self, ctx, fill):        ctx.log("filled", fill.tag, fill.qty, "@", round(fill.price, 2))if __name__ == "__main__":    bars = Bars.read_csv("btc_1h.csv", interval="1h")    r = run(Breakout, bars, capital=100_000, costs={"kind": "crypto_maker_taker", "value": 0.02, "taker": 0.05},            max_drawdown_stop_pct=25)    print(r.summary())

Upload the file as a and the server finds the subclass, runs it with the page's costs and settings, and scores it like any other . Set = Breakout if a file defines several.

The Context (ctx)

MemberMeaning
ctx.i, ctx.timeindex and time of the bar that just closed
ctx.open / high / low / close / volumethat bar
ctx.history(column, n)the last n values up to this bar (never )
ctx.barsthe whole series (for indicators in init; index them with ctx.i)
ctx.position, ctx.avg_price, ctx.cash, ctx.equitythe account at this close
ctx.open_orders, ctx.haltedworking orders; whether the limit stopped trading
ctx.buy(qty, limit=, stop=, sl=, tp=, sl_pct=, tp_pct=, trail_pct=, trail_amount=, tif=, expire_bars=, reduce_only=, oco=, tag=)send an order (the type follows from the prices given)
ctx.sell(...)the same, selling
ctx.order_target(units), ctx.order_target_percent(fraction)market order for the difference to a target position
ctx.close_position(), ctx.(order), ctx.cancel_all()exits and cancels
ctx.size_by_risk(risk_pct, risk_per_unit), ctx.size_pct(pct)position sizing, rounded down to lot_size
ctx.log(...)a line in the run log (shown in the Report and views)
!
Caution:Indicators computed in init span the whole series. Only read them at index ctx.i or earlier; the lookahead check catches strategies that do not.

The result

FieldContents
r.statsthe engine (, , calmar, maxDrawdownPct, profitFactor, ...)
r.Trade objects: entry / exit bar, time and price, qty, pnl, costs, entry_tag, exit_tag, mae_pct, mfe_pct
r., r.ordersevery fill and every order with its final status and reason
r.equity, r.positionper bar
r.halted_at, r.logsthe bar the limit fired on; the run log

See also

Related articles

  • Python: Research Toolkit

    Backtesting / SDKs / Python

    Everything after the first backtest: tearsheet analytics, multi-asset portfolios, position sizing, optimization and walk-forward, overfitting tests, Monte…

  • Backtesting in Python and C++

    Backtesting / SDKs

    The quatick Python package and the header-only C++ library let you import indicators, backtest on your own machine and send the same file to Quatick.…

  • The Backtest Engine

    Backtesting / Engine

    One service backtests every kind of strategy on Quatick. Each source type runs on the engine built for it, and every result is measured with the same…

  • C++ SDK Reference

    Backtesting / SDKs / C++

    Header-only C++20 (packages/quatick-backtest-cpp): the position simulator, an event-driven engine with the same order rules as Python, analytics, a parallel…

  • Engines — Python vs C++

    Automation / Predefined Strategies

    Two independent implementations of the same grid semantics, consuming the same config and the same command channel. The choice is a runtime choice, not a…

  • Long Position

    Charts / Drawing Tools / Measurement

    A measurement tool that visualizes a long (buy) trade setup with entry price, stop-loss level, and one or more take-profit targets, including the calculated…

  • Orders and Fills

    Backtesting / SDKs / Orders and Fills

    The event-driven engines of the Python and C++ SDKs share one set of order types and fill rules, so the same strategy fills identically in both languages…

  • Python Scripting with Pyodide

    Coding / IDE / Python

    Quatick strategies run in Python 3.11 via Pyodide — a full CPython compiled to WebAssembly. This means your strategies execute entirely in the browser, with…

  • Short Position

    Charts / Drawing Tools / Measurement

    A measurement tool that visualizes a short (sell) trade setup with entry price, stop-loss above, and take-profit targets below, including the calculated…

Browse all knowledge base articles →