Pine脚本(TradingView)-如何将止损移动到止盈位

时间:2020-10-25 14:21:40

标签: pine-script

在TradingView上有一个Pine脚本代码,其中我们有2个止盈位和2个止损位:tradingview.com。 当获得第一笔止盈时,一半的头寸被平仓,第一笔止损被转移到入门水平(收支平衡)。

您有任何想法如何通过以下逻辑实现3个获利水平:

  • 达到TP 1时,SL移至收支平衡点

  • 到达TP 2时,SL移至TP 2

  • 到达TP 3时,退出位置

非常感谢您的帮助!

    Traceback (most recent call last):
      File "e:/python程序库/wu.py", line 379, in <module>
        text = clean_str(text.get_text().encode('ascii', 'ignore'))
      File "e:/python程序库/wu.py", line 370, in clean_str
        string = re.sub(r"\\", "", string)
      File "C:\Users\29091\Anaconda3\lib\re.py", line 192, in sub
        return _compile(pattern, flags).sub(repl, string, count)
    TypeError: cannot use a string pattern on a bytes-like object

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

以下是您需要的示例:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov

// @description
// when tp1 is reached, sl is moved to break-even
// when tp2 is reached, sl is moved to tp1
// when tp3 is reached - exit

//@version=4
strategy("Stepped trailing strategy example", overlay=true)

// random entry condition
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

// sl & tp in points
sl = input(100)
tp1 = input(100)
tp2 = input(200)
tp3 = input(300)

curProfitInPts() =>
    if strategy.position_size > 0
        (high - strategy.position_avg_price) / syminfo.mintick
    else if strategy.position_size < 0
        (strategy.position_avg_price - low) / syminfo.mintick
    else
        0
        
calcStopLossPrice(OffsetPts) =>
    if strategy.position_size > 0
        strategy.position_avg_price - OffsetPts * syminfo.mintick
    else if strategy.position_size < 0
        strategy.position_avg_price + OffsetPts * syminfo.mintick
    else
        0
        
calcProfitTrgtPrice(OffsetPts) =>
    calcStopLossPrice(-OffsetPts)

getCurrentStage() =>
    var stage = 0
    if strategy.position_size == 0 
        stage := 0
    if stage == 0 and strategy.position_size != 0
        stage := 1
    else if stage == 1 and curProfitInPts() >= tp1
        stage := 2
    else if stage == 2 and curProfitInPts() >= tp2
        stage := 3
    stage

stopLevel = -1.
profitLevel = calcProfitTrgtPrice(tp3)

// based on current stage set up exit
// note: we use same exit ids ("x") consciously, for MODIFY the exit's parameters
curStage = getCurrentStage()
if curStage == 1
    stopLevel := calcStopLossPrice(sl)
    strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")
else if curStage == 2
    stopLevel := calcStopLossPrice(0)
    strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")
else if curStage == 3
    stopLevel := calcStopLossPrice(-tp1)
    strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")
else
    strategy.cancel("x")

工作原理,您可以看到here