edward
edward

Reputation: 646

How to get the highest value between 2 points?

I want to get the highest point between 2 entries (ex. between 2 ema crosses, like the image example). It's over my head, I tried with barssince() without luck. Any help would be welcomed!

//@version=4
study("My Script", overlay = true)

ema1 = ema(close, 20)
ema2 = ema(close, 50)
plot(ema1)
plot(ema2, color = color.yellow)

buy = crossover(ema1, ema2)
sell = crossunder(ema1, ema2)

highest_buy = highestbars(high, barssince(buy))

plot(highest_buy)

enter image description here

Upvotes: 1

Views: 1009

Answers (2)

AnyDozer
AnyDozer

Reputation: 2568

When sell signal appears highest_buy is equal na and the label is not displayed. It is necessary to take the values on the previous bar.

//@version=4

study("Help prof (My Script)", overlay = true)

var bool    track       = false
var float   highest_buy = na

ema1 = ema(close, 20)
ema2 = ema(close, 50)

buy  = crossover(ema1, ema2)
sell = crossunder(ema1, ema2)

if buy
    track := true
else if sell
    track := false

highest_buy := track ? max(nz(highest_buy), high) : na

plot(ema1)
plot(ema2,        color=color.yellow)
plot(highest_buy, color=color.purple, style=plot.style_linebr)

buy_entry = valuewhen(buy, close, 0)
plot(buy_entry, color = buy_entry == buy_entry[1] and ema1 > ema2? color.lime :na)

if sell 
    label1 = label.new(bar_index, highest_buy[1], text=tostring(highest_buy[1] - buy_entry[1]) , style=label.style_label_down, color=color.black, textcolor=color.white)

enter image description here

Upvotes: 2

Bjorn Mistiaen
Bjorn Mistiaen

Reputation: 6905

Continuous plot:

//@version=4
study("My Script", overlay = true)

var bool    track       = false
var float   highest_buy = na

ema1 = ema(close, 20)
ema2 = ema(close, 50)

buy  = crossover(ema1, ema2)
sell = crossunder(ema1, ema2)

if buy
    track := true
else if sell
    track := false

highest_buy := track ? max(nz(highest_buy), high) : na

plot(ema1)
plot(ema2,        color=color.yellow)
plot(highest_buy, color=color.purple, style=plot.style_linebr)

Plot latest occurrence only:

//@version=4
study("My Script", overlay = true)

var bool    track       = false
var float   highest_buy = na
var int     bar_buy     = na
var int     bar_sell    = na
var line    hline       = line.new(na, na, na, na, extend=extend.both, color=color.purple)

ema1 = ema(close, 20)
ema2 = ema(close, 50)

buy  = crossover(ema1, ema2)
sell = crossunder(ema1, ema2)

if buy
    track := true
    bar_buy := bar_index

highest_buy := track ? max(nz(highest_buy), high) : na

if sell
    track := false
    bar_sell := bar_index
    line.set_xy1(hline, bar_buy,  highest_buy)
    line.set_xy2(hline, bar_sell, highest_buy)


plot(ema1)
plot(ema2,        color=color.yellow)

bgcolor(buy  ? color.green : na, transp=80)
bgcolor(sell ? color.red   : na, transp=80)

Upvotes: 1

Related Questions