Keeping orders from closing if conditions are met & multiple orders - pine-script-v5

First time coding - trying to set up a bot that creates multiple buy orders every time the buying signal is met and closed once the short signal is triggered - and vice versa. It seems to be working in TradingView when I add the strategy to the chart however when I connect it to 3 commas it only takes in one buy order (paper trading account) - and it closes it specifically when the condition to keep the position from closing is triggered.
I think I've set up the strategy correctly to take up to six positions with pyramiding.
strategy("DEMA CROSS STRATEGY", shorttitle = "DEMAC-S", overlay = true, initial_capital = 4000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.03, pyramiding = 6)
The conditions to keep a position from closing if longAction or shortAction are true, then keep the opened positions from closing, otherwise close all positions and open a long/short.
positionState = volume < valueThreshold and ADXsignal < adxThreshold
//logic
longCondition = ta.crossover(DEMA1, DEMA2) and supertrend_X_min < close and mfi+rsi/1.8 > 40 and close > WMA
shortCondition = ta.crossunder(DEMA1, DEMA2) and supertrend_X_min > close and mfi+rsi/1.8 < 60 and close < WMA and atr < .05
longAction = (longCondition and positionState)
shortAction = (shortCondition and positionState)
if (shortAction or longAction)
false
else
if (longCondition)
strategy.entry("Enter Long", strategy.long)
strategy.exit("Exit Short", stop=na)
if (shortCondition)
strategy.entry("Enter Short", strategy.short)
strategy.exit("Exit Long", stop=na)
//
//Buy and sell alerts
buyAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXX
exitAlert = XXXXXXXXXXXXXXXXXXXXXXXXXXXX
if longAction ? na : longCondition
alert(buyAlert, alert.freq_once_per_bar)
if shortAction ? na : shortCondition
alert(exitAlert, alert.freq_once_per_bar)
I've tried multiple different if then statements but honestly I'm not sure if I'm just doing it plain wrong at this stage.
Like I've stated, the code works in TradingView - not in 3Commas

Related

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!

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)

How to add all or some conditions to alert ? - Pine script tradingview

I have a list of conditions for a candle. This is just an example:
aa = (close > open) and (low > low[1])
bb = (close[1] > open[1]) and (close[1] > 5)
cc = (close > ((high[1] - low[1])*23.6/100 + low[1]))
dd = (close > EMA34) and (close > ema(close, 10))
I set alert using the following code:
if aa
alert("A- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if bb
alert("B- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if cc
alert("C- " + tostring(close, "#.######"), alert.freq_once_per_bar)
else if dd
alert("D- " + tostring(close, "#.######"), alert.freq_once_per_bar)
With each condition, I will get an alert with a letter at the beginning of the message so I can know the priority of the conditions, ie A is the best, D is the last one.
I would like to know if there is any way to check all conditions at the same time, so I can set the priority like:
if the alert has all conditions fulfilled, so it's the best A
if the alert has at least 3 conditions fulfilled, then it's B
if the alert has at least 2 conditions, then it's C
and if there is only 1 condition fulfilled, then it will be D
The real list has more than 10 conditions so I cannot check them manually. Please give me some code to do it programmatically.
I think, it's something related to array but I don't know how to do it.
Thank you for helping me.
aa = (close > open) and (low > low[1]) ?1:0
bb = (close[1] > open[1]) and (close[1] > 5) ?1:0
cc = (close > ((high[1] - low[1])*23.6/100 + low[1])) ?1:0
dd = (close > EMA34) and (close > ema(close, 10)) ?1:0
number_of_condition_true=aa+bb+cc+dd
bool all_condition_true=na
bool three_condition_true=na
bool two_condition_true=na
bool one_condition_true=na
bool none_condition_true=na
if number_of_condition_true>=4
all_condition_true:=true
else if number_of_condition_true>=3
three_condition_true:=true
else if number_of_condition_true>=2
two_condition_true:=true
else if number_of_condition_true>=1
one_condition_true:=true
else if number_of_condition_true==0
none_condition_true:=true
this is one of the ways ,this code will help you in programming your logic. in the above code i have replaced it into numerical value if true , than i have added all , this will give you the overall how may are true at a time.

Script for indicating order history - Tradeview Pine

I want to indicate historical trades in tradingview charts via a script based on information on time and price for entry and close.
My best idea is to search through "time" to find matches for entry and close, and then change the background color according to short or long position or draw a horizontal line. However, this seems not optimal. Any suggestions?
I'd implement that in the next way:
//#version=3
strategy("Background changing", overlay=true)
NONE = 0
LONG = 1000
SHORT = -1000
position = NONE
position := nz(position[1], NONE)
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("LongEntryId", strategy.long)
position := LONG
if (close < high[1])
strategy.close("LongEntryId")
position := NONE
getColor(state) =>
state == LONG ? green :
state == SHORT ? red :
white
bgcolor(color=getColor(position))
Or you can put arrows to the chart:
//#version=3
study("My Script", overlay=true)
order = 0
if time >= timestamp(2018, 1, 10, 0, 0)
order := 1
if time == timestamp(2018, 1, 17, 0, 0)
order := -1
plotarrow(order)