'Pine Script - Stop loss triggers immediately if entry price equals previous close price
I am currently building a simple pine script strategy, where I enter a long/short trade based on a long/short signal, respectively. If I enter a long trade and get a short signal, my intention is to close the long trade and immediately open a short position (and vice versa). This "ping-ponging" goes on through out the strategy.
I'd also like to include a stop loss that exits any trade with a loss of 1.5%.
However, as it is currently written, any time the close price equals of my previous trade equals the entry price of my current trade, the stop loss executes immediately. In the cases where the close price of my previous trade DOES NOT equal the entry price of the new trade, the stop loss works as intended. I've tried a ton of different things to get this to work - any idea what I'm doing wrong and how I can get this to work?
Here's a high-level view of my current code:
//Input
stopLoss = input(2.0, title='Stop Loss %', type=input.float)
//Buy & Sell Condition calcs (mostly removed)
highlel = (sell conditions)
lowlel = (buy conditions)
// === INPUT BACKTEST RANGE ===
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2018, title = "From Year", type = input.integer, minval = 2017, maxval = 2030)
thruMonth = input(defval = 12, title = "Thru Month", type = input.integer, minval = 1, maxval = 11)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 30)
thruYear = input(defval = 2030, title = "Thru Year", type = input.integer, minval = 2017, maxval = 2030)
// === INPUT SHOW PLOT ===
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
if (window())
strategy.entry("buy", strategy.long, when=lowlel)
strategy.exit("Long Stop Loss", from_entry="buy", stop=strategy.position_avg_price * (1 - (stopLoss / 100)))
strategy.close("buy", when=highlel)
strategy.entry("sell", strategy.short, when=highlel)
strategy.exit("Short Stop Loss", from_entry="sell", stop=strategy.position_avg_price * (1 + (stopLoss / 100)))
strategy.close("sell", when=lowlel)
The results from this code gives me trades like those shown in the below output table - where stop losses are triggered in the cases mentioned above.
Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

