QuantScript — example-backtest.qs
// ─────────────────────────────────────────────────────────────────────────────
// SMA Trend Pullback Strategy — XAUUSD 1H (Backtest Mode)
// ─────────────────────────────────────────────────────────────────────────────
//
// Backtests a trend-following strategy on XAUUSD 1-hour candles from
// June 1, 2026 to July 1, 2026 using the DemoTrader data adapter.
//
// Strategy logic:
//   1. 50-period SMA defines the trend direction.
//   2. RSI(14) identifies pullback entries within the trend.
//   3. Long when price is above SMA and RSI crosses above 50 (bullish midline cross).
//   4. Short when price is below SMA and RSI crosses below 50 (bearish midline cross).
//   5. ATR-based stop loss and take profit for risk management.
//
// ─────────────────────────────────────────────────────────────────────────────

mode({ type: "backtest", script_name: "XAUUSD SMA Pullback" });
broker({ adapter: "sim", config: {
  initial_capital: 100000,
  fee_model: "percent",
  fee_percent: 0.05
} });

candles({ symbol: "XAUUSD", resolution: "1h", bars: 720, from_timestamp: 1780272000, to_timestamp: 1782864000, adapter: "demotrader.net" });

risk({ max_position_pct: 25, daily_loss_limit: 3 });

// ── Indicator Parameters ───────────────────────────────────────────────────
const smaLen    = input.int(50, "SMA Length", 10, 200, null, null, null, "Trend");
const rsiLen    = input.int(14, "RSI Length", 5, 50, null, null, null, "Entry");
const atrLen    = input.int(14, "ATR Length", 5, 50, null, null, null, "Risk");
const rsiBullZone  = input.float(50.0, "RSI Bullish Cross Level", null, null, null, null, null, "Entry");
const rsiBearZone  = input.float(50.0, "RSI Bearish Cross Level", null, null, null, null, null, "Entry");
const slMult    = input.float(1.5, "Stop Loss × ATR", 0.5, 5.0, 0.1, null, null, "Risk");
const tpMult    = input.float(2.5, "Take Profit × ATR", 1.0, 10.0, 0.5, null, null, "Risk");

// ── Entry handler ──────────────────────────────────────────────────────────
event.onCandle((candle) => {
  // ── Warmup ────────────────────────────────────────────────────────────
  if (candleIndex < Math.max(smaLen, rsiLen, atrLen)) { return; }

  let close = candle.close;
  let high  = candle.high;
  let low   = candle.low;

  // ── Indicators ────────────────────────────────────────────────────────
  let smaVal = ta.sma(close, smaLen);
  let rsiVal = ta.rsi(close, rsiLen);
  let atrVal = ta.atr(high, low, close, atrLen);

  // ── Debug: log indicator values every 50 bars ─────────────────────────
  if (candleIndex % 50 === 0) {
    console.log("[bar " + candleIndex + "] close=" + close + " sma=" + smaVal + " rsi=" + rsiVal + " atr=" + atrVal);
  }

  // ── Chart Plots ───────────────────────────────────────────────────────
  chart.plot(smaVal, "SMA(" + smaLen + ")", "#FF9800");

  // ── Entry Signals ─────────────────────────────────────────────────────
  let bullTrend  = close > smaVal;
  let rsiRecover = ta.crossover(rsiVal, rsiBullZone);

  let bearTrend  = close < smaVal;
  let rsiDrop    = ta.crossunder(rsiVal, rsiBearZone);

  // ── Long Entry ────────────────────────────────────────────────────────
  if (bullTrend && rsiRecover && strategy.positions().length < 2) {
    trade.buy({
      symbol: "XAUUSD", size: { lots: 0.1 }, comment: "Long",
      stopLoss: close - atrVal * slMult,
      takeProfit: close + atrVal * tpMult,
      reason: "SMA trend long: RSI crossed above " + rsiBullZone,
      context: { close: close, rsi: rsiVal, sma: smaVal },
      tags: ["trend", "long_entry"]
    });
  }

  // ── Short Entry ───────────────────────────────────────────────────────
  if (bearTrend && rsiDrop && strategy.positions().length < 2) {
    trade.sell({
      symbol: "XAUUSD", size: { lots: 0.1 }, comment: "Short",
      stopLoss: close + atrVal * slMult,
      takeProfit: close - atrVal * tpMult,
      reason: "SMA trend short: RSI crossed below " + rsiBearZone,
      context: { close: close, rsi: rsiVal, sma: smaVal },
      tags: ["trend", "short_entry"]
    });
  }

  // ── Exit on SMA cross ─────────────────────────────────────────────────
  if (close < smaVal) {
    for (const pos of strategy.positions()) {
      if (pos.comment === "Long") {
        trade.closePosition({ positionId: pos.id });
      }
    }
  }

  if (close > smaVal) {
    for (const pos of strategy.positions()) {
      if (pos.comment === "Short") {
        trade.closePosition({ positionId: pos.id });
      }
    }
  }
});

← Back to all examples