Easy Backtester PROWHAT IS EasyBacktester ?
EasyBacktester is a tool that helps you backtest trading strategies built by yourself with an included strategy builder and a multitude of options.
From within the parameters of the tool, you can specifically pick your entry settings across 12 most common indicators, such as "RSI", "MACD", "Moving Averages" etc... Then you can immediately visualise your setup's Stop-loss & Take Profit, your expected Profits & Loss and a lot of other statistics for your entry strategy. Once you are satisfied with your entry strategy, you are given a set of tools to optimize your setup using stop-loss rules, take profits rules, partial profits, trailing-stops, entry timing...
WHY IS THIS TOOL DIFFERENT ?
EasyBacktester is a backtesting engine with no coding skills required. TradingView allows for "Strategy Scripting" using PineScript, which is not an option for non-coder audience. EasyBacktester fills this gap and allow non-coders to get an idea of how their trading strategies may perform using mouse clicks only.
Some similar attempts have been made on TradingView, allowing some limited options, but none have the same capabilities EasyBacktester offers, for instance, as of April 2022 these features have not been seen in any other TradingView tools:
- partial take profits
- leverage simulation
- a multitude of trailing stop-loss possibilities including trail triggers and trail parameters
- visualisation of entries including stop-loss, take profits, partial take profits, and trailing stops. One can now visualize such complex setups.
- visualisation of Profits & Loss
- time in trade
- wait strategy after a signal: for example, when RSI is oversold, "WAIT until price retraces 100% of the original signal" amongst other possibilities
QUICK START GUIDE:
STEP 1: DEFINE YOUR SIGNAL STRATEGY
From the settings of the tool, find the "SIGNALS STRATEGY" section.
Select a type of entry you wish to simulate, for example "LONGs", and activate the checkbox right before "Simulate".
Right below, you will find 4 signal builder for you to play with and pick your strategy accordingly.
For example, to simulate a signal when RSI is oversold, follow these steps:
- On the 1st multiple choice box, select "RSI"
- On the 2nd multiple choice box, select "is below..."
- On the 3rd multiple choice box, select "OverSold level"
Don't forget to activate this rule by checking the checkbox in front of it.
After this first step, one should immediately see the chart affected with some plots. The dots represents the signal entry defined by the rule we just created, and the red/green boxes visually represent trades that could have been taken with this signal which, in this example, occurs "when RSI is below oversold level". Note that all specific parameters for RSI including its specific "oversold level" is customisable at the end of the tools settings along with all other indicators settings.
STEP 2: STATISTICS
By default, the "APPEARANCE" section only plots potential entry signals (materialized by dots) and actual entry boxes (materialized by red/green boxes).
But the user can easily add other precious statistics to the chart, and obviously the most important one for backtesting: Profits & Loss (P&L).
In the "STATISTICS" section please check the "P&L" box to see appear a chart of the simulated P&L for our example. You should immediately see a new graph below the chart representing the evolution of the P&L after each entry.
Other statistics are available to the user, including: Equity, Number of Trades, Time in Position, Number of trades Won, Number of trades Lost, Number of trades Stopped.
Play around with those to see them plotted on your chart.
STEP 3: OPTIMIZE YOUR ENTRY
Under the "ENTRY STRATEGY" section, one can pick how to enter AFTER the signal, which provides the user with an extensive flexibility to pick its timing.
Here there are a various set of choices offered, ranging from the default "Market Order at Next Candle Open", to "Limit Order: at signal's candle open" or even "Stop-Buy: at break of last candle high". As its name suggests, this option allows you to actually wait before randomly enter in trade.
It is important to also note that the user can totally prevent entry if the conditions are not filled after a customizable number of candles represented in "Max bars to wait for entry" (default being 1, meaning the engine will wait the condition to be filled during only 1 candle)
STEP 4: MANAGE YOUR RISK
Under the "RISK MANAGEMENT" section, the user is given a series of options to set the amount (s)he would like to risk.
This is extremely important to set, and is the result of a combination of customizable options including:
- the Initial Capital of the account
- the amount to risk per trade, and HOW to risk it: some fixed % the initial equity or adjust the stop-loss to the desired risk ?
- use of leverage or not
- initial stop-loss, as well as minimum and maximum
- trailing stop-loss: what should trigger the trailing ? and by how much should the engine trail ?
STEP 5: HAVE AN EXIT PLAN
Under the "EXIT STRATEGY", the user can define how to exit the trade.
For instance, here again a lot of options are given:
- Take Profit: exit at some level of profits defined by a multiple of the stop-loss, or a multiple of the ATR, or some % or points
- Partial Profit taking before exit
- Panic close position after some time spent on the trade
STEP 6: FURTHER OPTIMIZATIONS
Under the sections "Commissions" & "Calendar & Sessions", one can simulate real trading conditions by including commissions fees as well as filtering actual dates and trading sessions. These sections are straightforward for any user to use.
SETP 7: INDICATORS SETTINGS
Since EasyBacktester uses a predefined set of indicators to get started, those indicators are also customizable in the last section of the settings. Here, one can easily customize RSI periodicity, MACD lengths, Moving averages types & lengths, ATR, etc...
STEP 8: GOING FURTHER
This is only a start to give users an overview of how various options affect their trading performance. But of course, each trader has its special recipe and specific detailed setup that is not possible to embed in a single tool. For advanced simulation, EasyBacktester provides plug & play connectors for advanced users. Namely, there are 3 connectors:
- signal connector
- trail trigger connector
- exit connector
Each of these connectors are an opportunity to customize the engine signals, trail trigger and exit choices with the user's own options. This case does require a little bit of coding, but it can easily be implemented by copy-pasting existing resources or with a slight help of a professional. In fact, the only conditions to build a proper connector is to export a plot with the numbers 1 (for signals), 2 (for trigger trails) and 3 (for exits). Here is an example of custom SIGNAL connector compatible with EasyBacktester, to produce a signal when last RSI was below 30 and current RSI reads above 30:
============================================================
//@version=5
indicator("My custom RSI signal")
// when previous RSI 14 was below 30 and current RSI 14 is above 30, set "custom_signal" to 1, otherwise set "custom_signal" to 0
custom_signal = ta.rsi(close, 14) < 30 and ta.rsi(close, 14) > 30 ? 1 : 0
// Export a plot of "custom_signal", but do not display it
plot(custom_signal, title="my signal", display=display.none)
============================================================
Once this indicator has been built, the user only needs to connect it with EasyBacktester as follow:
1. Open a desired chart, and add both EasyBacktester indicator as well as the custom "My custom signal" we just created above.
2. Open EasyBacktester's settings, and in the first option, there is "Connect signals source" which by default is set to "close". In the multiple choices, find your custom signal which should be named something like "My custom RSI signal: my signal", generally speaking the name is built like this " : ".
3. Now the custom code is connected to EasyBacktester, but we need to indicate the engine we actually want to use it as custom signal.
4. Under the "SIGNALS STRATEGY" section, where we generally build signals rules, there is special rule for this specific connection named "Use external source as entry signal". Just check the checkbox to activate it and see how the chart took our custom signal into consideration.
That's it for the overview of EasyBacktester. Thank you for reading and happy trading :)
Backtest
Backtesting- IndicatorFor anyone interested, Here is an example of how to put backtesting results into an Indicator. This calculates the same values as you find in the Summary Screen of the built in Strategy backtester. This will use the same result size as the standard backtester i.e. 5 minute chart grabs roughly 1 month of data, 1 minute chart grabs 1 week of data, etc... I tried to keep this as self-contained as possible so I put most of the code for the results in the bottom of the Indicator. The results stop at the last completed trade signal i.e. a Buy has a Sell to it. This is the same indicator I posted earlier with the PCT Trailing StopLoss so you will see that code in here as well. As said in my previous posting, the indicator is just a simple EMA crossover to give it something to do and I would not recommend using this indicator on its own, but instead copy the code to your own indicator if you find it useful. I also left the code in so that you can switch back to a Strategy if you want to verify the results.
Additional Notes:
- The results are within an acceptable margin of error due to the fact that the Indicator is having to calculate based on when the Buy and Sell Signal occur as opposed to when actual trades occur like in the Strategy Backtester
- I was trying to find a way to set the number of Buy Signals to use i.e. show me the results from the past 100 trades but couldn't sort out the logic. I am open to suggestions. Also keep in mind I am not a coder by profession so if you have any ideas on that front, please explain it to me as though I am a 5 year old child and provide code examples if possible :)
- I included the Strategy results in the Screen Shots so that you can see where the results line up.
Additional Additional Note:
This is not financial advice. Use at your own risk.
Backtest HelperAre you tired of being able to see the future while you're backtesting? Have you ever clicked to a higher timeframe in bar replay, only to realize you've just seen everything that's going to happen before you've had a chance to test it? If you've had this problem, Backtest Helper is here for YOU.
All you have to do is set a start date and time, then set your desired timeframe in minutes, then you're off to the races.
For example, if you're a scalper that uses the 15 minute as their higher timeframe, set your start time at the 14th minute of the session you're testing and set your line spacing at 15 minutes. This will mark off every 14th minute on the charts. Now you know the exact moment you can go up to the 15 minute timeframe!
On our 1 minute timeframe, this is how we'd look with the above settings. The Backtest Helper has marked off the 14th, 29th, 44th and 59th minute.
When we go up to our 15 minute, there's no issues. We're seeing the candle we want to see and not the next 15 minute candle.
You can use this for any timeframe. Just make sure you set your start time to at least 1 minute before the close of the candle and your line spacing to the higher timeframe (in minutes) you want to target.
TTP Grid BacktesterThis pine script strategy allows to backtest Grid bots.
This initial version offers the following features:
- Set the top and bottom limits of the grid
- Plots the average position price, realised and unrealised profits
- Set the value to invest
- This script is a strategy so you can check each individual buy/sell, stats and all included with strategies
What does it do:
- Depending where is located the initial close price relative to the grid (above, below, inside) it will buy for as many levels are above the price.
- It will disable a level that recently filled an order (in the way grids bot do)
- When the grid starts it will disable the closest grid level
- It places limit orders in the active levels and many levels can be filled in a single candle
- You can activate recalculate on each order filled, which will allow to fill further needed orders if the price swings up and down crossing multiple times multiple grid levels but I have found that doing this can compromise the accuracy of the price used on those levels (there are minor gaps between the filled price and the original level price)
How to use it:
- When you add this strategy to the chart you will be asked to select the top and bottom limits of the grid
- Notice you can always select the strategy in the chart and drag and drop the limits to adjust the grid
- Once the grid is in place, you can use either lower chart timeframes for higher accuracy of the stats, or higher timeframes if you want to privilege longer periods of testing
How to set the correct "initial capital"
In order to prevent getting wrong stats you need to make sure you are using the correct initial capital. If you put less than what you are actually using your results will be over inflated. If you set an initial capital below what the bot requires, your results will be smaller than they should.
- If you want to use exactly 100% of the capital for the grid use then first select what amount per level you want to use. Set this value in the settings of the indicator (if you are trading BTCUSD pair, how much BTC you want to use per level, 0.01 for example).
- Once you have set this value, then open the TradingView "Data Window" to be able to visualise the calculation of cash required to run the grid that the strategy is giving you. In our example with BTCUSD this value will be given in USD.
- Enter this amount in the "Properties" tab, "Initial Capital". If you enter the exact amount you will be using all for the grid usage.
- The grid first action will be to buy 0.01 for each level that is above the current price in the first candle of the chart. If there are no levels above it won't do any initial investment.
- The rest of the cash will be use to buy levels below if the price goes to the lower range of the grid later
Intention of this script
I built this script to help me understand better how grid bots work.
Understanding the flow of realised vs unrealised profits in a grid can help me understand why sometimes even if you are in red on unrealised profits, you can still compensate with realised profits and many other tricky scenarios with grids.
Sometimes I'm running a grid bot and would like to simulate how much better (or worst) it would have been to run it using different limits.
Future work and ideas
Initially I'm focusing on confirming that the grid behaves correctly and that the stats are as accurate as possible.
That is the first priority.
Once I feel more confident with the accuracy I will consider adding some of the following ideas (not in any particular order):
- Table with stats including: price of each level, times the level filled an order, times it was use for selling/buying, etc. Time it took to become in realised profit. Comparison against profits from buy & hold.
- Trailing TP/SL
- Entry/exit price
- Trading time window: only trade between the specified dates/times
- Alerts
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
Manual Backtest - Flat the ChartThis script is an utility tool for manual backtesting.
The main problem in backtesting a discretionary strategy is the bias of knowing the future result of the market, in this way all the market will be crushed into a flat line, this way you can avoid bias.
The way to use this indicator is easy and made by 4 step:
Step 1 : add to an asset you won't backtest and put the auto scale on
Step 2 : go to the asset you will backtest and scroll left until the date you want to start
Step 3 : use the replay function of tradingview (15 min chart won't go back more than 18 month)
Step 4: toggle off the indicator or remove from the chart (untill next asset to backtest)
That's not a complex indicator but is what you need to do a fair backtesting
WhaleCrew BacktesterBacktesting indicators is easy , just add the following line of code to your script:
plot(longEntry ? 1 : shortEntry ? -1 : longTP ? 0.5 : shortTP ? -0.5 : 0, color=na, editable=false, title='Backtest')
These numbers are defined as constants in the backtester source-code.
After adding this indicator to your chart:
1. Open Settings
2. Select supported indicator to backtest
3. Select if you want to enter Longs and/or Shorts
4. Open the 'Strategy Tester' at the bottom to check the performance
Remember:
past performance is not indicative of future results
repainting indicators will create wrong/unrealistic results
Zero-Lag HMA Backtest v1.0 [loxx]This backtest compares profitability differences between a regular Hull Moving Average ( HMA ) and a Zero-Lag HMA .
Things to know:
- Profit is set to 1 ATR
- Stop-loss is set to 1.5 ATR.
- This is by design to test the minimum the profit scenario (1 ATR up) and the worst case loss scenario (1.5 ATR down) for momentum trading. Actual results vary when additional TPs are added
How to use:
- Adjust settings and dates to view different market structures and position scenarios
- See results in the "Strategy Tester" pane
Conclusions and what's next
- Modifying HMA does very little to improve backtest results
- Future iterations will include options to backtest various moving averages with additional modifiers to improve profits and avoide losses
Comment below or send a PM with questions, comments, observations, or concerns.
[MAD] Level5 Backtest MK5.5First of all, this Backtest module comes WITHOUT a Strategy, only Riskmanagement
Modular L5 Backtest
For testing your own Indicators in this backtest use this script snipped below in your indicator Suite
After this you can include every L1 Indicator and test it.
todo this, select Digitalsignal @ your specific indicator as source, so the backtester can see its signals.
To have correct data at the exchange, use alarms after successful backtest on the indicator with "on candle close"
Steps of a entry, which you can see the in the screenshot:
L1 Strategy/Indicator sends "long"
buy of position setting of SL @%
after TP1 SL is set to entry
after TP2 position is closed 100%
If there a running position but in negative P/L each Signal adds up to the position + Growfactor
so a 1.0 would increase the next buy +100% 1, 2, 4, 8 .... (double up)
Shrinkfactor detecs a position is to large. If position is at average price it reduces to allowed percentage and continues
-------------------
Where to buy and how often.... has to come from your own indicator
This is the codesnipped for a external indicator to plot the signal as needed
signalout = 0
signalout := (signal_buy? 1: signal_sell? -1: 0)
BM_color_signal = signal_buy? #4C9900 : signal_sell? #CC0000: color.black
L_digital_signal = plot(signalout, title ="Digitalsignal", color=BM_color_signal, transp=0, style=plot.style_columns)
Inverse Fisher Transform ScreenerThis is a Screener for Inverse Fisher Transform on multiple oscillators
This tool is intended to aid you to visually analyse reasonable buy and sell IFT-signal thresholds across multiple tokens and different sources. It will help you speed up the tedious and manual work of trying out different IFT-settings when you're able to review the chart visually to find which values are present the most often and the location of that signal on the chart.
What does it bring to the table, why is it useful?
- Invese Fisher Transform on multiple oscillators such as RSI, MFI, CCI, Stochastic
- Combine multiple sources into one signal, select how it's calculated
- Visually review the chart for good IFT-settings
- 4 dynamic buy labels with different thresholds
- 4 dynamic sell labels with different thresholds
- Buy and sell on signal reversal
- Create your own trade alerts for automation
- Backtester compatible (plots 1 and 2 for buy and sell signals)
- A dynamic table counting amount of signals for each setting
- The labels are automatically updated when you change the values in the settings
How to use?
1. Change signal source and method
2. Change buy and sell thresholds
3. Show/hide additional labels
4. Review chart
5. Change trade settings
6. Backtest
7. Create alerts
Description
With this indicator you're able to visually review the signal strength of one or multiple oscillators processed with Inverse Fisher Transform ( IFT ), combine them and choose the method of calculation when they are combined. This produces a signal which strongly fluctuates between -1 and +1 instead of the more common 0-100 most oscillators uses. The intention is to make the decision making clearer and easier when you decide when to enter or exit a trade. This aims to help you remove the feelings from your trading.
Inverse Fisher Transform was first presented by John Ehlers in Stocks & Commodities V. 22:5 where he proposes to process RSI with the formula for hyperbolic tangent, tanh (x). This transforms the oscillator into a smoother and more compressed version with quicker oscillations.
Zendog SHORT DCA Trigger RSI+StochRSIThis is a script that generates a SELL signal by combining RSI and Stochastic RSI into the same script and that can easily be integrated into an external Backtester like the one I published.
The script uses default values for RSI and Stochastic RSI overbought conditions.
They should be adjusted for specific assets and timeframes so they better match the current trend. Please beware you might overfit settings to match a short timeframe trend (like a few days or hours). If this is the case once the trend changes the signals will not be accurate.
The purpose of this script is to provide some pine code that can be used to further combine multiple indicators into a SHORT Deal Start signal.
Integration with the Zendog Backtster:
- add the backtester on the chart
- add this script on the chart
- in the Zendog backtester Deal start type select "External indicator"
- in the Zendog backtester Indicator source and value select "Zendog SHORT DCA Trigger RSI+StochRSI: SIGNAL"
Zendog LONG DCA Trigger RSI+StochRSIThis is a script that generates a BUY signal by combining RSI and Stochastic RSI into the same script and that can easily be integrated into an external Backtester like the one I published.
The script uses default values for RSI and Stochastic RSI oversold conditions.
They should be adjusted for specific assets and timeframes so they better match the current trend. Please beware you might overfit settings to match a short timeframe trend (like a few days or hours). If this is the case once the trend changes the signals will not be accurate.
The purpose of this script is to provide some pine code that can be used to further combine multiple indicators into a LONG Deal Start signal.
Integration with the Zendog Backtster:
- add the backtester on the chart
- add this script on the chart
- in the Zendog backtester Deal start type select "External indicator"
- in the Zendog backtester Indicator source and value select "Zendog LONG DCA Trigger RSI+StochRSI: SIGNAL"
VictoriaThis indicator visualises different oscillators processed through Inverse Fisher Transform
What is included:
Inverse Fisher Transform on different oscillators
You can combine multiple oscillators into one
The combination of sources can be calculated in different ways
Set different buy and sell signal thresholds
View selected thresholds in the chart
Use TradingView Technicals Buy and Sell signals to dynamically change threshold values
Convert signal to alerts
Multiple filters to allow or block signals
Backtest compatible
Alerts compatible
Two different chart modes:
You can view multiple oscillators in the same chart
You can view trade signals/alerts on the chart from the thresholds you have selected
Description:
With this indicator you're able to visually review the signal strength of one or multiple oscillators processed with Inverse Fisher Transform (IFT), combine them and choose the method of calculation when they are combined. This produces a signal which strongly fluctuates between -1 and +1 instead of the more common 0-100 most oscillators uses. The intention is to make the decision making clearer and easier when you decide when to enter or exit a trade. This aims to help you remove the feelings from your trading.
Inverse Fisher Transform was first presented by John Ehlers in Stocks & Commodities V. 22:5 where he proposes to process RSI with the formula for hyperbolic tangent, tanh(x). This transforms the oscillator into a smoother and more compressed version with quicker oscillations.
Within a bull or bear period of the traded asset the signal have different strengths. To harness this to our advantage we use the combined strength of the TradingView Technical indicator which gives us a Buy, Strong Buy, Sell or a Strong Sell on the selected timeframe and asset. This makes it possible to delay the buy in bearish conditions to only trigger when it is really oversold and also allow the signal be more relaxed and exit the trade sooner. While on the other hand if the condition is bullish the buy signal is relaxed and the sell requires a stronger signal. All of this is possible to change in the indicator to fine tune the settings for the specific asset and timeframe selected. We also have the possibility of blocking the buy signals with different filters.
Dual MACD StrategyThis strategy Multi Time Frame Macd Indicator
We take the first long position when we have a buy signal in Weekly Macd (Macd line crosses above Signal line). This open a trading window, showed with green background color
We close the first position when either Weekly or Daily Macd give us a sell signal ((Macd line crosses below Signal line))
Enable Profit and Stop in strategy settings with different percentage to backtest the strategy. Also if it is better to use a Traditional Stop Loss or a Trailing Stop Loss based on a percentage from low prices
Change macd resolution in settings for other time frames to test the strategy
This Strategy was tested on Crypto Market with good results in assets as BTC, ETH, BNB, ADA, LTC, XLM, BCH, among others
Zendog V2 backtest DCA bot 3commasHi everyone,
After a few iterations and additional implemented features this version of the Backtester is now open source.
The Strategy is a Backtester for 3commas DCA bots. The main usage scenario is to plugin your external indicator, and backtest it using different DCA settings.
Before using this script please make sure you read these explanations and make sure you understand how it works.
Features:
- Because of Tradingview limitations on how orders are grouped into Trades, this Strategy statistics are calculated by the script, so please ignore the Strategy Tester statistics completely
Statistics Table explained:
- Status: either all deals are closed or there is a deal still running, in which case additional info
is provided below, as when the deal started, current PnL, current SO
- Finished deals: Total number of closed deals both Winning and Losing.
A deal is comprised as the Base Order (BO) + all Safety Orders (SO) related to that deal, so this number
will be different than the Strategy Tester List of Trades
- Winning Deals: Deal ended in profit
- Losing deals: Deals ended with loss due to Stop Loss. In the future I might add a Deal Stop condition to
the script, so that will count towards this number as well.
- Total days ( Max / Avg days in Deal ):
Total Days in the Backtest given by either Tradingview limitation on the number of candles or by the
config of the script regarding "Limit Date Range".
Max Days spent in a deal + which period this happened.
Avg days spent in a deal.
- Required capital: This is the total capital required to run the Backtester and it is automatically calculated by
the script taking into consideration BO size, SO size, SO volume scale. This should be the same as 3commas.
This number overwrites strategy.initial_capital and is used to calculate Profit and other stats, so you don't need
to update strategy.initial_capital every time you change BO/SO settings
- Profit after commission
- Buy and Hold return: The PnL that could have been obtained by buying at the close of the first candle of the
backtester and selling at the last.
- Covered deviation: The % of price move from initial BO order covered by SO settings
- Max Deviation: Biggest market % price move vs BO price, in the other direction (for long
is down, for short it is up)
- Max Drawdown: Biggest market % price move vs Avg price of the whole Trade (BO + any SO), in the other
direction (for long price goes down, for short it goes up)
This is calculated for the whole Trade so it is different than List of Trades
- Max / Avg bars in deal
- Total volume / Commission calculated by the strategy. For correct commission please set Commission in the
Inputs Tab and you may ignore Properties Tab
- Close stats for deals: This is a list of how many Trades were closed at each step, including Stop Loss (if
configured), together with covered deviation for that step, the number of deals, and the percentage of this
number from all the deals
TODO: Might add deal avg value for each step
- Settings Table that can be enabled / disabled just to have an overview of your configs on the chart, this is a
drawn on bottom left
- Steps Table similar to 3commas, this is also drawn on bottom left, so please disable Settings table if you want
to see this one
TODO: Might add extra stats here
- Deal start condition: built in RSI-7 or plugin any external indicator and compare with any value the indicator plots
(main purpose of this strategy is to connect your own studies, so using external indicator is recommended)
- Base order and safety orders configs similar to 3commas (order size, percent deviation, safety orders,
percent scale and volume scale)
- Long and Short
- Stop Loss
- Support for Take profit from base order or from Total volume of the deal
- Configs help (besides self explanatory):
- Chart theme: Adjust according to the theme you run on. There is no way to detect theme at the moment.
This adjust different colors
- Deal Start Type: Either a builtin RSI7 or "External indicator"
- Indicator Source an value: If using External Indicator then select source, comparison and value.
For example you could start a deal when Volume is greater than xxxx, or code a custom indicator that plots
different values based on your conditions and test those values
- Visuals / Decimals for display: Adjust according to your symbol
- BO Entry Price for steps table: This is the BO start deal price used to calculate the steps in the table
Hull Crossover Strategy no TP or SLWhat is it?
A simple yet effective strategy ran on the 30m chart.
This is a basic idea that can be expanded on using different indicator to either add signals or filter out certain bad signals!
The strategy consists of 1 fast moving average and 1 slow moving average.
Both of these moving averages are the Hull Moving Average
What is the Hull Moving Average?
The Hull Moving Average ( HMA ) is a directional trend indicator.
It captures the current market conditions and uses recent price action to determine if conditions are bullish or bearish relative to historical data.
The Hull is different from traditional trend indicators like the EMA and the SMA .
It is designed to reduce the lag often associated with other MAs by providing a faster signal on a smoother visual plane.
How it works?
When the fast HMA crosses over the slow HMA , we initiate a long signal, and
when the fast HMA crosses under the slow HMA , we initiate a short signal.
Conclusion
The power of simplicity is what makes this such a great core to use to build onto making something even better!
The results were optimised to suit the most common market conditions seen today.
******** Not financial advice! ********
QFL bull bypassThis bypass indicator triggers plots 1 when the price is above the QFL base.
This can be used as a "bypass" by a consumer indicator that can skip trades when the bypass is triggering.
You can use it for long and short strategies, to prevent using buy or sell signals in areas were the price is either overextended.
QFL works better in 1, 2 or 4 hours timeframes.
Inverse Fisher Transform on RSI for backtest w/alertsThis version of the Inverse Fisher Transform on RSI comes with support for
1) Backtesting with Gavin's backtest script
2) Bypass, you can use another indicator to pause buy signals from this indicator. Just create another indicator that plots "1" whenever you want to activate the bypass on the IFTRSI signal.
3) Independent buy and sell level thresholds. Some tokens perform better with a higher sell level, even levels as high as 0.996, sometimes the buy level can also be relaxed to even 0.6 and get incredible results on the 5 minute chart.
4) alerts for Buy and Sell signals
Make sure you add Gavin's backtest and select external signal and this indicator as the source.
TV signal for DCA backtestThis script allows you to backtest Trading View's "Technical Ratings" (Buy, Strong buy, Sell, Strong Sell) using Gavin's backtest script.
To use it add the backtest script to the chart together with this script and then from the back test settings connect the external indicator. You should select "TV Signal" as the source.
Backtesting works best on the 5m chart, but you can still change this script from its settings to higher timeframes.
Encoding
Buy is 1
Strong Buy is 2
Sell is -1
Strong Sell is -2
In the backtest script you can decide which rating you want to use for open deal and which one for close deal.
For example, if you were backtesting a long bot you could enter a long position when TV signal is Buy (1) and close the deal when TV signal is Sell (-1).
You have the full flexibility to decide which technical rating to use for your backtesting.
Enjoy!
Smart AlertsThis indicator provides back-tested signals and alerts from multiple technical indicators.
No more guessing whether or not you should trust an indicator. See your indicators' past performance at a glance.
No more false alarms. Disable re-painting of signals.
When multiple indicators overlap, a Confluence indicator will print (large triangle). With your settings properly tuned, this will show a HIGH probability of a move.
Current Signal/Alert Options (more to come):
RSI Oversold
RSI Overbought
EMA Crossing Up
EMA Crossing Down
Buy Signal Confluence
Sell Signal Confluence
Instructions:
-Enable/disable individual indicators so you can fine tune one at a time
-Adjust the indicator's settings
-Adjust your trade parameters (Max Wait, Take Profit %). Signals that would have given the desired profit in the time allowed will be painted orange.
-Repeat this process with each indicator until you're satisfied
-Set-up alerts
Smart EMA SignalsThis indicator starts by plotting each time the price action crosses above or below the EMA, of which you can tune the timeframe and duration.
It then takes it a step further and plots whether or not that indicator would have given you a profitable trade, of which you can also tune the parameters (Max wait time, and % Profit).
Once you have your EMA tuned to your liking, set up alerts to notify you of a golden opportunity.
QFL single TF with alertsBacktesting compatible QFL pine script w/alerts
This version of QFL was made based on this one:
From author:
www.tradingview.com
I made the following additions according to my requirements:
- I need to use pine script 4
- I needed to avoid repainting issues so I'm not calling directly security, I'm using the wrapper function.
- There might be still repainting issues when you use "max base age" which uses the function "barssince" so be careful, you can disable it by setting its value to zero.
- Alerts so I can use it for automated trading and bots
- In order to make this signal compatible with the backtest script there's an option provided in the settings. If you enable this option this indicator will plot 1 whenever there's a BUY signal. This will allow the backtest to pick the "QFL Buy" from external indicator so it can perform the backtest.
I recommend some of these settings to start playing with the chart in 15 min / QFL in 1, 2 or 4 hours.
The higher the TF the more conservative.
QFL with 3.5% is pretty popular but you can try higher QFL percentage settings for a more conservative approach.
Rainbow Strategy BacktestingRainbow Strategy Backtesting base on "Rainbow Moving Average" Strategy as below:
1.Rainbow Moving Average setup
- Source: source of 1st MA
- Type: SMA/EMA
- Period: period of 1st MA
- Displacement: period of 2nd MA to 7th MA with source is previous MA
2.Trend Define
- Up Trend: Main MA moving at the top of Rainbow
- Down Trend: Main MA moving at the bottom of Rainbow
- Sideway: Main MA moving between the top and the bottom of Rainbow
3.Signal
- Buy Signal: When Rainbow change to Up Trend.
- Sell Signal: When Rainbow change to Down Trend.
- Exit: When Rainbow change to Sideway.
4.RSI Filter
- "Enable": Only signals have 1st RSI moving between Overbought and Oversold and 2nd RSI moving outside Middle Channel are accepted.
- The filter may help trader avoid bull trap, bear trap and choppy market.
5.Backtesting Infomation
- Ticker: BTCUSDT
- Timeframe: H1
- Rainbow parameter:
+ Source: hlc3
+ Type: SMA
+ Period: 12
+ Displacement: 3
- RSI Filter parameter:
+ Enable
+ 1st RSI filter: period 12, overbought 65, oversold 35
+ 2nd RSI filter: period 9, upper middle 56, lower middle 44