Search code examples
pine-scriptpine-script-v5pine-script-v4

Pine Script Not Showing Short Closes in TV when trade in BOTH directions


I've been trying to solve the errors in strategy.close, and the quantity Long order for nearly a week but failed to figure it out. It works well if only enables a single direction but if enables both directions at the same time, the strategy.close for Short is not showing and not firing. Besides, the Long Order quantity is double than the Short Order quantity.

Any help is appreciated. Thank you.

error details

    bool longCond   = enableLong ? kagi_L : na and strategy.opentrades == 0
    bool shortCond  = enableShort ? kagi_S : na and strategy.opentrades == 0
    bool longClose  = enableLong ? kagi_S : na and strategy.position_size > 0
    bool shortClose = enableShort ? kagi_L : na and strategy.position_size < 0

    if (longCond)
        strategy.entry('Long', strategy.long, alert_message = i_alert_msg_long)
    
    if (longClose)
        strategy.close(id='L', comment='Close Long', alert_message = i_alert_msg_closelong)
    
    if (shortCond)
        strategy.entry('Short', strategy.short, alert_message = i_alert_msg_short)
    
    if (shortClose)
        strategy.close(id='S', comment='Close Short', alert_message = i_alert_msg_closeshort)

Solution

  • Hedging is not supported by Tradingview. So, you cannot have a long and a short position open at the same time.

    What's happening here is, Tradingview closes your order with the opposite direction entry.

    You enter a short position with -4595.931 then next time it enters a long trade (where you marked), it places an order of +9508.951. However, your position size at that moment is: 9508.951 - 4595.931 = 4913.02. And if you look closely, the next cL on your chart is exactly 4913.02 to close this position.

    Additionally, your ids in your strategy.close() calls do not match with your ids in your strategy.entry() calls. That will of course not work.

    if (longCond)
        strategy.close('Short', comment='Close Short', alert_message = i_alert_msg_closeshort)
        strategy.entry('Long', strategy.long, alert_message = i_alert_msg_long)
    
    if (shortCond)
        strategy.close('Long', comment='Close Long', alert_message = i_alert_msg_closelong)
        strategy.entry('Short', strategy.short, alert_message = i_alert_msg_short)