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

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!

Related

plot the high low of 1 minute and 15 minutes bar during RTH 9:30 am ET (Pine script)

How do I plot horizontal lines using high and low of the first one minute bar after market opens at 9:30 (NYSE time)?
Possibly I would like to plot the open, high and close of 1st 1 minute bar.
Then when first 15 minutes is done, would like to plot the high and low of that bar as well.
I tried with OHLC indicator and others, but couldn't find something to tackle exactly this.
Also the below code that I got it from chatGPT, but it got couple of errors
type here
indicator("First Minute Bar High and Low", overlay=true)
var float firstBarHigh = na
var float firstBarLow = na
// Define the regular trading hours for the NYSE in Eastern Time
var tradingHoursStart = input("09:30-5", "Trading Hours")
var tradingHoursEnd = input("16:00-5", "Trading Hours")
var tradingHoursRange = time(tradingHoursStart + ":1234567-" + tradingHoursEnd + ":1234567")
// Define the desired time in Eastern Time
var timeInET = timenow("America/New_York")
if hour(timeInET) == 9 and minute(timeInET) == 30 and timeInET >= tradingHoursRange
if barstate.isfirst
firstBarHigh := high
firstBarLow := low
```plot(firstBarHigh, "First Minute High", color=color.green)
```plot(firstBarLow, "First Minute Low", color=color.red)

Keeping orders from closing if conditions are met & multiple orders

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

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)

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%")

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')