简体   繁体   中英

How to set dynamic take profit but static stop loss in pinescript v4?

I've been having some problems with the stop function in Pinescript v4. The TP works but for some reason, the stop isn't working. Attached is the code snippet and a picture of where it should be.

Stop should be at the highest high of the last 4 bars (including the current bar)

longstop = lowest(low, 4)
shortstop = highest(high, 4)

if longcond
    strategy.entry("long", strategy.long, 5, stop = longstop)
strategy.exit("TP", "long", limit = EMA)
if shortcond
    strategy.entry("short", strategy.short, 5, stop = shortstop)
strategy.exit("TP", "short", limit = EMA)

Update

If I add an extra strategy.exit() function within the if block, then it will only trigger when it hits the stop price even when it should have closed at the limit price Example

 if shortcond
    strategy.entry("short", strategy.short, 5)
    strategy.exit("SL", "short", stop = shortstop)
strategy.exit("TP", "short", limit = EMA)

If I add the stop to the current strategy.exit() line, then the stop price is continually updated at each bar for the lowest/highest of the past 4 bars which I don't want. I want the stop price to be set and static at the entry bar.

if longcond
    strategy.entry("long", strategy.long, 5)
 
strategy.exit("TP", "long", limit = EMA, stop = longstop)

I want the TP to be dynamic (updates every bar to be the EMA price) but I want the SL to be static (the lowest/highest price within the last 4 bars)

limit argument of the strategy.exit() is used for take profits. If you want to set a stop loss, use the stop argument.

I was able to fix it by adding a condition counting the number of bars since entry and switching to v5.

shortstop = ta.highest(5)
longstop = ta.lowest(5)

strategy.entry("long", strategy.long, 50, when = longcond)
longbarsSinceEntry = bar_index - strategy.opentrades.entry_bar_index(0)
strategy.exit("exit", "long", stop = longstop[longbarsSinceEntry], limit = EMA)


strategy.entry("short", strategy.short, 50,  when = shortcond)
shortbarsSinceEntry = bar_index - strategy.opentrades.entry_bar_index(0)
strategy.exit("exit", "short", stop = shortstop[shortbarsSinceEntry], limit = EMA)

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