Pine Script V5, How can i DELAY 5 seconds for my LONG & SHORT Entry? - pine-script-v5

I want to delay 5 seconds for my LONG & SHORT entries.
for example,
if the "longCondition" is true at 12:00:00, I want to execute LONG entry at 12:00:05
the same for Short entry: if the "shortCondition" is true at 12:00:00, I want to execute SHORT entry at 12:00:05
Can anyone help me, please?
//#version=5
strategy('My Strategy', overlay=true)
// Indicators
shortSMA = ta.sma(close, 10)
longSMA = ta.sma(close, 30)
rsi = ta.rsi(close, 14)
// Conditions
longCondition = ta.crossover(shortSMA, longSMA) and (rsi > 50)
shortCondition = ta.crossunder(shortSMA, longSMA) and (rsi < 50)
/// LONG
strategy.entry("long", strategy.long, when=longCondition, comment="Entry Long") //## How can i delay 5 seconds for this entry ???
strategy.close("long", when=shortCondition, comment = "Exit Long")
/// SHORT
strategy.entry("short", strategy.short, when = shortCondition, comment="Entry Short") //## How can i delay 5 seconds for this entry ???
strategy.close("short", when=longCondition, comment="Exit Short")

Related

strategy enter on auto Fibonacci levels when closing candle above line auto fibonacci percent 0.236

//#version=5
//strategy enter
List item
targetlong = close * 0.2
targetshort = close * 0.2
longEntryPrice = ta.cross(close,lineId5) and close > targetlong
shortEntryPrice =ta.cross(close,lineId5) and close > targetshort
//Entry Orders auto fibonacci
if longEntryPrice
strategy.entry("Buy", strategy.long,comment = "buy")
if shortEntryPrice
strategy.entry("Sell", strategy.short,comment = "sell")

Pine Script 5 - Unwanted alert messages

