Strategy Backtesting Template [MYN]A few people have been asking me to share my backtesting template. Currently I use this as my starting point for validating existing strategies and developing new ones.
Features:
Trading Date Range
Trade Direction
4 progressive take profits with target percents and percentage of position to take profit on (Thanks adolgo)
Variable percentage Stop Loss
Automatic ProfitView Alert Syntax builder for Longs and Shorts
ADX checkbox to automatically add conditional logic to your strategy
Pine utilities
Strategy BackTest Display Statistics - TraderHalaiThis script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
Full credit to the original author of this script. It can be found here: www.tradingview.com
I decided to modify the script by simplifying it down and make it easier to integrate into existing strategies, using simple copy and paste, by relying on existing tradingview strategy backtester inputs. I have also added 3 additional performance metrics:
- Max Run Up
- Average Win per trade
- Average Loss per trade
As this is a work in progress, I will look to add in more performance metrics in future, as I further develop this script.
Feel free to use this display panel in your scripts and strategies.
Thanks and enjoy :)
Strategy Multiple Orders + Statistics Template - EducationalHello traders
It's been a while
We're back in a bear market so I have a bit more time to publish new Pine scripts for the TradingView community
Special thanks to @fikira for his Multiple Orders script () and to @carnagecain for allowing me to publish this script we worked together on
I got widely inspired by @fikira's script for that one
This script is for educational purposes only - I wanted to show how we can add multiple TPs/SL + a table with custom statistics
In this Strategy template, users can define multiple take-profit and multiple stop-loss levels.
Basically, we have 4 trades per trend and each trade has its own SL/TP
Statistics
Stats are split per trade direction (Long, Short) and then consolidated
I put custom stats in that table such as:
- Probability of Win
- Probability of Loss
- Avg Profit/Loss per Trade
- APPT: (Probability of Win * Average Gross Profit) - (Probability of Loss * Average Loss)
- Number of times each TP/SL has been hit
I'm catching up with all recent pinescript features as we speak - more educational scripts template to come soon
Best Regards
Dave
OrderbugThis script demonstrate what I don't understand - according to documentation with order managements
The from_entry parameter should execute the exit on this specified trade.
The chart shows the right information, but the list of trades, in the Strategy tester panel doesn't make sense:
This is an extract of the CSV file I got from this script:
The enter1 is getting matched against 4 others entry names, each closing 30% of the position.
10,Exit Long,exit loss2
10,Entry Long,enter 3
===================
9,Exit Long,exit loss4
9,Entry Long,enter 3
==================
8,Exit Long,exit loss4
8,Entry Long,enter 2
==================
7,Exit Long,exit loss3
7,Entry Long,enter 2
===================
6,Exit Long,exit loss8
6,Entry Long,enter 2
==================
5,Exit Long,exit loss10
5,Entry Long,enter 2
==================
4,Exit Long,exit loss10
4,Entry Long,enter 1
===================
3,Exit Long,exit loss5
3,Entry Long,enter 1
===================
2,Exit Long,exit loss9
2,Entry Long,enter 1
===================
1,Exit Long,exit loss6
1,Entry Long,enter 1
The strategy example. Close position by timeoutThis is an example how to close open entries by timeout for educational purpose.
Template Trailing Strategy (Backtester)💭 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 “:🔌Signal to TTS” where 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:
📆 FILTERS
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.
🛠️ STRATEGY
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.
🔨 STRATEGY – EXTERNAL
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”.
🔧 STRATEGY – INTERNAL
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”.
🎢 VOLATILITY
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).
🔷 ENTRY
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.
🎯 TAKE PROFIT
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.
🛑 STOP LOSS
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.
🟪 EXIT
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.
💰 QUANTITY/RISK MANAGEMENT
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.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
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.
Enjoy!
Jason
STRATEGY R18-F-BTCHi, I'm @SenatorVonShaft
Just finished the strategy "STRATEGY R18-F-BTC" for trading on #bitcoin and other cryptocurrencies.
As any strategy on TradingView, R18 opens Long/Short positions (with no leverage) on certain price points for assets in the chart. But I intentionally make this strategy for Bitcoin . Strategy is effective with 1h chart and it has %36 winning trade ratio for #bitcoin trade. As strategy uses approximately 1/3 ratio of SL/TP levels, gross profit for 1 year backtest is above %200 (I mean above 3x for only BTC )
Strategy is built on combination of:
- MACD
- RSI
- FIBONACCI levels
- BTCUSDT price itself as indicator (for different crypto assets and BTCUSDTPERP trading. You can select different assets you like for indicator (it's BTCUSDT:Binance by default))
I fine-tuned all levels of indicators above accordingly (it has more than 10 variables that effects strategy itself).
You can find out your own strategy levels by adjusting long/short tp&sl variables as well as initial capital ratio variable.
Reverse option open reverse positions of the strategy
Backtest EngineThis is a simple backtest engine for your trading strategies. The idea behind this script is to make testing new strategies as easy as possible. Parameters such as take profit/stop loss and time period are built into the script and are customisable by the user via the settings interface. The only coding is to set the entry and exit conditions. Users need not touch any code beyond line 30.
For this post, I have used a 50/200 SMA crossover to demonstrate the ease of use for this script.
The features of this script include:
Backtest period start
Number of days until backtest period end
Take profit and stop loss % (via settings)
Programmable long and short entry/exit
Anti duplicate system (for entry conditions that are continuously satisfied, the engine will only make 1 trade until the is exit condition is satisfied).
DISCLAIMER: The strategy in this post is only a placeholder. The TP/SL levels are set to showcase the functionality of the engine and are in no means optimal settings.
Hope this helps! Feel free to ask any questions about the engine and happy coding!