Skip to main content

Bollinger Bands and MACD Swing Trading Strategy

This strategy looks for a price recovery after a close below the lower Bollinger Band. The MACD histogram supplies a momentum check on the recovery candle.

  • Buy when the previous candle closed below its lower band, the latest completed candle closes back inside the bands, and its MACD histogram is higher than on the previous candle.
  • Sell when the close is at or above the middle band or closes below the lower band again.

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.swingtradingmacdbbOrderCandle === candleTime || gb.data.openOrders.length > 0) return;

const closes = gb.data.candlesClose.slice(0, -1);
if (closes.length < 40) 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, upper] = indicator("bbands", [closes], [20, 2]);
const [, , histogram] = indicator("macd", [closes], [12, 26, 9]);
const close = closes.at(-1);
const buySignal = closes.at(-2) < lower.at(-2) && close >= lower.at(-1) &&
close <= upper.at(-1) && histogram.at(-1) > histogram.at(-2);
const sellSignal = close >= middle.at(-1) || close < lower.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.swingtradingmacdbbOrderCandle = 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.swingtradingmacdbbOrderCandle = candleTime;
await gb.method.buyMarket(amount, gb.data.pairName, gb.data.exchangeName);
}

Gunbot Live backtest result for swing trading macd bb, showing 43 buys, 43 sells and a final wallet value of 1,012.84 USDT.

This Binance spot backtest filled 43 buys and 43 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.