Search code examples
pine-scripttradingview-api

How To Add Order Limit and Stop Levels to Alerts?


I have created a pinescript strategy opens a position with the following code:

strategy.entry("Long", strategy.long, stop = close - riskLong, limit = takeProfitLong, qty = math.round(probLossLong / (riskLong / close)))

I want to add the stop and limit values to my alerts. I tried this alert body:

{
  "symbol": "{{ticker}}",
  "position": "{{strategy.order.action}}",
  "entry_price": "{{strategy.order.price}}",
  "leverage": "{{strategy.order.contracts}}",
  "stop_loss": "{{strategy.order.stop}}",
  "take_profit": "{{strategy.order.limit}}",
  "timestamp": "{{timenow}}"
}

The result is:

{
  "symbol": "ETHUSDT.P",
  "position": "buy",
  "entry_price": "2070.93",
  "leverage": "29",
  "stop_loss": "{{strategy.order.stop}}",
  "take_profit": "{{strategy.order.limit}}",
  "timestamp": "2023-11-25T12:00:01Z"
}

So the I cannot access the stop and limit like the price or action. What is the correct way?


Solution

  • I found the solution. PineScript doesn't support getting the stop and limit values as default. However, you can set custom values using the plot function. Each plotted line can be accessed using plot_n format. Where n is the index of the plot, starting from 0 up until 19. If there's more than 20 plots, you cannot access their values on alerts if you cannot rearrenge them.

    var float stopLossLevelGlobal = na 
    var float takeProfitLevelGlobal = na
    
    if long
       takeProfitLevelGlobal := x
       takeProfitLevelGlobal := y
    if short
       takeProfitLevelGlobal := x
       takeProfitLevelGlobal := y
    
    
    plot(stopLossLevelGlobal, title="Stop Loss Level", color=color.red)
    plot(takeProfitLevelGlobal, title="Take Profit Level", color=color.green)
    

    Corrected alert body:

    {
      "symbol": "{{ticker}}",
      "position": "{{strategy.order.action}}",
      "entry_price": "{{strategy.order.price}}",
      "leverage": "{{strategy.order.contracts}}",
      "stop_loss": "{{plot_0}}",
      "take_profit": "{{plot_1}}",
      "timestamp": "{{timenow}}"
    }