Pine Script strategy buy limit

Viewed 309

I want to buy at green line and sell at red line. At every beginning of each bar, I want to place an buy limit order at the green line price and/or a sell limit order at the red line price and cancel them at end of the bar session or at beginning of next bar session if they are not filled. Also, if there is a buy order that has not been exited, I don't want to buy any more of the position.

enter image description here

But my code below does this and I cannot figure out what I am doing wrong. Can someone help? enter image description here

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

//@version=4
strategy("vwap stdev strategy", overlay=true , calc_on_every_tick=true )

//User Input
period = input(title="Period", type=input.integer, defval = 4)


//Calculation
ohlcSumVolumeWeighted = 0.0
volumeSum = 0.0
stdevSumVolumeWeighted = 0.0


for i = 0 to period
    ohlc = (high[i]+low[i]+close[i]+open[i])/4
    stdev = sqrt(( pow(high[i]-ohlc,2) + pow(low[i]-ohlc,2) + pow(close[i]-ohlc,2) + pow(open[i]-ohlc,2))/(4-1)) 
    ohlcSumVolumeWeighted := ohlcSumVolumeWeighted + ohlc*volume[i]
    volumeSum := volumeSum + volume[i]
    stdevSumVolumeWeighted :=  stdevSumVolumeWeighted + stdev*volume[i]

myVwap = ohlcSumVolumeWeighted/volumeSum
trueStdev = stdevSumVolumeWeighted/volumeSum
buyPrice = myVwap- 2.25*trueStdev
sellPrice = myVwap + 1.5*trueStdev

//Plot
plot(myVwap, title="vwap", color=color.blue, transp=0)
plot(myVwap+ 1.5*trueStdev, title="stdev upper lvl.1", color=color.red, transp=0)
plot(myVwap- 2.25*trueStdev, title="stdev lower lvl.2.5", color=color.lime, transp=0)
plot(myVwap- 3*trueStdev, title="stdev lower lvl.3", color=color.green, transp=0)

//Conditions
isBuyLvl = myVwap- 2.25*trueStdev >= low
isSellLvl = myVwap + 1.5*trueStdev <= high

strategy.order("buy",strategy.long, limit = buyPrice)
0 Answers
Related