'If Toggle Enabled, Display EMA50

have a very simple script and I'm just trying to enable a toggle and cant seem to get it to work.

Heres the toggle

toggleEma50 = input.bool(true, title = "EMA50", group=g1)

Heres the working EMA50 pinescript:

ema50 = ta.ema(close, 50)
plot(ema50, color=#3179f5, title='EMA50: ', linewidth=1)

What I've Tried so far

Attempt 1: (Error:line 381: Cannot use 'plot' in local scope.)

ema50 = ta.ema(close, 50)
if toggleEma50
    plot(ema50, color=#3179f5, title='EMA50: ', linewidth=1)

Attempt 2: (Error: line 381: Cannot call 'plot' with argument 'series'='emaAndToggle'. An argument of 'series bool' type was used but a 'series float' is expected )

ema50 = ta.ema(close, 50)
emaAndToggle = ema50 and toggleEma50
plot(emaAndToggle, color=#3179f5, title='EMA50: ', linewidth=1)

Out of any ideas of what to try.. can anyone help?



Solution 1:[1]

You can use your bool input in a ternary statement to set the plot to either your ema, or to na when not in use. We can make the ternary statement right in the series argument slot int the plot() call like this:

toggleEma50 = input.bool(true, title = "EMA50", group=g1)

ema50 = ta.ema(close, 50)
plot(toggleEma50 ? ema50 : na, color=#3179f5, title='EMA50: ', linewidth=1)

plot() can not be used in local scope, so we must manipulate the value, rather than the function itself.

Cheers and all the best

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bjorgum