简体   繁体   中英

Pinescript: Can I turn on/off a plot series based on a value derived from just the current bar

Problem:

  • I have two moving average ema1, ema2
  • If ema1 is greater than ema2 I only want to show ema1 and its historical values and hide the other.
  • If ema1 is less than ema2 I only want to show ema2 and its historical values and hide the other.

I've tried countless approaches but having zero joy.



//@version=4
study("Line test")

ema1 = ema(close,5)
ema2 = ema(close,10)

var plot_ema_1 = false
var plot_ema_2 = false

if ema1[1] > ema2[1]
    plot_ema_1 := true
    plot_ema_2 := false

else
    plot_ema_1 := false
    plot_ema_2 := true  

plot(plot_ema_1 ? ema1 : na, color=color.blue, title="EMA-1", style=plot.style_line)
plot(plot_ema_2 ? ema2 : na, color=color.orange, title="EMA-2", style=plot.style_line)

Picture of problem

My real life usage is a little trickier I've realised. There is actually a third/fourth variable.. correlation_to_asset1 and correlation_to_asset2 (these are 2 separate correlation coefficients).

The condition I'm looking to satisfy is

if (correlation_to_asset1 > correlation_to_asset2)
    display_ema1_and_all_its_historical_data 

   // ema2 needs to be completely turned off. A combined line doesn't 
   // work as it messes with the scaling.

else
    display_ema2_and_all_its_historical_data

   // ema1 needs to be completely turned off. A combined line doesn't 
   // work as it messes with the scaling.

Any insights on this would be greatly appreciated. We can use ema3/ema4 as the 3rd/4th variable...I just wanted to introduce some context with the mention of the cc.

This shows 3 different methods of doing it. We prefer method #1:

//@version=4
study("Line test", "", true)

ema1 = ema(close,5)
ema2 = ema(close,10)

// ————— v1: plot the maximum of the 2 emas.
plotEma1 = ema1[1] > ema2[1]
c = plotEma1 ? color.blue : color.orange
mx = max(ema1, ema2)
plot(mx, color=c, title="EMA", style=plot.style_line)
plotchar(plotEma1 != plotEma1[1] ? mx : na, "Dot", "•", location.absolute, c, size = size.tiny)

// var plot_ema_1 = false
// var plot_ema_2 = false

// if ema1[1] > ema2[1]
//     plot_ema_1 := true
//     plot_ema_2 := false

// else
//     plot_ema_1 := false
//     plot_ema_2 := true  

// ————— v2: plot `na` color when the line isn't needed.
// plot(ema1, color=plot_ema_1 ? color.blue : na, title="EMA-1", style=plot.style_line)
// plot(ema2, color=plot_ema_2 ? color.orange : na, title="EMA-2", style=plot.style_line)

// ————— v3: plot using linebreak style.
// plot(plot_ema_1 ? ema1 : na, color=color.blue, title="EMA-1", style=plot.style_linebr)
// plot(plot_ema_2 ? ema2 : na, color=color.orange, title="EMA-2", style=plot.style_linebr)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM