Write Python strategies
Write QTrader entry and exit signals with Python, indicator series and input parameters, then inspect a historical backtest.
Before you start
QTrader uses restricted Python for signals, not a general Python notebook. You write supported functions, inputs and series expressions; arbitrary imports, external network access and third-party packages are outside the strategy contract.
Choose historical candles in the workbench and start with a bundled example. The same engine evaluates supported Pine and Python strategies, so the backtest settings and fill rules still matter. A guest can try the editor; current access limits determine which runs and resources are available.
Follow the workflow
- Open the Python SMA example below. Inputs define the two average lengths; the
indicator.smacalls create series. - Return the entry condition from
enter_long()and the closing condition fromexit_long(). Use the documented short entry/exit functions when the strategy needs shorts. - Use the Parameters controls to vary declared inputs. Inspect compile errors and warnings before interpreting any result.
- Choose the market, timeframe, dates, size and costs. Press Backtest and inspect individual trades, not only the headline return.
- Keep a copy of the code and assumptions before trying another idea. Opening a docs example creates unsaved work; an account is needed for account features.
Worked example
SMA 50/200 cross: Long only. Buys when the 50-bar SMA crosses above the 200-bar SMA and sells when it crosses back below; both lengths are inputs. No stop-loss or take-profit. The link opens this exact bundled example as unsaved work on its recommended timeframe.
fast_length = input.int(50, "Fast SMA", minval=2)
slow_length = input.int(200, "Slow SMA", minval=2)
def enter_long():
return indicator.crossover(indicator.sma(close, fast_length), indicator.sma(close, slow_length))
def exit_long():
return indicator.crossunder(indicator.sma(close, fast_length), indicator.sma(close, slow_length))
The functions return signals rather than making an exchange request. The backtest engine handles the position and simulated fills.
Limits and interpretation
Python history uses close[-1] for the previous bar, unlike Pine's positive offset. Expressions can read the current and earlier bars, not future bars. Indicators need enough history to warm up; a missing value is not a valid signal.
Read the Python contract, position fields, indicator reference and strategy settings before adding state, protective exits or multiple entries. Historical simulation does not prove that a strategy will remain profitable.