简体   繁体   中英

What approach to be followed to code this in Pinescript

  1. Buy signal to be generated if any candle closes above a line (let's say EMA20)
  2. Stoploss should get triggered only if any subsequent candle closes below it (buy signal candle).
  3. 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

  1. You can use ta.crossover(close, ema20) to check that
  2. Store entry price in a var , and check if the price closes below it when you are in a trade
  3. 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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM