简体   繁体   中英

PINESCRIPT - Lock ATR for Stop Loss and Take Profit

I want to use ATR to take profit and set stop loss. The problem is, the ATR continues to adjust every bar. How do I set the ATR to be static number based on the opening candle and not continue to update every bar?

FYI: There are a few of this same question on stackoverflow, but none of them actually work.

I also have tried using strategy.position_avg_price instead of close but that never seems to work either.

Here is my code.

I am using v4.

Thanks!

// Create ATR
atr = atr(14)


// Determine stop loss price
longStopPrice  = close - (atr * 1)


// Take Profit
takeProfit = close + (atr *  1.5)

You should use strategy.position_size to check if you have an open position and then place your take profit and stop loss levels with strategy.exit .

Here is a simple example:

//@version=5
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)

longCondition = ta.atr(14) >= 100
tp = close * 1.01
plot(tp)

if (longCondition)
    strategy.entry(id="Long Id", direction=strategy.long)

if (strategy.position_size > 0)
    strategy.exit(id="Short Id", from_entry="Long Id", profit=tp)

在此处输入图片说明

Blue line is the take profit level calculated each bar. As you can see, take profit level changes every bar, however, the actual strategy exit takes places based on the initially calculated take profit level.

was trying to figure out the same problem today just found this on another post

ta.valuewhen(condition, source, occurrence)

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