如何使用以下代码触发止损后进行相反方向的交易。请纠正我

问题描述 投票:0回答:1
var entry_price_main = 0.0
var tg_price_main = 0.0
var sl_price_main = 0.0


if (buySignal or sellSignal) and time_cond
    
    if buySignal 
        entry_price_main := shortStop
        strategy.entry("1ST CE", strategy.long, qty = level_Qty)
        sl_price :=low 
        sl_price := entry_price-sl_price < 2 ? sl_price : na
        sl_price1 := shortStop-sl
        tg_price_main := entry_price_main + tg
        sl_price_main := sl_price > sl_price1 ? sl_price : sl_price1
        strategy.exit("exit CE",qty = tg1_Qty, limit = tg_price, stop = sl_main, comment_loss = " loss CE", comment_profit = "Profit CE")
        strategy.exit("exit CE2",qty = sl_qty, stop = sl_main, comment_loss = " Loss CE")

        
    if sellSignal
        entry_price_main := longStop
        strategy.entry("1ST PE", strategy.short, qty = level_Qty )
        sl_price := high 
        sl_price := sl_price- entry_price < 2 ? sl_price : na       
        sl_price1 :=longStop + sl
        tg_price_main := entry_price_main - tg
        sl_price_main := sl_price < sl_price1 ? sl_price : sl_price1
        strategy.exit("exit PE",qty = tg1_Qty, limit = tg_price, stop = sl_main, comment_loss = " Loss PE", comment_profit = "Profit PE")
        strategy.exit("exit PE2",qty = sl_qty, stop = sl_main, comment_loss = " Loss PE") 






need to get pine code for trade at stop loss after above codes
algorithm pine-script pine-script-v5 tradingview-api algorithmic-trading
1个回答
0
投票

您需要在另一个方向以止损价下限价单。

下面是一个例子。它将设置 SL 为 2%,并以相同价格设置空头限价单。

//@version=5
strategy("My strategy", overlay=true)

sma_14 = ta.sma(close, 14)
sma_28 = ta.sma(close, 28)

plot(sma_14, color=color.green)
plot(sma_28, color=color.orange)

long_cond = ta.crossover(sma_14, sma_28)
long_exit_cond = ta.crossunder(sma_14, sma_28)

if (long_cond)
    strategy.entry("Long", strategy.long)

if (long_exit_cond)
    strategy.close("Long")

entry_price = strategy.opentrades.entry_price(strategy.opentrades - 1)
sl_price = (strategy.position_avg_price * 0.98) // 2% SL

plot(sl_price, "SL", color.red, 1, plot.style_circles)
plot(entry_price, "Entry", color.white, 1, plot.style_circles)

if (strategy.position_size > 0)
    strategy.exit("LE", "Long", stop=sl_price)
    strategy.entry("Short", strategy.short, stop=sl_price)
else
    strategy.cancel("Short")    // Cancel pending short limit order if we are no longer in a long position

© www.soinside.com 2019 - 2024. All rights reserved.