Darvas Box Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ceyhun

//@version=4
strategy ("Darvas Box Strategy",overlay=true)

boxp=input(5, "BOX LENGTH")

D_High = security(syminfo.tickerid, 'D', high) 
D_Low = security(syminfo.tickerid, 'D', low) 
D_Close =  security(syminfo.tickerid, 'D', close) 
D_Open =  security(syminfo.tickerid, 'D', open) 

LL = lowest(D_Low,boxp)
k1 = highest(D_High,boxp)
k2 = highest(D_High,boxp-1)
k3 = highest(D_High,boxp-2)

NH   = valuewhen(D_High>k1[1],D_High,0)
box1 = k3<k2
TopBox = valuewhen(barssince(D_High>k1[1])==boxp-2 and box1, NH, 0)
BottomBox = valuewhen(barssince(D_High>k1[1])==boxp-2 and box1, LL, 0)

plot(TopBox, linewidth=2, color=#00FF00, title="TopBox")
plot(BottomBox, linewidth=2, color=#FF0000, title="BottomBox")

if crossover(D_Close,TopBox)
    strategy.entry("Long", strategy.long, comment="Long")

if crossunder(D_Close,BottomBox)
    strategy.entry("Short", strategy.short, comment="Short")
