Reputation: 121
Here is my idea for this script. I find the number of candles between the swing low and the swing high, and that becomes the period for my EMA. (I have a starting candle for the lookback period of course)
I need to get the value for the EMA[0], but that seems not to be possible with basic functions, so I wrote mine. I used the basic equation found on the internet, still my calculations are not correct. Always wrong by 0.001 or more.
Here's the code.
lookbackPeriod = (1440) // 24hrs
var timeframA = 1
period = timeframe.period
numOfCandles = lookbackPeriod/timeframA // numOfCandles is a number of candles to look back into the past
var lastLabel1 = label.new(bar_index-numOfCandles,high[numOfCandles],text="")
var lastLabel2 = label.new(bar_index-numOfCandles,high[numOfCandles],text="")
var lastLabel3 = label.new(bar_index-numOfCandles,high[numOfCandles],text="")
var lastLabel4 = label.new(bar_index-numOfCandles,high[numOfCandles],text="")
var lastLabel5 = label.new(bar_index-numOfCandles,high[numOfCandles],text="")
pine_ema(src,time_period) =>
alpha = 2 / (time_period + 1)
ema = 0.0
ema := alpha * src + (1 - alpha) * nz(ema[1])
ema
Ema(src,p) =>
ema = 0.
sf = 2/(p+1)
ema := nz(ema[1] + sf*(src - ema[1]),src)
if barstate.islast == true
var HH = high[0]
var LL = low[0]
var HHcandleNum = 0
var LLcandleNum = 0
for i = 1 to numOfCandles
if high[i] > HH
HH:=high[i],
HHcandleNum := i
if low[i] < LL
LL:=low[i],
LLcandleNum := i
if label.get_text(lastLabel1)!=""
label.delete(lastLabel1)
if label.get_text(lastLabel2)!=""
label.delete(lastLabel2)
if label.get_text(lastLabel3)!=""
label.delete(lastLabel3)
if label.get_text(lastLabel4)!=""
label.delete(lastLabel4)
if label.get_text(lastLabel5)!=""
label.delete(lastLabel5)
lastLabel1 := label.new(bar_index-numOfCandles,high[numOfCandles],text="start") // print the start of the lookback period
lastLabel2 := label.new(bar_index-HHcandleNum,high[HHcandleNum],text="HH") // print the HH
lastLabel3 := label.new(bar_index-LLcandleNum,low[LLcandleNum],text="LL") // print the LL
int num = abs(HHcandleNum-LLcandleNum)[0]
float sum = 0
for j = 0 to num-1
sum := sum + float(close[j])
sma = sum/num
lastLabel5 := label.new(bar_index-4,high[4],text = tostring(num))
float value = 0
float before_value = close[num]
smoothing = 2/(1+num)
for i = num-1 to 0
value := close[i]*smoothing + before_value*(1-smoothing)
before_value := value
value := round(value,5)
lastLabel4 := label.new(bar_index,high[0],text = tostring(value)) // print ema value on last candle
Try it on your chart, (1min timeframe because I removed some code for other tf's) and you'll see what I mean.
Thanks in advance!
Upvotes: 0
Views: 352
Reputation: 21
nice idea. You could change the label of the HH and LL only if they are broken and not with each new bar. You could also plot your EMA (period obtained from the number of candles between high and low)
Upvotes: 1