Darvas Box strategy in Pine Script
A break out of the Darvas box in the direction of a slow weighted average, with the other side of the box as stop.
Darvas Box · WMA · Relative Vigor Index · long and short · by xxy_theone · Mozilla Public License 2.0
What is its backtest worth?
A parameter sweep finds the best setting of the Darvas Box 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
- Enters long when the close crosses above the top of the box and is above the MavilimW average; short when it crosses below the bottom and is below.
- Places the stop at the opposite side of the box; closes a trade in profit when the Relative Vigor Index crosses its signal line.
- Stops opening trades after 100 closed trades (a limit in the code).
What to watch for
- The 100-trade limit can end the backtest early on a short timeframe; check the date of the last trade.
- The exit only acts on trades in profit; losing trades run until the box stop.
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 these changes 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; and its default From/To dates cover the whole test period (they were March 7 – 19, 2022, which limited every backtest to those two weeks). 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/
// © xxy_theone
// Modified by PineTester (2026-11-13): the default From/To cover the whole test period (they were Mar 07 – Mar 19 2022,
// which limited every backtest to those two weeks). Nothing else changed.
// 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.
// https://www.youtube.com/watch?v=YYxlnFOX9sQ
// This strategy script has been made to backtest the strategy explained in the video above
//@version=5
strategy(shorttitle = "Darvas Box Test", title="TradeIQ Darvas Box Test", overlay=true, pyramiding=0, currency=currency.USD, 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)
// === INPUT BACKTEST RANGE ===
var GRP1 = "Backtest Range"
fromDate = input.time(timestamp("1 Jan 2017 00:00 +0000"), "From", group=GRP1)
toDate = input.time(timestamp("31 Dec 2099 23:59 +0000"), "To", group=GRP1)
window() => // create function "within window of time"
time >= fromDate and time <= toDate ? true : false
var GRP3 = "Darvas Box"
boxp=input(5, "Box Length", group=GRP3)
LL = ta.lowest(low,boxp)
k1=ta.highest(high,boxp)
k2=ta.highest(high,boxp-1)
k3=ta.highest(high,boxp-2)
NH = ta.valuewhen(high>k1[1],high,0)
box1 =k3<k2
TopBox = ta.valuewhen(ta.barssince(high>k1[1])==boxp-2 and box1, NH, 0)
BottomBox = ta.valuewhen(ta.barssince(high>k1[1])==boxp-2 and box1, LL, 0)
plot(TopBox, linewidth=3, color=color.green, title="TBbox")
plot(BottomBox, linewidth=3, color=color.red, title="BBbox")
var GRP4 = "MavilimW"
fmal=input(3,"First Moving Average length", group=GRP4)
smal=input(5,"Second Moving Average length", group=GRP4)
tmal=fmal+smal
Fmal=smal+tmal
Ftmal=tmal+Fmal
Smal=Fmal+Ftmal
M1= ta.wma(close, fmal)
M2= ta.wma(M1, smal)
M3= ta.wma(M2, tmal)
M4= ta.wma(M3, Fmal)
M5= ta.wma(M4, Ftmal)
MAVW= ta.wma(M5, Smal)
col1= MAVW>MAVW[1]
col3= MAVW<MAVW[1]
colorM = col1 ? color.blue : col3 ? color.red : color.yellow
plot(MAVW, color=colorM, linewidth=2, title="MAVW")
var GRP5 = "Relative Vigor Index"
len = input.int(10, title="Length", minval=1, group=GRP5)
rvi = math.sum(ta.swma(close-open), len)/math.sum(ta.swma(high-low),len)
sig = ta.swma(rvi)
offset = input.int(0, "Offset", minval = -500, maxval = 500, group=GRP5)
//plot(rvi, color=#008000, title="RVGI", offset = offset)
//plot(sig, color=#FF0000, title="Signal", offset = offset)
var longStopSet = false
long = ta.crossover(close,TopBox) and close > MAVW ? true : false
longClose = strategy.opentrades.profit(strategy.opentrades-1)>0 and ta.crossunder(rvi,sig) ? true : false
strategy.entry("Long Position", strategy.long, when = long and window() and strategy.position_size==0 and strategy.closedtrades<100)
if(longStopSet==false and strategy.position_size > 0)
strategy.exit("exit", "Long Position", stop=BottomBox)
longStopSet := true
if(strategy.position_size==0)
longStopSet := false
strategy.close("Long Position", when = longClose)
var shortStopSet = false
short = ta.crossunder(close,BottomBox) and close < MAVW ? true : false
shortClose = strategy.opentrades.profit(strategy.opentrades-1)>0 and ta.crossover(rvi,sig) ? true : false
strategy.entry("Short Position", strategy.short, when = short and window() and strategy.position_size==0 and strategy.closedtrades<100)
if(shortStopSet==false and strategy.position_size < 0)
strategy.exit("exit", "Short Position", stop=TopBox)
shortStopSet := true
if(strategy.position_size==0)
shortStopSet := false
strategy.close("Short Position", when = shortClose)
Related strategies
- Volatility Range Breakout – Bands around the price, as wide as its recent range, are averaged; a break of a band opens the trade.
- Vortex Cross with Moving Average – A cross of the two Vortex lines, confirmed by the price against a smoothed moving average.
- Volatility Capture RSI-Bollinger – A trailing line built from wide Bollinger Bands, with an RSI filter on the entries.
Open-source script by xxy_theone, 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.