'What approach to be followed to code this in Pinescript
- Buy signal to be generated if any candle closes above a line (let's say EMA20)
- Stoploss should get triggered only if any subsequent candle closes below it (buy signal candle).
- All candles formed prior to the "buy signal" candle should have a closing below EMA20.
Inversely for sell signal also.
I do not wish to know the code, only the logic would suffice for backtesting.
Thanks
Solution 1:[1]
- You can use
ta.crossover(close, ema20)to check that - Store entry price in a
var, and check if the price closes below it when you are in a trade - Use a counter to count when the price is below ema20
Below code should do it or at least give you an idea
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius
//@version=5
indicator("My script", overlay=true)
ema_len = input.int(20)
below_ema_no = input.int(4)
_ema = ta.ema(close, ema_len)
ema_co = ta.crossover(close, _ema)
var below_ema_cnt = 0
below_ema_cnt := close < _ema ? below_ema_cnt + 1 : 0 // Increase the counter if it closed below EMA20, reset oterwise
var is_long = false
var float buy_price = na
is_buy = not is_long and ema_co and (below_ema_cnt[1] >= below_ema_no) // Buy when we are not already long, ema crossover takes place, last n candles below ema20
is_long := not is_long ? is_buy ? true : false : is_long // Update is_long flag
buy_price := not is_long[1] and is_long ? close : buy_price // New position: Store buy price (close price)
is_sl = is_long ? close < buy_price : false // SL is hit if price closes below entry price
is_long := is_sl ? false : is_long // Update is_long flag in case SL is hit
buy_price := is_sl ? na : buy_price // Reset buy_price in case SL is hit
plot(_ema, "EMA", color.yellow, 2)
plotshape(is_buy, "Buy", shape.triangleup, location.belowbar, color.green, 0, "Buy", size=size.small)
plotshape(is_sl, "SL", shape.triangledown, location.abovebar, color.red, 0, "SL", size=size.small)
plot(buy_price, "Buy Price", color.white, 1, plot.style_circles)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vitruvius |

