Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TradingView – Multiple take profits for a single order in Pine Script

Tags:

pine-script

I'm trying to implement a simple strategy where I enter a long when I receive a buy signal, then I want to take multiple profits and set a stop loss :

  • Sell 25% quantity at 1% profit
  • Sell 25% quantity at 2% profit
  • Sell 25% quantity at 3% profit
  • Sell 25% quantity at 4% profit
  • Stop loss at 2%

I've tried many things based on strategy.close, strategy.exit, strategy.entry but didn't find anything working. Does anyone have experience with that kind of strategy?

Thanks

like image 214
Jul Avatar asked Apr 28 '20 10:04

Jul


People also ask

What is pyramiding in Pine script?

The pyramiding setting says how many entries in the same direction a Pine strategy may take . The higher the value of pyramiding , the more additional long and short entries are possible.


1 Answers

The example of such strategy:

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

//@version=4
strategy("Multiple %% profit exits example", overlay=false, default_qty_value = 100)

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

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

percentAsPoints(pcnt) =>
    strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)

lossPnt = percentAsPoints(2)

strategy.exit("x1", qty_percent = 25, profit = percentAsPoints(1), loss = lossPnt)
strategy.exit("x2", qty_percent = 25, profit = percentAsPoints(2), loss = lossPnt)
strategy.exit("x3", qty_percent = 25, profit = percentAsPoints(3), loss = lossPnt)
strategy.exit("x4", profit = percentAsPoints(4), loss = lossPnt)

profitPercent(price) =>
    posSign = strategy.position_size > 0 ? 1 : strategy.position_size < 0 ? -1 : 0
    (price - strategy.position_avg_price) / strategy.position_avg_price * posSign * 100

p1 = plot(profitPercent(high), style=plot.style_linebr, title = "open profit % upper bound")
p2 = plot(profitPercent(low), style=plot.style_linebr, title = "open profit % lower bound")
fill(p1, p2, color = color.red)

How it works you can see on https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/

like image 81
Andrey D Avatar answered Nov 04 '22 10:11

Andrey D