This script demonstrates how to do trailing take profit. With this approach instead of setting a limit order, when you hit the target you just follow the price upwards (for long positions) and you sell when the price drops by a small percentage. This approach will increase the profits (slightly) in every strategy! Be aware that the simulated data may produce unrealistic results.
Release Notes
⋅
Add min and max input val
Simplify the strategy order commands
Simplify long Take profit price plot command
Release Notes
⋅
Use close source to define the profit price
Set offset to the plot of TP price
Release Notes
⋅
Check if time is within backtest period to prevent unecesary calculation and print inside the area of interest
Replace deprecated transp argument with color.new
Release Notes
⋅
Use strategy.percent_of_equity
Draw lines with width 1
Release Notes
⋅
Update pinescript to V5
Take profit step to 0.05 deviation to 0.01
Transparency deprecation fix
Release Notes
⋅
Let's face it a Green-Red color model is more intuitive!
Release Notes
⋅
Happy New Year!
Many code refactorings and optimizations to better use this script as a template and plug your own strategy at ease
Release Notes
⋅
(minor) refactoring
Release Notes
⋅
Use time_filters library
Release Notes
⋅
Minor revision update
Release Notes
⋅
Replace deprecated "when=" with if statements in strategy calls
Release Notes
⋅
Change fastMA default color to yellow
Release Notes
⋅
Increase max labels to 150
Increase max lines to 150
Minor refactoring
Release Notes
⋅
Update time_filters library
Release Notes
⋅
Some minor label/color changes
Release Notes
⋅
small refactoring
Release Notes
⋅
Update time_filters library version
Release Notes
⋅
Update time_filters library version
Release Notes
⋅
Use the 'chrono_utils' library for the date-time window filter
Awesome script! thank you very much for publishing it. I have used trailing orders before in some trading platforms and they are very profitable.
Since we can't have several positions, sometimes an entry doesn't hit the target for long time and prevents other trade opportunities. Pyramiding and then exiting the whole position is not a good idea.
I came with this idea of giving each entry and exit a random ID and then adapting the code for this. I'm a noobie in Pine Script but I think this could work:
if (isWithinBacktestPeriod())
// getting into LONG position
strategy.entry(id = thisLongId, long = strategy.long, when = startLongDeal, alert_message = "Long(" + syminfo.ticker + "): Started")
// submit exit orders for trailing take profit price
strategy.exit(id = thisLongExitId, from_entry = thisLongId, ...
jason5480
⋅
@elerouxx, This is an interesting approach! I think this might work eventually. However, I think you might want to keep track of longTakeProfitPrice(s) because when the second position comes it will modify the take profit price of the first one. Also, if you want to support an arbitrary number of trades, you have to find a way to draw the take profit prices for all open positions!
elerouxx
⋅
@jason5480, I thought that, at least for the time being, the line.new() function could be a way to do something like this, but haven't figured out how to plot a line at the time of the order.
jason5480
⋅
@elerouxx, you have to create a series that has 'na' in the timeframes you do not want to print and the actual value in the timeframes you want to draw then call plot with 'style = plot.style_linebr' like I did in the line 147
jason5480
⋅
@elerouxx, Or you can just average in and calculate the overall take profit price using the strategy.position_avg_price * (1 + longTakeProfitPerc)
elerouxx
⋅
@jason5480, you are right! It's funny that the position_avg_price line just changes (temporarily) when there is a new entry, but at at least I managed to exit every entry correctly by removing the first nz() argument.
float longTakeProfitPrice = na
longTakeProfitPrice := if (isWithinBacktestPeriod()) and longIsActive
//nz(longTakeProfitPrice,close * (1 + longTakeProfitPerc))
nz(close * (1 + longTakeProfitPerc))
This breaks the drawing of the TP line tho. Drawing a line for every entry and its respective TP will be more challenging. The idea of an overall take profit is a good idea, it will work better graphically, but the exit will probably be less probable to happen in the strategy I'm thinking of. Sometimes an entry will just be open too high before a bear period and it will have to wait for next bullish, or then SL, but in the meantime other trades are possible.
jason5480
⋅
@elerouxx, This implementation will update the take profit price on each candle using the close value of the previous candle. Are you sure that this is what you want?
elerouxx
⋅
@jason5480, Yes, it draws the take profit line relative to each candle, however the strategy.exit issue is sent properly. This is because each entry has its own TP% in the script I'm working on, and it is calculated from data instead of user input.
A temporary solution I found is to use line.new() to create custom lines for each entry price + exit take profit price at the time of order creation, only these lines don't extend to the exit point.
Thanks for the info about series and 'style = plot.style_linebr' above, maybe I can figure out how to create a new series for each entry in the pyramid.
jason5480
⋅
@elerouxx, OK I see, if the functional part is right then the rest are cosmetics :) good job
elerouxx
⋅
@jason5480, Thanks again! After the functional part, I managed to set lines for individual entries using 2 arrays, pushing a new entryPrice and targetPrice into the arrays when opening position, and removing them when target price is hit by a candle.
The caveat is not being able to put a plot() instruction inside a 'for... to', so I kinda had to hard code a "loop" with a maximum limit, like this:
Since we can't have several positions, sometimes an entry doesn't hit the target for long time and prevents other trade opportunities. Pyramiding and then exiting the whole position is not a good idea.
I came with this idea of giving each entry and exit a random ID and then adapting the code for this. I'm a noobie in Pine Script but I think this could work:
// STRATEGY EXECUTION ===============================================================================================
randomStringId = tostring(int(random(10000,99999,171)))
thisLongId = "EN"+randomStringId
thisLongExitId = "EX"+randomStringId
if (isWithinBacktestPeriod())
// getting into LONG position
strategy.entry(id = thisLongId, long = strategy.long, when = startLongDeal, alert_message = "Long(" + syminfo.ticker + "): Started")
// submit exit orders for trailing take profit price
strategy.exit(id = thisLongExitId, from_entry = thisLongId, ...