I receive unwanted alert messages. I would like to have only 1 "Go Long" alert when going long and then no other "Go Long" alerts until after the first "Go Short" alert. I'm having trouble getting this right.
//#version=5
strategy("Single Alert Strategy", overlay=true)
// Create flags to avoid multiple Long signals when already in Long and multiple Short signals when already in Short
isLong = false // We initialize a value and give it false (we are not in a Long position)
isLong := nz(isLong[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
isShort = false // We initialize a value and give it false (we are not in a Short position)
isShort := nz(isShort[1]) // We check the previous value and assign the previous value to this variable (when no previous value exist it will become false)
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and not isLong // Go Long only if we are not already Long
shortCondition = ta.crossunder(tot_rsi, bearLevel) and not isShort // Go Short only if we are not already Short
// Change the flags to avoid duplicate signals
if (longCondition)
isLong := true
isShort := false
if (shortCondition)
isLong := false
isShort := true
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
I followed the instructions in the answer provided here. While the signal indicators plot correctly (no additional signals), I do get an alert message when there was no signal plotted. This strategy is newly created with a new alert and is only added to 1 chart. The alert was created at 06:58, there were signals plotted before the alert was created but it triggered at 07:05 even though there was no signal plotted.
RSI level at 07:05 was 48.20
Any ideas what may have caused this alert to trigger and how to prevent additional alerts like these?
Link to screenshot
Edit: I'm testing an alternative approach. The unwanted alerts do not come frequently so I may have to run it for some time. If anyone knows of a different work around then I'm happy to give that a try.
//#version=5
strategy("Single Alert Strategy", overlay=true, calc_on_every_tick = true)
noOrder = strategy.closedtrades == 0 // There is no previous order
openLong = strategy.position_size > 0 // We are going Long
openShort = strategy.position_size < 0 // We are going Short
// Long Short conditions
tot_rsi = ta.rsi(close, 14)
bullLevel = 30
bearLevel = 70
longCondition = ta.crossover(tot_rsi, bullLevel) and (openShort[1] or noOrder) // Go Long only if the previous order was Short
shortCondition = ta.crossunder(tot_rsi, bearLevel) and (openLong[1] or noOrder) // Go Short only if the previous order was Long
if longCondition
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition
strategy.entry('Short', strategy.short, alert_message = "GoShort")
// Plot the signals and compare them with the Alerts log
plotshape(series=longCondition, title="Long", text="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(series=shortCondition, title="Short", text="Short", style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
Edit 2: The 2nd approach also created an alert despite there not being any signal plotted. Screenhot here
You should test also with strategy.opentrades which will return something !=0 if a trade (Long or Short) is currently open :
if longCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Long', strategy.long, alert_message = "GoLong")
if shortCondition and strategy.opentrades==0
strategy.close_all(comment="close", immediately=true)
strategy.entry('Short', strategy.short, alert_message = "GoShort")

How do I use both stop loss and take profit in pinescript v5 ? (Three methods)

I'd like to get the stop loss and take profit to trigger and print on the chart. The stop loss and take profit should both be set to 1% from the entry for both long and short positions.
Method 1: Initiate the take profit order immediately after entry
if longCondition
strategy.entry("BB Long", strategy.long)
strategy.exit("EXIT LONG WIN", from_entry="BB Long", limit=high * 1.01)
Can I initiate both the stop loss and take profit orders in the same way, immediately after the entry? Example:
if longCondition
strategy.entry("BB Long", strategy.long)
strategy.exit("EXIT LONG WIN", from_entry="BB Long", limit=high * 1.01)
strategy.exit("EXIT LONG STOP", from_entry="BB Long", stop=open * 0.99)
So far I'm not able to get it working with method 1 for both stop loss and take profit.
Method 2: I've seen this example in a few scripts. If I can't use both takeprofit and stop loss in method 1, when would I need to use this instead?
if (strategy.position_size > 0)
strategy.exit("EXIT LONG STOP", from_entry="BB Long", stop=open * 0.99)
Using method 1 for the take profit and method 2 for the stop loss, I'm getting varying success. The script still isn't printing the closing of the positions on the chart for both take profit and stop loss.
Method 3: Instead of using strategy.exit() , use strategy.close() . Can someone explain the differences to me?
Can you help me understand what I should be doing to achieve my goal for this script?
For the sake of completeness, here is the script as I have it currently.
//#version=5
strategy(shorttitle="BB Multi", title="Bollinger Bands Strategy", overlay=true)
// Set input parameters
length = input.int(20, minval=1)
mult = input.float(2.5, minval=0.001, maxval=50)
offset = input.int(0, "Offset", minval = -500, maxval = 500)
// Calculate Bollinger Bands using 15 minute data
src = close
middle = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = middle + dev
lower = middle - dev
// Calculate Bollinger Bands using 1 hour data
src1h = request.security(syminfo.tickerid, '60', close, lookahead=barmerge.lookahead_on, gaps=barmerge.gaps_on)
middle1h = ta.sma(src1h, length)
dev1h = mult * ta.stdev(src1h, length)
upper1h = middle1h + dev1h
lower1h = middle1h - dev1h
// Enter long position when 15 minute chart Bollinger Band is touched and the 1 hour band is touched
longCondition = ta.crossover(low, lower) and (ta.crossover(low, lower1h) or ta.crossover(low[1], lower1h))
if longCondition
strategy.entry("BB Long", strategy.long)
strategy.exit("EXIT LONG WIN", from_entry="BB Long", limit=high * 1.01)
// Enter short position when 15 minute chart Bollinger Band is touched and the 1 hour band is touched
shortCondition = ta.crossunder(high, upper) and (ta.crossover(high, upper1h) or ta.crossover(high[1], upper1h))
if shortCondition
strategy.entry("BB Short", strategy.short)
strategy.exit("EXIT SHORT WIN", from_entry="BB Short", limit=low * 0.09)
// Plot Bollinger Bands
plot(upper, color=color.red, linewidth=2)
plot(lower, color=color.red, linewidth=2)
plot(upper1h, color=color.blue, linewidth=2)
plot(lower1h, color=color.blue, linewidth=2)
if (strategy.position_size > 0)
strategy.exit("EXIT LONG STOP", from_entry="BB Long", stop=open * 0.99)
if (strategy.position_size < 0)
strategy.exit("EXIT SHORT STOP", from_entry="BB Short", stop=open * 1.01)
I have written a few scripts from cobbled together pieces of code but I'm now trying to get a better understanding of the functions. I've tried combinations of different methods but I'm still not getting both the take profit and the stop loss to trigger as well as display on the chart.
Thank you!
Ok, so the first solution I found is this:
strategy.exit("TP / SL", from_entry="BB Long", limit=high * 1.01, stop=initialEntryPrice * 0.99)
The take profit and stop loss are placed in the same strategy.exit() function. However, this doesn't plot in on the graph in the way that I want. I would want to see just TP or SL, depending on the case. In this solution, it will plot "TP / SL" whenever it exits a trade, for either reason. This is ok, but if anyone has can answer my other questions I would be grateful!

Compilation error. Line 10: Extraneous input ':' expecting 'end of line without line continuation'

I keep getting compilation errors, I am new to pinescript and cant figure out where I am going wrong.
//#version=5
// Define the RSI period
period = 14
// Calculate the RSI
rsi = rsi(close, period)
// Check for bullish divergence
if (rsi < 30) and (rsi < rsi[1]) and (close > close[1]):
# Bullish divergence detected, go long
strategy.entry("Long", long=true)
strategy.exit("Exit long", "Long", profit=50, stop=-50)
// Check for bearish divergence
if (rsi > 70) and (rsi > rsi[1]) and (close < close[1]):
# Bearish divergence detected, go short
strategy.entry("Short", short=true)
strategy.exit("Exit short", "Short", profit=50, stop=-50)
You error comes from the indentation of your 'if' block.
Change you indentation and your code to :
//#version=5
// Define the RSI period
period = 14
rsi = ta.rsi(close, period)
// Check for bullish divergence
if (rsi < 30) and (rsi < rsi[1]) and (close > close[1])
// Bullish divergence detected, go long
strategy.entry("Long", strategy.long)
strategy.exit("Exit long", "Long", profit=50, stop=-50)
// Check for bearish divergence
if (rsi > 70) and (rsi > rsi[1]) and (close < close[1])
// Bearish divergence detected, go short
strategy.entry("Short", strategy.short)
strategy.exit("Exit short", "Short", profit=50, stop=-50)

Move stop loss after take profit is hit

I would like to move my stop loss to where my first take profit is IF it reaches it. And also as of now when my stop loss is hit it only sells half the position and then the left is left lingering until it hits the second take profit if it ever does. Any suggestions are greatly appreciated.
shortCondition = close < lowerBand and close[1] > lowerBand
if (shortCondition)
strategy.entry("short", strategy.short, qty=pos_size)
if strategy.position_size < 0
strategy.exit("exit short TP", qty=size_trim, profit = 400, comment="close first 50%")
strategy.exit("exit short SL", loss = 400, profit = 800, comment="SL/last50%")
longCondition = close > upperBand and close[1] < upperBand
if (longCondition)
strategy.entry("long", strategy.long, qty=pos_size)
if strategy.position_size > 0
strategy.exit("exit long TP", qty=size_trim, profit = 400, comment="close first 50%")
strategy.exit("exit long SL", loss = 400, profit = 800, comment="SL/last50%")