Compare bool and float to determine plot (pine script v5) - boolean

You folks helped me with another part of this script and I'm making good progress. However, I'm stuck again.
I added a code to produce a dynamic overbought/oversold line on the indicator. That part works great. Now, I'm wanting to add a plotshape when conditions are met to signal long or short. Unfortunately, I can't figure out how to compare a bool variable and a float variable. The dynamic OB/OS lines are floats. The crossover lines are bool.
What I want is for the (green/long) shape to plot when a crossover happens below the dynamic oversold line and the (red/short) shape to plot when the crossunder happens above the dynamic overbought line.
I've tried all kinds of things (var, loop with "while" using sb value as a trigger). I either break the code or I get every crossover plotted. Here is what I have that is stable. I took all my junk that didn't work out:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HammerGeek
//#version=5
indicator('Impulse MACD [HammerGeek - LazyBear]', shorttitle='IMACD_HG_LB', overlay=false)
lengthMA = input(34)
lengthSignal = input(9)
//OverBought = input.float(0.1)
//OverSold = input.float(-0.1)
calc_smma(src, len) =>
smma = 0.0
sma_1 = ta.sma(src, len)
smma := na(smma[1]) ? sma_1 : (smma[1] * (len - 1) + src) / len
smma
calc_zlema(src, length) =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
d = ema1 - ema2
ema1 + d
src = hlc3
hi = calc_smma(high, lengthMA)
lo = calc_smma(low, lengthMA)
mi = calc_zlema(src, lengthMA)
md = mi > hi ? mi - hi : mi < lo ? mi - lo : 0
sb = ta.sma(md, lengthSignal)
sh = md - sb
mda = ta.sma(md, lengthSignal)
OverBoughtLine = ta.highest(sb * 0.5, lengthMA*100)
OverSoldLine = ta.lowest(sb * 0.5, lengthSignal*100)
shsbCrossOver = ta.crossover(md, sb)
shsbCrossUnder = ta.crossunder(md, sb)
//mdc = src > mi ? src > hi ? color.lime : color.green : src < lo ? color.red : color.orange
mdc = color.green
plot(0, color=color.new(color.gray, 0), linewidth=1, title='MidLine')
plot(md, color=mdc, linewidth=2, title='ImpulseMACD', style=plot.style_line)
plot(sh, color=color.rgb(122, 5, 168, 40), linewidth=2, title='ImpulseHisto', style=plot.style_area)
plot(sb, color=color.rgb(255, 255, 255, transp = 40), linewidth=2, title='ImpulseMACDCDSignal')
plot(OverBoughtLine, color=color.new(#f3e032, 0), linewidth=1, title = 'Overbought Line')
plot(OverSoldLine, color=color.new(color.yellow, 0), linewidth=1, title = 'Oversold Line')
plotshape(shsbCrossOver, "LONG", shape.triangleup, location.bottom, color.new(color.green, 0))
plotshape(shsbCrossUnder, "SHORT", shape.triangledown, location.top, color.new(#cd0808, 0))
//ebc = input(false, title='Enable bar colors')
//barcolor(ebc ? mdc : na)

You cannot compare a bool with a float. It doesn't make any sense and it is not legal in pinescript.
What I want is for the (green/long) shape to plot when a crossover
happens below the dynamic oversold line and the (red/short) shape to
plot when the crossunder happens above the dynamic overbought line.
You want to check if the values you use in that crossover is under your dynamic oversold line at the time of crossover.
OverSoldLine = ta.lowest(sb * 0.5, lengthSignal*100)
shsbCrossOver = ta.crossover(md, sb)
is_good = shsbCrossOver and (md < OverSoldLine) and (sb < OverSoldLine)

Related

Pine Script V5 - Not getting expected breakout entry price and entry in expected bar

I have a long entry buy condition where
Candle time frame is 15 minutes
Alert candle high is below lower band of bollinger bands.
entry when next candle crossover the alert candle high
This script gives entry oh high breakout + 0.01 but it does not give entry in the exact breakout candle and gives entry when price comes next time on expected entry price i.e. alert candle high + 0.01.
Requesting solution to get entry in breakout candle itself and at expected breakout price.
//#version=5
strategy("Bands Reversion", overlay=true, calc_on_every_tick=true)
//// Indicator Bollinger Bands
source = close
length = input.int(20, minval=1)
mult = input.float(1.5, minval=0.001, maxval=50)
direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
plot(basis, color = color.red)
plot(upper)
plot(lower)
/// Trade entry time and squareoff time
TradeTime = input(title="Trade Timings",defval="0930-1130")
SqoffTime = input(title="Squareoff Timings",defval="1530-1545")
Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0
Insession = Barsinsession(TradeTime) ? 1 : 0
endofsession = Insession == 0 and Insession[1] == 1
Sqsession = Barsinsession(SqoffTime) ? 1 : 0
SqTime = Sqsession == 1 and Sqsession[1] == 0
//// Input control and conditions
buy_condition = high[1] < lower[1] and ta.crossover(high, high[1]) and Insession
short_condition = low[1] > upper[1] and ta.crossunder(low, low[1]) and Insession
buy_alert_high = ta.valuewhen(buy_condition, high[1],0)
buy_alert_low = ta.valuewhen(buy_condition, low[1],0)
short_alert_low = ta.valuewhen(short_condition, low[1],0)
short_alert_high = ta.valuewhen(short_condition, high[1],0)
buy_alert_high1 = ta.valuewhen(buy_condition, high,0)
plot(buy_alert_high, style = plot.style_circles)
plot(buy_alert_low, style = plot.style_circles, offset = -2)
plot(short_alert_low, style = plot.style_circles)
plot(short_alert_high, style = plot.style_circles)
sell = ta.crossunder(close, low) or SqTime //// or SqTime if for intraday exit
cover = ta.crossover(close,high) or SqTime //// or SqTime if for intraday exit
plotshape(buy_condition, style = shape.triangleup, location = location.belowbar, color = color.green, text = "BUY")
plotshape(short_condition, style = shape.triangledown, location = location.abovebar, color = color.red, text = "SHORT")
long_price = ta.valuewhen(buy_condition, (buy_alert_high + 0.01),0 )
longstop = buy_alert_low - 0.01
longtgt = basis
short_price = ta.valuewhen(short_condition,short_alert_low - 0.01,0) ////short_alert_low - (0.01 * 100 * syminfo.mintick) //// ta.valuewhen(short_condition,short_alert_low - 0.01,0)
shortstop = short_alert_high + 0.01
shorttgt = basis
strategy.entry("long",direction = strategy.long, when = buy_condition, limit = long_price, comment ="BUY")
strategy.close("long", when = sell, comment = "SELL")
strategy.exit("long", from_entry = "long", stop = longstop, limit = longtgt, comment = "TG/SL_EXIT")
strategy.entry("short",direction = strategy.short, when = short_condition,limit = short_price, comment ="SHORT")
strategy.close("short", when = cover, comment = "COVER")
strategy.exit("short", from_entry = "short", stop = shortstop, limit = shorttgt, comment = "TG/SL_EXIT")
plot(strategy.position_size > 0 ? longstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size > 0 ? longtgt : na, style = plot.style_linebr, color = color.green)
plot(strategy.position_size < 0 ? shortstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size < 0 ? shorttgt : na, style = plot.style_linebr, color = color.green)

Strategy ATR TP/SL target doesn't stay 'locked' to my entry readings

I want a strategy to Take Profit/Stop Loss to be based on the ATR (plus multiplier). However, I want it to be whatever the readings were at the point of entry, not simply the last candle (which is what it seems to be doing). Weird thing is that I have other strategies that use this approach, and they seem fine, so I'm really stumped by what I'm doing wrong.
Any help would be much appreciated!
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dave-browning
//#version=5
strategy("Dead-Cat Bounce", overlay = true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, currency = currency.GBP, commission_value = 0.05, use_bar_magnifier = true)
trendEMAlength = input.int(130, "Trend EMA Length")
fastSMALength = input.int(14, "Fast SMA Length")
tpATRmultiplyer = input.float(6.2, "Short TP ATR Multiplier")
slATRmultiplier = input.float(4, "Short SL ATR Multiplier")
//Trade Conditions
shortCondition = close > ta.sma(close, fastSMALength) and close < ta.ema(close, length=trendEMAlength)
notInTrade = strategy.position_size <= 0
atr = ta.atr(14)
ema=ta.ema(close, trendEMAlength)
plot(ta.sma(close,length=fastSMALength), color=color.blue, linewidth = 2)
plot(ta.ema(close, length=trendEMAlength), color=color.yellow, linewidth = 4)
plot(low - (atr * tpATRmultiplyer), color=color.green)
plot(high + (atr * slATRmultiplier), color=color.red)
if shortCondition and notInTrade
stopLoss = (high + (atr * slATRmultiplier))
takeProfit = (low - (atr * tpATRmultiplyer))
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", "Short", limit=takeProfit, stop=stopLoss)

draw line and color the area above in indicator in Trading View with Pine Script

I want to draw a horizontal line at fixed value 30.000 and color the area above in light green in the DMI Indicator. How is this possible?
Thanks
//#version=5
indicator(title="Directional Movement Index", shorttitle="DMI", format=format.price, precision=4, timeframe="", timeframe_gaps=true)
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
plot(adx, color=#F50057, title="ADX")
plot(plus, color=#2962FF, title="+DI")
plot(minus, color=#FF6D00, title="-DI")
You can use the hline and fill functions
https://www.tradingview.com/pine-script-reference/v5/#fun_fill
https://www.tradingview.com/pine-script-reference/v5/#fun_hline
hline(30, title = "30 Line", color=color.blue, linestyle=hline.style_solid, linewidth=2)
fill(30, 100, color = color.new(color.green, 90))

Code not plotting - Function should be called on each calculation for consistency. It is recommended to extract the call from this scope"

I am getting this as an orange error - not sure what I have done wrong or whether this error is the reason that the code doesn't plot. I am brand new to Pine-script and any assistance would be invaluable. Many thanks in advance Alastair
//#version=5
indicator("PCY TEST4")
//Get User Inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
//Variables
a = 0.33
PCY = 0.0
PCYi = 0.0
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
minMacd=0.0
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
//maxMacd = ta.min(macd)
//minMacd = ta.max(macd)
//signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
//hist = macd - signal
delta = maxMacd-(fast_ma - slow_ma)/(maxMacd -minMacd)
for i = 0 to (signal_length)
PCYi := a*((delta - PCYi[1])+PCYi[1])
PCYi
//Plotting
plot(PCYi)
I think it's because you're calculating the min/max in a for loop
Those functions should (not mandatory but strongly recommended) be calculated at every candle instead
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
If you want to calculate the min/max over a X period of time, maybe use the ta.highest/ta.lowest functions instead :)
And of course, those 2 should be called at every candle (i.e. not in a if, for,... statement)

TRADE open and close in the same time

in the following strategy all time (trades) open and close in the same time, so I pay only fees.
I have written to tradingview assistance, they have said me (and send) to put OPEN LONG and CLOSE LONG (the first 2 lines in strategy).
But I still have the same problem, I don't know why.
All test are ok, I think that problem is with TRAIDINGVIEW HUB, but I am not scure.
Thanks for your attention and time
strategy V5
Open Long:
{"pair":"BTCUSDT","unitsPercent":"50","unitsType":"percentWallet","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isBuy":true,"isMarket":false,"leverage":"5","marginType":"ISOLATED","closeCurrentPosition":true,"delay":"10"}
Close Long:
{"pair":"BTCUSDT","unitsPercent":"50","exchange":"Bybit","apiKey":"TradingView BYBIT ACC AFF","token":"7dfa66d6-5b94-4047-a11c-e8bdd0f1c0f4","isClose":true,"delay":"10"}
strategy(title='Take profit (% of instrument price)', overlay=true, pyramiding=1)
// STEP 1:
// Make inputs that set the take profit % (optional)
FastPeriod = input.int(title='Fast MA Period', defval=18, minval=1, group='Moving Average')
SlowPeriod = input.int(title='Slow MA Period', defval=20, minval=1, group='Moving Average')
TPPerc = input.float(title='Long Take Profit (%)', minval=0.0, step=0.5, defval=0.9, group='TP & SL')
SLPerc = input.float(title='Long Stop Loss (%)', minval=0.0, step=0.1, defval=4, group='TP & SL')
TP_Ratio = input.float(title='Sell Postion Size % # TP', defval=100, step=1, group='TP & SL', tooltip='Example: 100 closing 100% of the position once TP is reached') / 100
// Calculate moving averages
fastSMA = ta.sma(close, FastPeriod)
slowSMA = ta.sma(close, SlowPeriod)
// Calculate trading conditions
enterLong = ta.crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=color.new(color.green, 0), title='Fase MA')
plot(series=slowSMA, color=color.new(color.red, 0), title='Slow MA')
// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? (pcnt / 100.0 + 2.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
TP = strategy.position_avg_price + percentAsPoints(TPPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
// Submit entry orders
if enterLong
strategy.entry(id='Long', direction=strategy.long)
// STEP 3:
// Submit exit orders based on take profit price
if strategy.position_size > 0
strategy.exit('TP', from_entry='Long', qty=initial_position_size * TP_Ratio, limit=TP, stop=SL)
// Plot take profit values for confirmation
plot(series=strategy.position_size > 0 ? TP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=1, title='Take Profit 1')
plot(series=strategy.position_size > 0 ? SL : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=1, title='Stop Loss')