Strategy library

Double Inside Bar & Trend strategy in Pine Script

After two inside bars, a stop order on the side of the Hull average trend enters the breakout.

Inside bars · Hull moving average · ATR · long and short · by Kaspricci · Mozilla Public License 2.0

What is its backtest worth?

A parameter sweep finds the best setting of the Double Inside Bar & Trend strategy. PineTester tells you if it holds up: whether the best result was only picked after the fact, what it makes with fees, what you could have known at the time (a walk-forward on data the pick did not see) and how deep it fell along the way. On the free start, your first own backtest gets the full evaluation; its trade list and result file come with the full report or a plan.

Creates a draft on Binance BTC/USDT 4h over about six and a half years with 0.1% commission per order and 2 ticks slippage; you start it yourself. A backtest uses credits; new accounts receive free credits.

The rules

  • When two bars in a row lie inside the range of the bar before them, it places a buy stop at the last high if the close is above the Hull moving average, a sell stop at the last low if it is below.
  • Sets the stop loss an ATR multiple away and the take profit at a ratio of that distance; pending orders are cancelled once a trade is open.
  • Sizes each trade from a risk of 1% of the equity per trade (its risk setting is on by default); the date and session filters are off by default.

What to watch for

  • The order size is computed from the stop distance in ticks, as written for other markets; on a crypto pair the sizes can differ a lot from 1% risk – check the trade sizes.
  • Double inside bars are rare: the trade count decides how much the result says.

How PineTester judges a backtest, with its sources: how we judge results.

The Pine Script code

The author's code with its licence notice (Mozilla Public License 2.0), with one change marked in the code: the same test conditions for every library strategy in its strategy() line – the whole account per trade (split over the entries where it adds to a position), 0.1% commission per order and 2 ticks slippage; the trading rules are unchanged. Pine Script v5; PineTester converts it to v6 automatically, so results can differ slightly from TradingView.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
// Modified by PineTester (2026-11-14): the same test conditions for every library strategy in strategy(): 100% of equity per entry,
// 0.1% commission per order, 2 ticks slippage, initial capital 10,000. The trading rules are unchanged.
//@version=5
strategy(
     title = "Double Inside Bar & Trend Strategy - Kaspricci", 
     shorttitle = "Double Inside Bar & Trend", 
     overlay=true, 
     currency = currency.USD, 
     calc_on_every_tick = true, 
     close_entries_rule = "ANY", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, slippage=2)
// ================================================ Entry Inputs ======================================================================
headlineEntry   = "Entry Seettings"
maSource        = input.source(defval = close,             group = headlineEntry, title = "MA Source")
maType          = input.string(defval = "HMA",             group = headlineEntry, title = "MA Type", options = ["EMA", "HMA", "SMA", "SWMA", "VWMA", "WMA"])
maLength        = input.int(   defval = 45,    minval = 1, group = headlineEntry, title = "HMA Length")
float ma = switch maType 
    "EMA"  => ta.ema(maSource,  maLength)
    "HMA"  => ta.hma(maSource,  maLength)
    "SMA"  => ta.sma(maSource,  maLength)
    "SWMA" => ta.swma(maSource)
    "VWMA" => ta.vwma(maSource, maLength)
    "WMA"  => ta.wma(maSource,  maLength)
