Search code examples
pine-scriptalgorithmic-tradingtradingback-testing

Pyramiding trades with independent take profit (Pinescript)


  1. Let's say I have 1 long signal. Take profit is set to 10% (not yet reach).
  2. Then, I have another long signal (same condition). I want to set 10% of take profit like the other one.
  3. I want each trade to have independent take profit because entries were not at the same time.

When I use pyramiding=2, it will make an average of the two trades and close all trade at the same time when average price has a gain of 10%. But I want to keep the take profit independent and close each trade when each one has reach their own take profit.

My code :

longProfitPerc = input(title="Long Take Profit (%)",
     minval=0.0, step=0.1, defval=10) * 0.01

longExitPrice  = strategy.position_avg_price * (1 + longProfitPerc)
strategy.entry(id="Long", long = true, when = enterLong())
strategy.exit(id="Long", limit=longExitPrice)

Solution

  • Here you are:

    longProfitPerc = input(title="Long Take Profit (%)",
         minval=0.0, step=0.1, defval=10) * 0.01
    
    percent2points(percent) =>
        strategy.position_size !=0 ? strategy.position_avg_price * percent / 100 / syminfo.mintick : na
    
    strategy.entry(id="Long", long = true, when = enterLong())
    strategy.exit(id="Long", profit=percent2points(longProfitPerc))