Skip to main content

Bollinger Bands and RSI Range Trading Strategy

This example looks for a move from the lower Bollinger Band back to the middle band. The 20-period bands sit two standard deviations from the middle band.

  • Buy when the close is below the lower 20-period Bollinger Band and 14-period RSI is below 35.
  • Sell when the close is at or above the middle band.

Follow the backtest setup to run this example on a spot pair.

// Read completed candles. The newest candle can still be forming.
const candleTime = Number(gb.data.candlesTimestamp.at(-2));
if (!(candleTime > 0) || !(gb.data.ask > 0) || !(gb.data.bid > 0)) return;

const store = gb.data.pairLedger.customStratStore ??= {};
if (store.rangetradingOrderCandle === candleTime || gb.data.openOrders.length > 0) return;

const closes = gb.data.candlesClose.slice(0, -1);
if (closes.length < 30) return;

// Use the same synchronous Tulind callback as the editor's spot starter.
function indicator(name, inputs, options) {
let series = [];
gb.method.tulind.indicators[name].indicator(inputs, options, (error, results) => {
if (error) throw error;
series = results;
});
return series;
}

const [lower, middle] = indicator("bbands", [closes], [20, 2]);
const [rsi] = indicator("rsi", [closes], [14]);
const close = closes.at(-1);
const buySignal = close < lower.at(-1) && rsi.at(-1) < 35;
const sellSignal = close >= middle.at(-1);

// Spot market order amounts are in the asset being traded (BTC in USDT-BTC).
if (gb.data.gotBag && sellSignal && gb.data.quoteBalance > 0) {
store.rangetradingOrderCandle = candleTime;
await gb.method.sellMarket(gb.data.quoteBalance, gb.data.pairName, gb.data.exchangeName);
} else if (!gb.data.gotBag && buySignal) {
const budget = Number(gb.data.pairLedger.whatstrat.TRADING_LIMIT);
if (!Number.isFinite(budget) || budget <= 0 || gb.data.baseBalance <= budget) return;

const amount = budget / gb.data.ask;
store.rangetradingOrderCandle = candleTime;
await gb.method.buyMarket(amount, gb.data.pairName, gb.data.exchangeName);
}

Gunbot Live backtest result for range trading, showing 21 buys, 21 sells and a final wallet value of 1,008.28 USDT.

This Binance spot backtest filled 21 buys and 21 sells on 1-hour USDT-BTC candles from January through March 2024, using a 1,000 USDT starting balance, a 100 USDT buy budget and 0.1% trading fees.