Boolean input to negate if statements in pinescript - if-statement

In short I have an indicator that has multiple requirements for setting background colors and bar colors. All of this was fine until I wanted to add a small wrinkle to it.
Basically I have two lines (plots), one of which I call the signal line and the other the baseline, If a value is above one or the other then the background is blue and if it is below then background is red (this also goes for barcolor if people so wish to have bar coloring on). I have two separate boolean inputs for each of these two lines so that the background color or bar color is colored depending on what the user prefers. I also have a boolean for bar colors just when the value crosses up or down one of the two lines, but we'll ignore that to keep this simpler.
One of the two lines I mentioned above is a moving average (signal line) of the values being measured by the indicator. I want to add a boolean input that if true only colors the bars or background IF the signal line is increasing and not if it is decreasing.
So, if value is above signal line or baseline AND signal line is rising then color background blue, and if not, red. The problem I've run into is that regardless of the signal line rising being true, if the indicator value is above the signal or baseline then the background or bars are always going to be colored in those areas. What I want is if the boolean input for the rising signal line is true then it ONLY colors behind those areas where it is true and no other areas. If that makes sense. Problem is it always colors for areas where the indicator value is above the signal/baseline regardless if the signal line is rising or not, even if the boolean for a rising signal line is true, which defeats the purpose of having this rising signal line requirement.
I'm going to add the pertinent code below. If someone could help that would be wonderful. I can't figure out how to make a negation of background colors and bar colors, which it seems is what I need? The only other alternative I can think of (because I'm an awful coder) is to have separate boolean inputs for 'if value is above signal line' and 'if value is above signal line and signal line is rising' and 'if value is above baseline' and 'if value is above baseline and signal line is rising', plus bar coloring and the crossing up or down vs. being simply above or below. This would make for a grand total of 16 boolean inputs, which is insane obviously.
//BAR COLOR AND BACKGROUND COLOR SIGNAL LINE INPUTS
barcolor_signal = input.bool(defval=false, title='Bar Colors', group='Signal Line')
bg_signal = input.bool(defval=false, title='Background Colored', group='Signal Line')
xover_signal = input.bool(false, 'Volatility Advance', group='Signal Line')
xunder_signal = input.bool(false, 'Volatility Decline', group='Signal Line')
//BAR COLOR AND BACKGROUND COLOR BASELINE INPUTS
barcolor_bline = input.bool(defval=true, title='Bar Colors', group='Baseline')
bg_bline = input.bool(defval=false, title='Background Colored', group='Baseline')
xover_bline = input.bool(false, 'Volatility Advance', group='Baseline')
xunder_bline = input.bool(false, 'Volatility Decline', group='Baseline')
////BOOLEAN
signal_rise = input.bool(defval=true, title='Require Signal Line Rising', tooltip='Require the signal line to be rising to highlight increasing volatility.')
For the inputs, the first group is for if the value is above/below or crossing the signal line, the second group is for if the value is above/below or crossing the baseline, and the last input is signal line rising input.
///BACKGROUND AND CANDLE COLORING
sig_rise = signal_rise and signal_line > signal_line[1]
bline_rise = avg_range > baseline
bline_fall = avg_range < baseline
avg_sig_rise = avg_range > signal_line
avg_sig_fall = avg_range < signal_line
bgcolor(bg_bline and bline_rise ? color.new(#445b84, 50) : bg_bline and bline_fall ? color.new(#844444, 100) : na, title='Baseline Background')
bgcolor(sig_rise and bg_bline and bline_rise ? color.new(#445b84, 50) : sig_rise and bg_bline and bline_fall ? color.new(#844444, 100) : na, title='Baseline Background | Signal Line Rising')
bgcolor(bg_signal and avg_sig_rise ? color.new(#445b84, 50) : bg_signal and avg_sig_fall ? color.new(#844444, 100) : na, title='Signal Line Background')
bgcolor(sig_rise and bg_signal and avg_sig_rise ? color.new(#445b84, 50) : sig_rise and bg_signal and avg_sig_fall ? color.new(#844444, 100) : na, title='Signal Line Background | Signal Line Rising')
I'm not adding the code for barcolor because whatever solution there is should work for that too I would think.
You can see in the first line for bgcolor that that is the simplest--if background is true and avg_range is above baseline then COLOR. The one below requires the signal line to be rising, and the two below are if the avg_range is above the signal line.
I need for the first and third lines to be false if the second or fourth are true, OR I need another way to write this.
Appreciate any help with this.

Basically the way you use ternary operators in your bgcolor() is correct.
If those bgs are dependent on each other I'd evaluate first in variables then apply the coloring.
baseLineRising = bg_bline and bline_rise
baseLineFalling = bg_bline and bline_fall
baseLineRisingSigRising = sig_rise and bg_bline and bline_rise
baseLineFallingSigRising = sig_rise and bg_bline and bline_fall
avgSigRising = bg_signal and avg_sig_rise
avgSigFalling = bg_signal and avg_sig_fall
sigRisingAvgRising = sig_rise and bg_signal and avg_sig_rise
sigRisingAvgFalling = sig_rise and bg_signal and avg_sig_fall
bgcolor(baseLineRising ? color.new(#445b84, 50) : baseLineFalling ? color.new(#844444, 100) : na, title='Baseline Background')
bgcolor(baseLineSigRising ? color.new(#445b84, 50) : baseLineFallingSigRising ? color.new(#844444, 100) : na, title='Baseline Background | Signal Line Rising')
bgcolor(avgSigRising ? color.new(#445b84, 50) : avgSigFalling ? color.new(#844444, 100) : na, title='Signal Line Background')
bgcolor(sigRisingAvgRising ? color.new(#445b84, 50) : sigRisingAvgFalling ? color.new(#844444, 100) : na, title='Signal Line Background | Signal Line Rising')
This way you are much more flexible combining your conditions.
Eg.
secondOrForthtrue = baseLineSigRising or baseLineFallingSigRising or sigRisingAvgRising or sigRisingAvgFalling // I assume they are true if they have a coloring at all
bgcolor(baseLineRising and not secondOrForthtrue ? color.new(#445b84, 50) : baseLineFalling and not secondOrForthtrue ? color.new(#844444, 100) : na, title='Baseline Background')

I finally figured out what I needed to do. For me, being a non-coder and not in the tech profession and only having some experience coding in pinescript (the only language I can code in) this took a significant amount of my time, but I'm happy to have figured it out (I can be quite dogged at times).
Essentially instead of trying to declare everything using ternary operators in bgcolor and barcolor (because it won't work), I created some if-else-if conditions that I hoped would allow me to negate a condition that would be true all the time even if a certain other input variable was also true. Basically, if A and B are true, then C. But if input D is also true, then not C, but E. This actually is stated like if A and B and not D are true, then C, else if A, B and D are true then E. The 'not D' part is what I was struggling with using ternary operators (and maybe it's not possible in this way).
//SIGNAL LINE RISING/FALLING
signal_rising = signal_rise and signal_line >= signal_line[1]
signal_falling = signal_rise and signal_line < signal_line[1]
//BACKGROUND CONDITIONS AND COLORING
above_bline = bg_bline and avg_range > baseline
below_bline = bg_bline and avg_range < baseline
above_signal = bg_signal and avg_range > signal_line
below_signal = bg_signal and avg_range < signal_line
AboveBaselineSignalRising = if (signal_rising and above_bline)
color.new(#445b84, 50)
else if (signal_rising and below_bline or signal_falling and below_bline)
color.new(#844444, 100)
AboveBaseline = if (not signal_rise and above_bline)
color.new(#445b84, 50)
else if (not signal_rise and below_bline)
color.new(#844444, 100)
AboveSignalLineSignalRising = if (signal_rising and above_signal)
color.new(#445b84, 50)
else if (signal_rising and below_signal or signal_falling and below_signal)
color.new(#844444, 100)
AboveSignalLine = if (not signal_rise and above_signal)
color.new(#445b84, 50)
else if (not signal_rise and below_signal)
color.new(#844444, 100)
bgcolor(AboveBaselineSignalRising, title='Background | ACBR > Baseline & Signal Rising')
bgcolor(AboveBaseline, title='Background | ACBR > Baseline')
bgcolor(AboveSignalLineSignalRising, title='Background | ACBR > Signal Line & Signal Rising')
bgcolor(AboveSignalLine, title='Background | ACBR > Signal Line')
//BAR COLOR CONDITIONS AND COLORING (ACBR CROSSING ABOVE OR BELOW BASELINE/SIGNAL LINE)
barcolor_xover_bline = xover_bline and ta.crossover(avg_range, baseline)
barcolor_xunder_bline = xunder_bline and ta.crossunder(avg_range, baseline)
barcolor_xover_signal = xover_signal and ta.crossover(avg_range, signal_line)
barcolor_xunder_signal = xunder_signal and ta.crossunder(avg_range, signal_line)
BarColorBaselineCrossSignalRising = if (signal_rising and barcolor_xover_bline)
#848044
else if (barcolor_xunder_bline)
#5a4484
BarColorBaselineCross = if (not signal_rise and barcolor_xover_bline)
#848044
else if (not signal_rise and barcolor_xunder_bline)
#5a4484
BarColorSignalLineCrossSignalRising = if (signal_rising and barcolor_xover_signal)
#848044
else if (barcolor_xunder_signal)
#5a4484
BarColorSignalLineCross = if (not signal_rise and barcolor_xover_signal)
#848044
else if (not signal_rise and barcolor_xunder_signal)
#5a4484
barcolor(BarColorBaselineCrossSignalRising, title='Bar Color | ACBR Baseline Cross & Signal Rising')
barcolor(BarColorBaselineCross, title='Bar Color | ACBR Baseline Cross ')
barcolor(BarColorSignalLineCrossSignalRising, title='Bar Color | ACBR Signal Line Cross & Signal Rising')
barcolor(BarColorSignalLineCross, title='Bar Color | ACBR Signal Line Cross')
//BAR COLOR CONDITIONS AND COLORING (ACBR ABOVE OR BELOW BASELINE/SIGNAL LINE)
barcolor_above_bline = barcolor_bline and avg_range > baseline
barcolor_below_bline = barcolor_bline and avg_range < baseline
barcolor_above_signal = barcolor_signal and avg_range > signal_line
barcolor_below_signal = barcolor_signal and avg_range < signal_line
BarColorAboveBaselineSignalRising = if (signal_rising and barcolor_above_bline)
color.new(#445b84, 0)
else if (signal_rising and barcolor_below_bline or signal_falling and barcolor_above_bline or signal_falling and barcolor_below_bline)
color.new(#844444, 0)
BarColorAboveBaseline = if (not signal_rise and barcolor_above_bline)
color.new(#445b84, 0)
else if (not signal_rise and barcolor_below_bline)
color.new(#844444, 0)
BarColorAboveSignalLineSignalRising = if (signal_rising and barcolor_above_signal)
color.new(#445b84, 0)
else if (signal_rising and barcolor_below_signal or signal_falling and barcolor_above_signal or signal_falling and barcolor_below_signal)
color.new(#844444, 0)
BarColorAboveSignalLine = if (not signal_rise and barcolor_above_signal)
color.new(#445b84, 0)
else if (not signal_rise and barcolor_below_signal)
color.new(#844444, 0)
barcolor(BarColorAboveBaselineSignalRising, title='Bar Color | ACBR > Baseline & Signal Rising')
barcolor(BarColorAboveBaseline, title='Bar Color | ACBR > Baseline')
barcolor(BarColorAboveSignalLineSignalRising, title='Bar Color | ACBR > Signal Line & Signal Rising')
barcolor(BarColorAboveSignalLine, title='Bar Color | ACBR > Signal Line')

Related

Can Pinescript do this?

thanks for any help. I'm new to coding. I was wondering if this is something Pinescript can achieve? The code below is not meant to be accurate at all. I'm including it to hopefully give you an idea of what I want to code. It would be a series of if/then statements piled on top of each other with the end result being a simple green or red background. Not sure if a ternary condition, function or if statement should be used.
A = if ( dataA > 0 )
green
else
red
B = if ( dataB > 0 )
green
else
red
C = if ( A = green and B = green )
bgcolor(color=color.green)
D = if ( A = red and B = red )
bgcolor(color=color.red)
You can create a color variable and set its value with the ternary operator.
color c1 = dataA > 0 ? color.green : color.red
bgcolor(c1)
Or you can directly apply your condition in the bgcolor() function.
bgcolor(dataB > 0 ? color.green : color.red)

Pinescript. Plotting conditional statement

If the variable barup is true, I want it to plot one series; if the variable bardown is true, I want it to plot another series value.
My current code yields the error: Cannot use "plot in local scope".
How do I change the following code to make the indicator show the number of days the lows have been above the 30 ema or below the 30 day ema based on the high or low of the current day.
Here is the code I have now:
indicator("LandryLight")
bardown = high < ta.ema(close,30)
barup = low > ta.ema(close,30)
if barup
plot(series=ta.barssince(barup)*-1, title="Consecutive Bars Down", color=color.red, style=plot.style_histogram, linewidth=2)
if bardown
plot(series=ta.barssince(bardown), title="Consecutive Bars Up", color=color.green, style=plot.style_histogram, linewidth=2)
hline(10,title="Threshold", color=color.white, linestyle=hline.style_dashed, linewidth=1)
First Use tag [pine-script]
Try going step by step, and then the plot
I would do it like this:
//#version=5
indicator("LandryLight")
bardown = high < ta.ema(close,30)
barup = low > ta.ema(close,30)
barupCont = ta.barssince(barup)*-1
bardownCont = ta.barssince(bardown)
barupOK = barup ? barupCont : na
bardownOK = bardown ? bardownCont : na
plot(series= barupOK, title="Consecutive Bars Down", color=color.red, style=plot.style_histogram, linewidth=2)
plot(series= bardownOK, title="Consecutive Bars Up", color=color.green, style=plot.style_histogram, linewidth=2)
hline(10,title="Threshold", color=color.white, linestyle=hline.style_dashed, linewidth=1)

Nested if statement in pine script

I'm trying to build a ema script in trading view but struggling with how to finish up the code. I'm essentially trying to code this, but not sure how to nest this in an if statement:
(tl <= em1 and tc > ema2) and ((tc<ema3) or (tc<em4) or (tc<em5))
How can I put a nested if statement for this? Goal is to use the if statement to tie in the rest of the code
// EMA trap
m1=8
m2=3.1
m3=3.2
m4=3.4
tl=low
tc=close
em1 = ema(tl,m1)
em2 = ema(tc,m1)
em3 = ema(tc,m2)
em4 = ema(tc,m3)
em5 = ema(tc,m4)```
You can't use float periods for ema(), so replaced them with integers.
This plots an arrow on the chart when your condition is true:
//#version=4
study("", "", true)
// EMA trap
m1=8
m2=3
m3=4
m4=5
tl=low
tc=close
em1 = ema(tl,m1)
em2 = ema(tc,m1)
em3 = ema(tc,m2)
em4 = ema(tc,m3)
em5 = ema(tc,m4)
cond = tl <= em1 and tc > em2 and (tc < em3 or tc < em4 or tc < em5)
plotchar(cond, "cond", "▼", location.top)

Pine Script for Trading View: How to display on certain time frames

Could you kindly teach me how to not show the vertical line for timeframe of more than or equal to 1 Hour?
I desire to show the vertical lines (when the market opens) .
There is a difficulty using the iff statement alongside with the use of the likes of isIntraday and cannot compile.
Thank you in advance.
//#version=2
study("Line", overlay=true)
t2 = time(period, "1800-1801")
t1 = time(period, "0300-0301")
t3 = time(period, "0930-0931")
Open2 = na(t2) ? na : blue
Open1 = na(t1) ? na : green
Open3 = na(t3) ? na : green
This will show when the chart's TF is >= 60min. You can use this condition to build your display conditions:
//#version=2
study("")
tf60AndMore = not (isseconds or (isintraday and interval < 60))
plotchar(tf60AndMore, "tf60AndMore", "•", location.top)

show navigation in a graph in R

I am trying to show navigation in R plot. The current status in time one or (t1) is set as val$currentstatus and next status in (t2) wants to be shown in the graph based on the action that the user choose from the checkbook. then I want to draw a line to show this path. The code that I wrote is as following
output$navigation<-renderPlot({
#initial state of X and Y
if(is.element("Within", vals$currentstatus))
x <- 1
y <- 2
if(is.element("Out", vals$currentstatus)) {
x <- 1
y <- 1
}
action<-c(input$action1,input$action2)
x<-1:4
y<-1:2
rewards<-matrix(rep(0,8),nrow=2)
rewards[1,4]<- -1
rewards[2,4]<- 1
values<-rewards#initial Values
states<-expand.grid(x=x,y=y)
#Transition probability
transition <- list( input$action1= c("within" = 0.8, "out" = .2),
input$action2= c("within" = 0.3, "out" = .7))
# The value of an action (e.g. move toward benchmark )
action.values <- list(input$action1 = c("x" = 1, "y" = 0),
input$action1 = c("x" = 1, "y" = 0))
# act() function serves to move the agent to go to new position
act <- function(action, state) {
action.value <- action.values[[action]]
new.state <- state
#
if(state["x"] == 4 && state["y"] == 1 || (state["x"] == 4 && state["y"] == 2))
return(state)
#
new.x = state["x"] + action.value["x"]
new.y=if(transition["within">"out"]){state["y"==2]}
if(transition["within"<"out"]){state["y"==1]}
}
plot(x, y, xaxt='n',yaxt='n',cex=10,pch=19,
col=ifelse(y==1,"red","green"),ylab="status",xlab="period",
xlim=c(0,4), ylim=c(0,3))
axis(1,at=1:4,labels=c("t1","t2","t3","t4"))
axis(2,at=1:2,labels=c("out bench","within bench"))
if next position is within bench it should be green and connect to the previous state and if it is out of bench should be red and connect to previous state. Also I want to see the name of chosen action on the connection line between two states.Moreover I want to know how can I update the new position and use it for calculating next state in next period (t3) and so force.Similar to the following graph: