Template Trailing Strategy (Backtester)

jason5480 Updated   
๐Ÿ’ญ Overview

๐Ÿ’ข What is the "Template Trailing Strategyโ€โ“
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
  • Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
  • Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
  • Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
  • Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
  • Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingViewโ€™s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap โ€œtrading logicโ€ by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.

NOTE: The โ€œTemplate Trailing Strategyโ€ does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a โ€œTrading Systemโ€, because it gives its user full flexibility on that end (for better or worse).

๐Ÿ’ข What is a โ€œSignal Indicatorโ€โ“
โ€œSignal Indicatorโ€ (SI) is an indicator that can output a โ€œsignalโ€ that follows a specific convention so that the โ€œTemplate Trailing Strategyโ€ can โ€œunderstandโ€ and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS โ€œwhenโ€ to enter or exit, and the TTS determines โ€œhowโ€ to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a โ€œlong entry signalโ€. Once TTS receives the โ€œlong entry signalโ€, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a โ€œMarketโ€ order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a โ€œStopโ€ order type with a 1% Stop Distance, then when the price of the security rises by 1% after the โ€œlong entry signalโ€ occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.

๐Ÿค” How to Guide

๐Ÿ’ข How to connect a โ€œsignalโ€ from a โ€œSignal Indicatorโ€โ“
The โ€œTemplate Trailing Strategyโ€ was designed to receive external signals from a โ€œSignal Indicatorโ€. In this way, a โ€œnew trading ideaโ€ can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, โ€œAm I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?โ€
To make that possible by connecting an external signal indicator to TTS, you should:
  • Add in the same chart, the โ€œSignal Indicatorโ€ of your choice (e.g. โ€œTwo MA Signal Indicatorโ€, โ€œClick Signal Indicatorโ€, โ€œSignal Adapterโ€, โ€œSignal Composerโ€) and the โ€œTemplate Trailing Strategyโ€.
  • Go to the โ€œSettings/Inputsโ€ tab in the โ€œ๐Ÿ› ๏ธ STRATEGYโ€ group of the TTS and change the "๐ƒ๐ž๐š๐ฅ ๐‚๐จ๐ง๐๐ข๐ญ๐ข๐จ๐ง๐ฌ ๐Œ๐จ๐๐ž" to โ€œ๐Ÿ”จExternalโ€
  • Go to the โ€œ๐Ÿ”จ STRATEGY โ€“ EXTERNALโ€ group settings of the TTS and change the โ€œ๐Ÿ”Œ๐’๐ข๐ ๐ง๐š๐ฅ ๐Ÿ›ˆโžกโ€ to the output signal of the โ€œSignal Indicatorโ€ you want to connect. The selected combo box option should look like โ€œ<SI>:๐Ÿ”ŒSignal to TTSโ€ where <SI> should correspond to the short title of your โ€œSignal Indicatorโ€

๐Ÿ’ข How to create a Custom Trading logicโ“
The โ€œTemplate Trailing Strategyโ€ provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.

โœ๏ธ Develop your own Customized โ€œSignal Indicatorโ€๐Ÿ’ฅ
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a โ€œSignal Indicatorโ€. To create a new script, press the โ€œPine Editorโ€ button below the chart to open the โ€œPine Editorโ€ and then press the โ€œOpenโ€ button to open the drop-down menu with the templates. Select the โ€œNew Indicatorโ€ option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the โ€œPine Editorโ€ with a warning on top stating that this is a read-only script. Press the โ€œcreate a working copyโ€. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
  startLongDeal = [...],
  startShortDeal = [...],
  endLongDeal = [...],
  endShortDeal = [...],
  cnlStartLongDeal = [...],
  cnlStartShortDeal = [...],
  cnlEndLongDeal = [...],
  cnlEndShortDeal = [...])
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '๐Ÿ”ŒSignal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the โ€œโ€ฆโ€ part after โ€œ=โ€. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the โ€œAdd to chartโ€ button. If all goes well, you will be able to connect your โ€œsignalโ€ to the TTS as described in the โ€œHow to connect a โ€œsignalโ€ from a โ€œSignal Indicatorโ€?โ€ guide.

๐Ÿงฉ Adapt and Combine existing non-signal indicators๐Ÿ’ฅ
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the โ€œindicator on indicatorโ€ feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the โ€œSignal Adapterโ€ script in the same chart as well. This script is a โ€œSignal Indicatorโ€ that can be used as a proxy to define your custom logic in the CONDITIONS group of the โ€œSettings/Inputsโ€ tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a โ€œsignalโ€ will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the โ€œHow to connect a โ€œsignalโ€ from a โ€œSignal Indicatorโ€?โ€ in the โ€œ๐Ÿค” How to Guideโ€œ for more information.
If your logic is slightly more complicated, you can add a second โ€œSignal Adapterโ€ in your chart. Then you should add the โ€œSignal Composerโ€ in the same chart, go to the SIGNALS group of the โ€œSettings/Inputsโ€ tab, and connect the โ€œsignalsโ€ from the โ€œSignal Adaptersโ€. โ€œSignal Composerโ€ is also a SI so its composed โ€œsignalโ€ can be connected to the TTS the same way it is described in the โ€œHow to connect a โ€œsignalโ€ from a โ€œSignal Indicatorโ€?โ€ guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of โ€œSignal Adaptersโ€ and โ€œSignal Composersโ€ before connecting the final โ€œsignalโ€ to the TTS.

๐Ÿ’ข How to set up โฐAlertsโ“
The โ€œTemplate Trailing Strategyโ€ provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the โ€œ๐Ÿ”” ALERT MESSAGESโ€ module of the TTS settings and check the โ€œEnableโ€ฆโ€ checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. Whatโ€™s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
โ— To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the โ€œMessage Boxโ€ that contains the message that came from the TTS.

๐Ÿ’ข How to execute my orders in a brokerโ“
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the โ€œTemplate Trailing Strategyโ€ first (see the โ€œHow to set up Alerts?โ€ guide above). Then you should go to the โ€œCreate Alert/Notificationsโ€ tab check the โ€œWebhook URLโ€ and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.

๐Ÿ“‘ Definitions
This section tries to give some definitions in terms that appear in the โ€œSettings/Inputs" tab of the โ€œTemplate Trailing Strategyโ€

๐Ÿ’ข What is Trailingโ“
Trailing is a technique where a price target follows another โ€œbarrierโ€ price (usually high or low) by trying to keep a maximum distance from the โ€œbarrierโ€ when it moves in only one direction (up or down). When the โ€œbarrierโ€ moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.

๐Ÿ’ข What is a Moonbagโ“
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.

๐Ÿ’ข What is Distanceโ“
Distance is the difference between two prices.

๐Ÿ’ข What is Biasโ“
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.

๐Ÿ’ข What is the Margin Distance of a price targetโ“
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.

โš™๏ธ Settings
In the โ€œSettings/Inputsโ€ tab of the โ€œTemplate Trailing Strategyโ€, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon ๐Ÿ›ˆ where you can learn more if you mouse over it. The โ€œSettings/Inputsโ€ tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. โ€œDistance Methodโ€. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:

In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.

This module contains the "๐ƒ๐ž๐š๐ฅ ๐‚๐จ๐ง๐๐ข๐ญ๐ข๐จ๐ง๐ฌ ๐Œ๐จ๐๐ž" that defines if the โ€œTemplate Trailing Strategyโ€ will operate using the Internal or the External (โ€œSignal Indicatorโ€) conditions. Some general settings can be applied regardless of the mode.

This sub-module makes the connection between the external signal of the โ€œSignal Indicatorโ€ and the โ€œTemplate Trailing Strategyโ€. It takes effect only if the "๐ƒ๐ž๐š๐ฅ ๐‚๐จ๐ง๐๐ข๐ญ๐ข๐จ๐ง๐ฌ ๐Œ๐จ๐๐ž" is set to โ€œ๐Ÿ”จExternalโ€.

This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the โ€œTwo MA Signal Indicatorโ€ was used as a โ€œsignalโ€ in external mode. It takes effect only if the "๐ƒ๐ž๐š๐ฅ ๐‚๐จ๐ง๐๐ข๐ญ๐ข๐จ๐ง๐ฌ ๐Œ๐จ๐๐ž" is set to โ€œ๐Ÿ”งInternalโ€.

This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).

This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.

This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.

This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.

This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.

This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.

This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.

This module defines all the messages that can be emitted per event during the strategy execution.

๐Ÿ˜ฒ Caveats

๐Ÿ’ข Does โ€œTemplate Trailing Strategyโ€ has a repainting behaviorโ“
The answer is that the โ€œTemplate Trailing Strategyโ€ does not repaint as long as the โ€œSignal Indicatorโ€ that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
โš ๏ธThere is an exception though, when the โ€œEnable Trailโš ๏ธ๐Ÿ’นโ€ checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.

๐Ÿ’ข Can โ€œTemplate Trailing Strategyโ€ satisfy all my trading strategiesโ“
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
โš ๏ธ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.

๐Ÿค— Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a โ€œdefect reportโ€ or asking questions that helped me to understand what improvements were necessary.

Release Notes:
  1. A New Distance Method called CUST! You can define a custom target as the take profit and stop loss. You can even select an output from any other indicator as the source input and take advantage of the "Indicator on Indicator" feature. This new feature makes this framework the most versatile and easy way to compose new strategies. What's more important is the fact that it served various strategy ideas for two years now in production and its robustness is proven in production.

  2. The "performance issue" was addressed by making several optimizations in this script and the libraries that empower it. I measured an average execution time reduction per bar of 21 percent!

  3. Some visual changes on the settings menu and in the labels in the chart to better indicate the entry and exit prices.

  4. Defaults that confused people changed e.g. "Adjust on Gaps" is disabled by default.

I want to thank all of you for the support in this journey!

If you're interested in exploring and discovering other high quality free strategies come join us in Discord: discord.gg/2wkm9QqSuY
Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.


The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.

Want to use this script on a chart?