Tradingview Pinescript alert not working as expected - charts

I am using below pinescript and i am not getting alerts as expected. I am aware that it is a repainting script. It is working fine with the back testing.
Long alert is set to "Once per bar close" and short alert is set to "once per bar".
The unexpected behavior is
1) Few times, i am getting short alert though there is no corresponding long alert (though i have taken care in my script, short alert will be sent only when there is a long).
2) Multiple consecutive Short alerts per bar. I am aware that in the realtime bar, the short condition may be true multiple number of times. But since i have set alert to "once per bar", the alert should come only for the first time short condition becomes true.
Please can you let me know if i am doing anything wrong ?
Thanks in advance.
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2020, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
firstrun = true
bought = false
longcondition = false
shortcondition = false
//Just to track first run
firstrun := firstrun[1]
if (firstrun == false)
bought := bought[1]
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
alertcondition(longcondition, "Long", "Long")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
if (longcondition)
longcondition :=false
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(shortcondition, "short", "short")
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
if (shortcondition)
shortcondition :=false
plotchar(bought, "bought", "", location = location.top)
firstrun := false

You bought variable now automatically saves its value bar to bar and I have removed the late reinitializations of vars in your script. Seems to be working fine here:
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2000, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
var bought = false
longcondition = false
shortcondition = false
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(longcondition, "Long", "Long")
alertcondition(shortcondition, "short", "short")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
// For debugging.
plotchar(bought, "bought", "•", location = location.top)

if buy signal is generated continuously for two sessions, then it will not appear till sell signal is generated.

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)

Plotshape and label

In below code, I am getting syntax error for plotshape and several for label. Even for max / min i am getting too many arguments. I used label to get the value from intraburst formula as text. Will need help to resolve these.
//#version=4
study("Intraburst", overlay=true)
truemove = abs(open[2] - close) dayTrueHigh = max(high[1], high,
close[2]) dayTrueLow = min(low[1], low, close[2]) dayTrueRange =
dayTrueHigh - dayTrueLow intraburstLevel = truemove / dayTrueRange *
100
if intraburstLevel > 30
plotshape(series=intraburstLevel, text="ON", style=shape.circle, location=location.abovebar, color=color.green, size=size.normal) else
plotshape(series=intraburstLevel, text="OFF", style=shape.circle, location=location.abovebar, color=color.red, size=size.normal)
label = label.new(bar_index=0, yloc=y_top, xloc=xloc.bar_index,
text=tostring(intraburstLevel, "0.00"), size=size.large,
color=color.black) label.location = location.top label.y = y_top
label.x = x_right label.text = tostring(intraburstLevel, "0.00")
In series, use a ternary
Something like that:
plotshape(
intraburstLevel > 30 ? intraburstLevel : na,
text = "ON",
style = shape.circle,
location = location.abovebar,
color = color.green,
size = size.normal)
plotshape(
intraburstLevel <= 30 ? intraburstLevel : na,
text = "OFF",
style = shape.circle,
location = location.abovebar,
color = color.red,
size = size.normal)
and the label
label.new(
bar_index,
close,
tostring (intraburstLevel, "##.00"),
color = color.black,
textcolor = color.white)

Looking for current price > previous day high . Works fine but plotting for all the 5 minutes candle