plot(ma, "Trend MA", color.purple)
// ================================================ Trade Inputs ======================================================================
headlineTrade   = "Trade Seettings"
stopLossType    = input.string(defval = "ATR",                         group = headlineTrade,                 title = "Stop Loss Type",            options = ["ATR", "FIX"])
atrLength       = input.int(   defval = 50,   minval = 1,              group = headlineTrade, inline = "ATR", title = "   ATR: Length                 ")
atrFactor       = input.float( defval =  2.5, minval = 0, step = 0.05, group = headlineTrade, inline = "ATR", title = "Factor       ",             tooltip = "multiplier for ATR value")
takeProfitRatio = input.float( defval =  2.0, minval = 0, step = 0.05, group = headlineTrade,                 title = "            TP Ration",     tooltip = "Multiplier for Take Profit calculation")
fixStopLoss     = input.float( defval = 10.0, minval = 0, step = 0.5,  group = headlineTrade, inline = "FIX", title = "   FIX: Stop Loss             ") * 10 // need this in ticks
fixTakeProfit   = input.float( defval = 20.0, minval = 0, step = 0.5,  group = headlineTrade, inline = "FIX", title = "Take Profit",               tooltip = "in pips") * 10 // need this in ticks
useRiskMagmt    = input.bool(  defval = true,                          group = headlineTrade, inline = "RM",  title = "")
riskPercent     = input.float( defval = 1.0,  minval = 0., step = 0.5, group = headlineTrade, inline = "RM",  title = "Risk in %                ", tooltip = "This will overwrite quantity from startegy settings and calculate the trade size based on stop loss and risk percent") / 100
// ================================================ Filter Inputs =====================================================================
headlineFilter  = "Filter Setings"
// date filter
filterDates     = input.bool(defval = false,                                 group = headlineFilter, title = "Filter trades by dates")
startDateTime   = input.time(defval = timestamp("2022-01-01T00:00:00+0000"), group = headlineFilter, title = "       Start Date & Time")
endDateTime     = input.time(defval = timestamp("2099-12-31T23:59:00+0000"), group = headlineFilter, title = "       End Date & Time  ")
dateFilter      = not filterDates or (time >= startDateTime and time <= endDateTime)
// session filter
filterSession   = input.bool(title = "Filter trades by session", defval = false, group = headlineFilter)
session         = input.session(title = "       Session", defval = "0045-2245", group = headlineFilter)
sessionFilter   = not filterSession or time(timeframe.period, session, timezone = "CET")
// ================================================ Trade Entries and Exits =====================================================================
// calculate stop loss
stopLoss        = switch stopLossType
    "ATR" => nz(math.round(ta.atr(atrLength) * atrFactor / syminfo.mintick, 0), 0)
    "FIX" => fixStopLoss
// calculate take profit
takeProfit      = switch stopLossType
    "ATR" => math.round(stopLoss * takeProfitRatio, 0)
    "FIX" => fixTakeProfit
doubleInsideBar = high[2] > high[1] and high[2] > high[0] and low[2] < low[1] and low[2] < low[0]
// highlight mother candel and inside bar candles
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na)
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na, offset = -1)
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na, offset = -2)
var float buyStopPrice  = na
var float sellStopPrice = na
if (strategy.opentrades == 0 and dateFilter and sessionFilter and doubleInsideBar and barstate.isconfirmed)
    buyStopPrice  := high[0] // high of recent candle (second inside bar)
    sellStopPrice := low[0] // low of recent candle (second inside bar)
    tradeID = str.tostring(strategy.closedtrades + strategy.opentrades + 1)
    quantity = useRiskMagmt ? math.round(strategy.equity * riskPercent / stopLoss, 2) / syminfo.mintick : na
    commentTemplate = "{0} QTY: {1,number,#.##} SL: {2} TP: {3}"
    if (close > ma)
        longComment = str.format(commentTemplate, tradeID + "L", quantity, stopLoss / 10, takeProfit / 10)
        strategy.entry(tradeID + "L", strategy.long, qty = quantity, stop = buyStopPrice, comment = longComment)
        strategy.exit(tradeID + "SL", tradeID + "L", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP")
    if (close < ma)
        shortComment = str.format(commentTemplate, tradeID + "S", quantity, stopLoss / 10, takeProfit / 10)
        strategy.entry(tradeID + "S", strategy.short, qty = quantity, stop = sellStopPrice, comment = shortComment)
        strategy.exit(tradeID + "SL", tradeID + "S", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP")
// as soon as the first pending order has been entered the remaing pending order shall be cancelled 
if strategy.opentrades > 0
    currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
    strategy.cancel(currentTradeID + "S")
    strategy.cancel(currentTradeID + "L")
  • PresentTrend – An ATR band follows the price and switches sides with the Money Flow Index; a turn of the band opens the trade.
  • Hull Kaufman SuperTrend Cloud – A cloud of three lines – Kaufman adaptive average, its Hull average and a Supertrend – that the price has to break.
  • Chandelier Exit + ZLSMA – A Chandelier Exit turn opens a trade only when the price also crosses a zero-lag least squares average (ZLSMA).
  • Bull Trend Filtered StochRSI – Buys while the Stochastic RSI is above a lower band and the close is above the highest EMA of the highs.
  • Steven Primo's Bollinger Bands – After several closes above narrow Bollinger Bands, a stop order above the last pivot high enters the breakout.

Open-source script by Kaspricci, shown under the Mozilla Public License 2.0. Not a recommendation; neither the author nor TradingView endorses PineTester. Backtests are hypothetical results on past data, not a forecast.