Here is my usecase :
if currentprice of 5 minutes candle is greater than previous day high , plot the chart with the 'x' mark in green .
If currentprice of 5 minutes candle is lesser than previous day low , plot the chart with 'x' mark in green
This script prints the 'x' mark for every 5 minutes but I want to plot only first for the first time when condition is met
I used a counter to check if it is a new day but seems that is not working as expected
//#version=5
indicator("HLPrice", max_lines_count = 11, overlay=true)
emaValue8 = ta.ema(close,8)
emaValue21 = ta.ema(close,21)
vwapValue = ta.vwap(hlc3)
// to highlight the session
timeframe = "1D"
isNewDay = timeframe.change(timeframe)
bgcolor(isNewDay ? color.new(color.green, 80) : na)
[dh,dl,dc] = request.security(syminfo.ticker, "D", [high[1],low[1], close[1]], lookahead=barmerge.lookahead_on)
isNewDayy = time("D") != time("D")[1]
var plotcond = false
greaterThanPreviousDayHigh = false
lesserThanPreviousDayLow = false
if isNewDayy
plotcond := true
if close[0] > dh and plotcond
greaterThanPreviousDayHigh:=true
if close[0] < dl and plotcond
lesserThanPreviousDayLow:=true
plotshape(series=greaterThanPreviousDayHigh , title="Candle on All EMAs" ,color = color.green, size=size.tiny)
plotshape(series=lesserThanPreviousDayLow , title="Candle on All EMAs" ,color = color.red, size=size.tiny)

Buy and sell-markers on lower time frames when longer time frame shows uptrend

So, I'm trying to run a trading bot on medium timeframes (1h - 4h) using the KDJ-indicator. I know it's not the most responsive indicator but it is very reliable, at least on higher time frames (8h - 1D).
What I would like to be able to do is use the following script to send BUY/SELL-signals to my bot, BUT ONLY when the asset is not trending down on the 1D-chart. In other words, I would like to run this script:
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
makeShape1 = if (crossover(j,d) or crossover(j,99))
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end
And I would like to add a condition to makeShape1, something like "AND If j>d on 1D-chart", to ensure that buys are only generated while J is larger than D on the 1D-chart of that asset (ie: when the market for that asset is in an uptrend).
Any ideas on if/how I can achieve that?
Thanks!
-Daniel
You can access higher TFs with security() function
//#version=4
study(title="KDJ IndicatorTV", shorttitle="KDJ_TV", format=format.price, precision=2, resolution="", overlay=true)
periodK = input(9, title="K", minval=1)
periodD = input(5, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
multiplierJ = input(3.5, title="Jx", minval=0.1)
k = ema(stoch(hlc3, high, low, periodK), smoothK)
d = ema(k, periodD)
j = multiplierJ * k-2 * d
j_sec = security(syminfo.tickerid, "D", j) // 1 day time frame for j
d_sec = security(syminfo.tickerid, "D", d) // 1 day time frame for d
makeShape1 = if (crossover(j,d) or crossover(j,99)) and j_sec > d_sec
true
else
false
plotshape(series=makeShape1, style=shape.cross, color=#0094FF, transp=10, text="buy", title='buy')
makeShape2 = if (crossunder(j,d) or crossunder(j,99))
true
else
false
plotshape(series=makeShape2, style=shape.cross, color=#FF6A00, transp=10, text="sell", title='sell')
//end

In Pine Script, how can you do something once per day, or keep track if something has been done yet that day?

I'm working on a TradingView script (Pine) and i'm trying to use my Daily-bar strategy on the 5-minute chart. To do this, I need to basically only check conditions once per day.
I can do this by having a boolean variable such as dailyCheck = false and set it to true when I run that code and then reset it on a new day.
Does anyone know how to go about doing this? From what I read in the pine manual it says you can get unix time...but I don't know how to work with this and I can't print anything except numbers in the form of plot, so I can't figure out how to tell when a new day has started. Thanks in advance!
Version 1
There are lots of ways to detect a change of day. The Session and time information User Manual page shows a few.
I like detecting a change in the dayofweek or dayofmonth built-in variables:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(dayofweek)
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
Version 2
Following Michel's comment, this uses a more robust detection of the day change:
//#version=4
study("Once per Day")
var dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? color.orange : na)
And for the OP, a v3 version:
//#version=3
study("Once per Day v3")
dailyTaskDone = false
newDay = change(time("D"))
doOncePerDay = rising(close, 2) // Your condition here.
dailyTaskDone := doOncePerDay or (dailyTaskDone[1] and not newDay)
plotchar(newDay, "newDay", "▼", location.top, transp = 60)
plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
bgcolor(dailyTaskDone ? orange : na)