FreedX Backtest█ Our strategy template empowers TradingView users to effortlessly backtest any indicator, enhancing their trading strategy's effectiveness. In addition, users can create automated webhook alerts from the template. This document details our template's features and how to utilize them effectively.
█ TRADE DATE SETTINGS
The Trading Date Settings feature in our TradingView script allows you to refine their backtesting parameters by specifying trading dates and hours. This feature enhances the accuracy of the backtest by aligning it with specific time frames and days, ensuring that the strategy is tested under relevant market conditions.
Features:
⚙️ Enable Trading Between Specific Dates:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific date range.
💡 How to Use:
→ Input the Start Date and End Date for the backtest period.
→ The script will execute the strategy only within this specified date range.
⚙️ Enable Trading Between Specific Hours:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific hour range.
💡 How to Use:
→ Input the start and end hour for in Trading Session section.
→ The script will execute the strategy only within this specified hour range.
⚙️ Enable Trading on Specified Days of the Week:
🎯 Purpose:
→ Gives you the option to conduct backtesting on selected days of the week, tailoring the strategy to particular market behaviours that may occur on these days.
💡 How to Use:
→ Select the days of the week for the backtest.
→ The script will activate the trading strategy only on these chosen days.
█ BUY/SELL TRIGGER SETTINGS
The Buy/Sell Trigger Settings feature is designed to provide users with flexibility in defining the conditions for 'LONG' and 'SHORT' signals based on various indicator types. This customization is crucial for tailoring strategies to different trading styles and market conditions.
Features:
⚙️ Single-Line Plotted Indicators :
🎯 Purpose:
→ Enables you to select a single-line plotted indicator as a source for backtesting. You can define specific levels to trigger 'LONG' or 'SHORT' signals.
💡 How to Use:
→ Choose a Single-Line Plotted indicator as the source.
→ Set the top and bottom levels for the indicator.
→ The script triggers 'LONG' signals at the bottom level and 'SHORT' signals at the top level.
⚙️ Two-Line Plotted Indicators :
🎯 Purpose:
→ Allows backtesting with two-line cross plot sources. Signals are generated based on the crossover of these lines.
💡 How to Use:
→ Select two lines as 'Source 1' and 'Source 2' for the indicator.
→ The script triggers a 'LONG' signal when 'Source 1' crosses above 'Source 2'.
→ Conversely, a 'SHORT' signal is triggered when 'Source 2' crosses above 'Source 1'.
⚙️ Custom Signals :
🎯 Purpose:
→ This setting enables users to define their own criteria for LONG, SHORT, and CLOSE signals based on custom indicator outputs.
💡 How to Use:
→ Select the custom source for your signals.
→ Define the output values that correspond to each signal type (e.g., “1” for 'LONG', “-1” for SHORT, and “0” for CLOSE).
→ The script will trigger signals according to these custom-defined values.
█ TP/SL SETTINGS
The TP/SL (Take Profit/Stop Loss) Settings feature is designed to give users control over their profit securing and risk mitigation strategies. This feature allows for setting custom TP and SL levels, which can be critical in managing trades effectively.
Features:
Custom TP/SL Levels for Long/Short Signals:
🎯 Purpose:
→ Enables users to set specific percentage levels for Take Profit and Stop Loss on long and short signals.
💡 How to Use:
→ In the TP/SL Settings, input the desired percentage for Take Profit (TP) and Stop Loss (SL).
→ For example, to secure a profit at a 10% price increase on LONG signals, set the “Long TP Percentage” to “10”.
█ STRATEGY SETTINGS
Strategy Settings provide a range of options to customize the trading strategy. These settings include leverage, drawdown limits, position direction changes, and more, allowing users to tailor their strategy to their risk tolerance and market view.
Features:
⚙️ Enable Leverage :
🎯 Purpose:
→ Allows users to apply leverage to their trades.
☢️ Caution:
→ High leverage can significantly increase the risk of liquidation.
→ High leverage and a high stop-loss price may override your fixed stoploss percentage, adjusting the stop-loss to the liquidation price.
💡 How to Use:
→ Set the desired leverage ratio in the Strategy Settings.
⚙️ Enable Drawdown Limit:
🎯 Purpose:
→ Sets a maximum drawdown limit, automatically halting the strategy if this limit is reached, thereby controlling risk.
💡 How to Use:
→ Input the maximum drawdown limit (default: 100, min: 0, max: 100).
⚙️ Enable Reverse Position:
🎯 Purpose:
→ Automatically closes a current position and opens a new one in the opposite direction upon detecting a signal for a market trend change.
🎯 Example:
→ If a LONG signal is received while in a SHORT position, the script will close the SHORT position and open a LONG position.
💡 How to Use:
→ Activate this feature in the Strategy Settings.
⚙️ Enable Spot Mode:
🎯 Purpose:
→ Disables short orders, using short signals only for closing long positions.
💡 How to Use:
→ Select the 'Spot Mode' option in the Strategy Settings.
⚙️ Enable Invert Signals:
🎯 Purpose:
→ Inverts all indicator signals, changing LONG signals to SHORT and vice versa.
💡 How to Use:
→ Opt for the 'Invert Signals' feature in the Strategy Settings.
⚙️ Enable Trailing Stop:
🎯 Purpose:
→ Triggers a trailing stop order on the exchange instead of a standard stop market order.
☢️ Caution:
→ The backtesting of this feature on TradingView may not accurately reflect actual strategy performance due to discrepancies between TradingView and exchange mechanisms.
💡 How to Use:
→ Select 'Trailing Stop' in the Strategy Settings.
█ ADVANCED STRATEGY SETTINGS
Advanced Strategy Settings offer sophisticated methods for managing Stop Loss (SL) and Take Profit (TP) using the Average True Range (ATR). These settings are ideal for traders who want to incorporate volatility into their exit strategies.
Features:
⚙️ Enable ATR Stop Loss:
🎯 Purpose:
→ Automatically sets the Stop Loss price using the Average True Range at the time of entry.
💡 How to Use:
→ Activate 'ATR Stop Loss' to have the SL price calculated based on the current ATR.
⚙️ Enable ATR Take Profit:
🎯 Purpose:
→ Sets the Take Profit price based on the Average True Range at the time of entry.
💡 How to Use:
→ Choose 'ATR Take Profit' for TP price determination using ATR.
⚙️ Enable ATR Trailing Stop:
🎯 Purpose:
→ Dynamically updates the Stop Loss price with each new bar, according to the Average True Range.
💡 How to Use:
→ Activate 'ATR Trailing Stop'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
█ TREND FILTERING SETTINGS
Trend Filtering Settings are designed to align trading strategies with the prevailing market trend, enhancing the precision of trade entries and exits. These settings utilize moving averages for trend analysis and decision-making.
Features:
⚙️ Enable Trend Filtering:
🎯 Purpose:
→ Limits trades based on moving average trends, blocking short trades in an uptrend and vice versa.
💡 How to Use:
→ Enable 'Trend Filtering'.
→ Set Fast and Slow MA Lengths for trend analysis.
→ Select the Timeframe for moving averages.
→ Choose the Moving Average Type for trend filtering.
🎯 Note:
→ Be cautious with timeframe selections; lower timeframes than the base may cause inconsistencies.
⚙️ Enable Exit on Trend Reversal:
🎯 Purpose:
→ Automatically closes a position when a market trend reversal is detected.
💡 How to Use:
→ Turn on 'Exit on Trend Reversal' in the settings.
⚙️ Enable Trend Drawing On Chart:
🎯 Purpose:
→ Visually represents the trend filter directly on the chart for easy reference.
💡 How to Use:
→ Activate 'Trend Drawing On Chart' to see the trend filter overlaid on the trading chart.
█ AUTOMATED ALERT SETTINGS
Automated Alert Settings are designed to integrate your TradingView script with webhook alerts. These settings allow for enhanced strategy execution and management.
Features:
Enable Webhook Alerts:
🎯 Purpose:
→ Trigger BUY, SELL, CHANGE_DIRECTION or MOVE_STOP_LOSS .
💡 How to Use:
→ Enable 'Webhook Alerts' in the settings.
→ Enter your Strategy ID.
→ Optionally, activate 'Override Allocation Percentage' to bypass the preset allocation percentage.
☢️ Caution:
→ Overriding the allocation percentage may result in trade entry errors due to misalignment between entry cost and available balance.
█ DEBUGGING SETTINGS
Debugging Settings are crucial for users who want to analyze and optimize their strategies. These settings provide tools for visualizing alerts on charts and accessing detailed data outputs.
Features:
⚙️ Enable Alert Plotting:
🎯 Purpose:
→ Allows users to visualize trading alerts directly on the chart, aiding in strategy analysis and refinement.
💡 How to Use:
→ Activate 'Alert Plotting' to draw alerts on the chart.
☢️ Caution:
→ It is recommended to disable this feature when creating actual trading alerts, as it can cause latency in signal processing.
⚙️ Enable Debugger Mode:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Data Window.
💡 How to Use:
→ Turn on 'Debugger Mode' to access real-time data and metrics relevant to your strategy.
█ ADDITIONAL SETTINGS
⚙️ Enable Bar Magnifier
⚙️ Enable Using standard OHLC
Backtester
[pAulseperformance] PSStrategyX█ OVERVIEW
This script reduces the amount of time it takes to turn your indicator into a live trading bot.
It will convert your signals into alerts that will be sent to your exchange for trading.
The script features a broker connector to automate alert syntax and connect with third-party exchanges to live trade strategies with minimal setup.
It also includes an enhanced version of the built-in backtester with customizable options to speed up backtesting, trade-by-trade statistics, and a chart strategy summary to help traders make informed decisions.
The PSStrategyX trading tool is designed to provide traders with a range of benefits, including:
Increased confidence in their strategies.
Better understanding of the accuracy of indicator signals.
Simplified automated trading through third-party broker connections.
Reduced time to develop strategies by focusing on signal development only. No need to work with complicated strategy testing code and 3rd party automation.
█ FEATURES
Broker Connector
— Supports Autoview (More Connectors added in the future)
— Connects and auto trades with most exchanges
— No need for Webhooks (AutoView)
— Can forward test live strategies on Testnets before using real money.
Built in Backtester loaded with options to speed up backtesting
— Standard strategy features including stop loss, take profit, and various filters reduce the time and complexity involved in building a working strategy.
Trade By Trade Statistics
— Gain insight on every trade with additional trade-by-trade statistics.
Strategy Summary
— Get instant feedback on your chart of your strategies performance. Visual cues and feedback give you hints on where to look and what to improve.
Strategy Tester Enhancements
— Take the max trades allowed in the strategy tester without errors.
— Take the largest or smallest trade allowed without errors.
█ WHY?
The PSStrategyX tool was developed to solve a common problem faced by traders who use Pine Script on TradingView: the inability to integrate Pine Script with exchanges through TradingView.
Without this integration, traders need to go through several extra steps to live trade their Pine Script strategies on a real exchange with real money. This includes finding a broker, learning the new syntax for the broker, and placing that syntax correctly in the strategy.
These steps can be time-consuming and add complexity to the codebase.
The PSStrategyX tool simplifies this process by automatically configuring the correct alert syntax to connect to third-party exchanges, allowing traders to live trade their strategies with minimal setup. This saves traders time and effort, allowing them to focus on signal development rather than complicated strategy testing code and 3rd party automation.
Additionally, the tool was developed to address the time-consuming task of converting any one of the thousands of great free indicators on TradingView to strategies through hours of coding.
Overall, I built the PSStrategyX to streamline the auto trading process and make auto trading more accessible to traders of all levels.
█ HOW TO USE THIS?
Using the PSStrategyX trading tool is a straightforward process that requires a few key steps:
1 — Generate trading signals: You need a signal generator that can provide buy and sell signals for your preferred trading instrument(s).
You can use TradingView's indicators or create your own custom indicators using TradingView's Pine programming language.
2 — Connect trading signals to PSStrategyX: You will use 2 scripts on your chart. One generates buy/sell/exit signals, and the other is the PSStrategyX script executing those signals as trades.
To set this up you will need to make sure that your signal generator is an indicator, NOT a strategy.
Make sure the signals are being plotted buy = 1; sell = -1; exit = 0; signals in one plot. Exits are optional.
Example plot(buy ? 1 : sell ? -1 : exit ? 0 : na)
You will choose the plot with buy/sell/exit signals inside the PSStrategyX tool to execute trades. If you need help, check out the docs for more details.
3 — Set up the broker connector (optional): If you want to take live trades with this tool, you will need to set up a third party connecter. Once set up, everything is automated. See more details in the "authors instructions." at the bottom of this post.
4 — Set up an exchange account (optional): If you want to trade on an exchange, you will need to set up an account with the exchange you plan to use.
The Broker Connector supports a range of popular exchanges, including Binance, Bitfinex, Kraken, Oanda and more.
Once you have generated your trading signals, set up the Broker connecter (optional) and set up an exchange account (optional), you can start using the PSStrategyX trading tool to execute trades automatically based on your trading signals.
█ LIMITATIONS
Here are some important limitations to keep in mind when using the PSStrategyX trading tool:
General:
— Once the alert is sent, there is no way to monitor positions on any exchange. The order will be processed by the broker connector and sent to the exchange.
While this usually works fine, it's important to check the log for errors.
Sometimes the broker connector may fail to process the order, or the exchange may not process it for various reasons.
— The tool sends TP/SL orders with the entry order when possible to protect your order in case of errors or if you lose a connection.
However, not all exchanges accept TP/SL orders, and sometimes your entry order will be left unprotected.
FIFO:
— This tool DOES NOT support the First In First Out (FIFO) method for closing positions.
— Instead, it uses the ANY method. There currently is no way to make this variable.
█ FAQ
What does PSStrategyX do exactly?
PSStrategyX is a strategy enhancing, backtester, forwardtester, automation and simulation tool. It's NOT a signal generator, and does not produce buy/sell signals by itself. You provide buy/sell signals, and PSStrategyX will put those signals on steroids...basically.
PSStrategyX helps you figure out what indicators actually work. Without wasting time learning how to code.
Why did you choose AutoView for this tool?
AutoView offered the best integration I could find. They allow you to connect to test exchanges for free, which is great for practicing without using real money. They also work without using webhooks, which means you can live trade without paying for Tradingview pro. Additionally, AutoView supports many different exchanges. I don't work for AutoView, but if you sign up through my referral link and purchase a paid version, I earn a commission.
Why doesn't Tradingview automatically connect Pine Script to exchanges?
This is a great question, but unfortunately I don't have the answer. It would definitely be helpful if Tradingview provided this feature, but it might also put some brokers out of business.
How do I get access?
DON'T ask for access in the comments.
DO review the "Authors Instructions" on this page for details.
basilGrid GridBot Live [basilChart]This strategy is a full implementation of Live Grid Trading.
Prominent features of this live grid trading strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count, however there may be irregularities because of limitations when higher grid levels are used. You can pick any number starting from 2.
- Average Price: Traders can monitor average price of positions.
- Alerts: When order is filled trader can receive notification. Create new alert > Select basilGrid Live > Order fills only()
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting date for the live grid bot either by dragging and dropping the vertical line or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 1D timeframe, our settings are:
Inputs Tab:
- Grid Count: 19
- High Limit: 65 500
- Low Limit: 15 000
- Quantity per level: 0.1
- Toggle Log Scale: Checked (because I always use Log Scale on charts, if Log Scale is turned on for the chart, this needs to be checked)
- Terminate Grid At The Upmost Level: Not checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 22 628
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make it easier to get the idea of grid trading, experiencing it in live session.
bc Grid Backtest v1.4This strategy is a full implementation of Grid Trading backtest.
Prominent features of this backtesting strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count. You can pick any number starting from 2.
- Customized Backtesting Results Table: A table which includes data for those who want to know has been added at top right. It can be disabled.
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting and ending date for the grid backtesting bot either by dragging and dropping the vertical lines or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 4h timeframe, our settings are:
Inputs Tab:
- Grid Count: 13
- High Limit: 72 000
- Low Limit: 17 000
- Logarithmic Grids: Checked (because I always use Log Scale on charts, if Log Scale is turned on, this needs to be checked)
- Quantity per level: 0.1
- Show Table: Checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 24 902
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make simulating possible outcomes between two dates. Therefore making it easier to get the idea of grid trading, finding the best settings for your risk management and for your portfolio.
Backtest AdapterThis is a proof-of-concept Backtest Adapter that can be used with my recent publication "Machine Learning: Lorentzian Classification" located here:
This adapter is helpful because it enables interactive backtesting with TradingView's built-in "Strategy Tester" framework without the need to translate the logic from an "indicator" script to a "strategy" script.
To use this, one must have the "Machine Learning: Lorentzian Classification" script and this Backtest Adapter open simultaneously on the same chart. From there, simply change the "Source" setting of the Backtest Adapter to "Lorentzian Classification: Backtest Stream" to transfer the entry/exit signals stream to the Backtest Adapter.
For an example of how to implement your own backtest stream in your indicators, please refer to the "Backtesting" section in the source code of the "Machine Learning: Lorentzian Classification" script, which is shown below for convenience:
Cyatophilum Universal Oscillator TraderAn indicator to backtest and create an infinite number of strategies using any external indicator.
═════════════════════════════════════════════════════════════════════════
█ HOW IT WORKS
The indicator allows you to create your oscillator strategy and get backtest results from the Strategy Tester.
You can also create alerts for each of the strategy events.
█ HOW TO USE
Choose a strategy direction long or short that you want to create.
Always use regular candle type.
Configure your entry condition . To use any other indicator as source, it needs to be added to the chart first.
If you have the basic (free) TradingView plan, you can only have 1 indicator on your chart, and cannot use this external source feature. For this case, the indicator has a list of built-in oscillator (that can be increased upon request).
Then choose your condition: Cross over, Greater than, Pullback, Turning up, etc.
You now have your entry and should already see trades on the chart!
Next you can fine tune your entry condition or move to the risk management and filters.
Configure your stop loss
Use the stop loss feature to exit a trade at a certain loss.
You can also create a trailing stop using price % movement or ATR.
Configure your profit target
Use the Take Profit feature to set a target in percentage of price. You can also make it trail.
Configure your safety orders
This indicator has a safety orders feature to reduce the risk of your trade. See more below.
Check your backtest parameters
Make sure that the initial capital and order size make sense. Since it is a pyramiding strategy with safety orders, the sum of all deals should not be bigger than the initial capital.
If you use % equity as order size, please note that it will create compounding.
Check the fees, by default they are set to 0.1%.
I also recommend to set a slippage that corresponds to your exchange's spread.
█ FEATURES
• Strategy direction
Configure to go long or short.
• Entry Conditions
- External Oscillator source
- Built-in Oscillator (for basic plans)
- Base Condition for entry (Less/Greater than, Crossing Up/Down, Pullback Bull/Bear, Turning Up/Down, etc. More can be added later on)
- Additional Momentum Condition: Oscillator should be rising/falling for x number of bars
- Addition Threshold Condition: Oscillator should be Greater/Lowser than x
• Trend Filter
Filter Trades using 1 or 2 moving averages (MTF), based on Slop Change or Price Cross. Trend line is green = only longs, red = only shorts.
• Entry Filters
- Volume filter to remove low volume entries
- Overbought/Oversold filters
- Flat market Filter
• Stop Loss and Take Profit
Configure your stop loss and take profit for long and short trades.
You can also make a trailing take profit and trailing stop.
• DCA (Safety orders)
Create up to 100 safety orders with configurable options for step and volume scaling, take profit from total volume, base and safety order size.
• Backtest Settings
Choose a backtest period, longs or shorts, wether to use limit orders or not.
Graphics
A Backtest Results panel with additional information from the strategy tester.
A lightweight mode to remove background plots and make the indicator load faster.
█ ALERTS
The indicator is using the alert() calls: it only uses 1 alert slot to send order messages for each event (Long/Short entry, stop loss, take profit, safety order, exit timer). This means basic-free TV plans can create 1 complete strategy.
To set your alert messages, open the indicator settings and scroll to the bottom of the "inputs" tab.
Create your alert after you set the messages in the indicator settings, and make sure "Any alert() function call" is set in the alert option.
Use placeholders to automatically replace values in your alert messages like price, target profit, order size etc. (see the indicator inputs).
█ BACKTEST RESULTS
The backtest settings can be seen in the 'Properties' tab of the backtest report below.
Please read the author instructions below for access.
Miyagi BacktesterMiyagi: The attempt at mastering something for the best results.
Miyagi indicators combine multiple trigger conditions and place them in one toolbox for traders to easily use, produce alerts, backtest, reduce risk and increase profitability.
The Miyagi Backtester is a standalone backtester which is to be applied to the chart after the Miyagi indicator to be backtested.
The backtester can only backtest one script at a time, and is meant to backtest ONCE PER BAR CLOSE entries.
It is currently not possible to backtest ONCE PER BAR entries.
The backtester will allow users to all Miyagi Indicators using DCA strategies to show returns over a selectable time period.
The backtester allows leverage, and as such users should be aware of the Maximum Amount for Bot Usage and Leverage Required Calculations.
The DCA Selector switch will allow users to backtest with, or without DCA.
Static DCA is used within the backtester and allows users to see DCA Statistics on closed trades.
How to use the Miyagi Backtester
Step 1: Apply the Miyagi Indicator of Choice to backtest (4in1/10in1/Strend).
DATE AND TIME RANGE:
-Date and time range to backtest.
TRADE:
-Entry source to backtest. Please select the "Outbound Entry Signal Sender"
-Trade Direction to backtest. This can be helpful to backtest according to your strategy (long or short).
-Take Profit % to backtest. This is the percent take profit to backtest. Slippage can be accounted for on the "Properties" tab.
-Stoploss % to backtest. This is the percent stoploss to backtest.
DCA:
DCA Checkbox: Enable the DCA Checkbox to backtest with DCA. Disable it to backtest without DCA.
Leverage: Input the Leverage you will trade with.
Base Order Size (% Equity): This is the Base order (BO) size to backtest in % of equity.
Safety Order Size (% Equity): This is the Safety order (SO) size to backtest in % of equity.
Number of DCA Orders: This is the maximum amount of DCA orders to place, or total DCA orders.
Price Deviation (% from initial order): This is the percent at which the first safety is placed.
Safety Order Step Scale: This is the scale at which is applied to the deviation for the step calculation to determine next SO placement.
Safety Order Volume Scale: This is the scale at which is applied to the safety orders for the volume calculation to determine SO Volume.
Real world DCA Example:
The process is as follows.
Base Order: This is your initial order size, $100 used for Base Order
Safety Order: This is your first safety order size, which is placed at the deviation. $100 Safety Order, it is good to keep the same size as your BO for your scaling to be effective.
Price deviation: This is the deviation at which your first Safety order is placed. 0.3-0.75% used by most of our members.
Safety Order Volume Scale: This is the scale at which is applied to the safety orders for the volume calculation. Scale of 2 used, which means that SO2 = (SO1) * 2, or $200. This scaling is typical for all following orders and as such SO3 = (SO2) *2, or $400.
Safety Order Step Scale: This is the scale at which is applied to the deviation for the step calculation. This is similar to the volume scale however the last order percentage is added.
Scale of 2 used, which means that SO2 % = ((Deviation) * 2) + (SO1%). (0.5% *2) + (0.5) = 1.5%.
This scaling is typical for all following orders except that the prior deviation is used and as such SO3 = ((Prior%) * 2) + (Deviation). (1.5% * 2) +(0.5%) or 3.5%.
Total SO Number: The calculations will continue going until the last SO. It is helpful to understand the amount of SO’s and scaling determines how efficient your DCA is.
Backtester Outputs include:
Net Profit to display net profit
Daily Net Profit to estimate
Percent Profitable which shows ratio of winning trades to losing trades.
Total Trades
Winning Trades
Losing Trades (only applicable if stoploss is used)
Buy & Hold Return (of the backtested asset) to compare if the strategy used beats buy & hold return.
Avg Trade Time is very helpful to see average trade time.
Max Trade Time is very helpful to see the maximum trade time.
Total Backtested Time will return total backtested time.
Initial Capital which is taken from the Properties tab.
Max amount for Bot Usage which can be helpful to see bot usage.
Leverage Required will show you the leverage required to sustain the DCA configuration.
Total SO Deviation will allow users to see the drop coverage their DCA provides.
Max Spent which is a % of total account spent on one trade.
Max Drawdown which displays the maximum drawdown of any trade.
Max % distance from entry shows the maximum distance price went away from entry prior to the trade closing.
Max SO Used which shows the maximum number of SO's used on a single trade
Avg SO Used which shows the average number of SO's used in all closed trades.
Deals closing with BO Only calculation will show how many trades are closed without DCA.
Deals closing with 1-7 SOs calculation will show how many trades are closed with DCA, and allow for fine-tuning.
Happy Trading!
This script will be effective to backtest and produce the best settings for each timeframe and pair across all STP Scripts.
This will take a lot of the manual work out of backtesting for our users while improving profit potential.
Happy Trading!
[MT] Strategy Backtest Template| Initial Release | | EN |
An update of my old script, this script is designed so that it can be used as a template for all those traders who want to save time when programming their strategy and backtesting it, having functions already programmed that in normal development would take you more time to program, with this template you can simply add your favorite indicator and thus be able to take advantage of all the functions that this template has.
🔴Stop Loss and 🟢Take Profit:
No need to mention that it is a Stop Loss and a Take Profit, within these functions we find the options of: fixed percentage (%), fixed price ($), ATR, especially for Stop Loss we find the Pivot Points, in addition to this, the price range between the entry and the Stop Loss can be converted into a trailing stop loss, instead, especially for the Take Profit we have an option to choose a 1:X ratio that complements very well with the Pivot Points.
📈Heikin Ashi Based Entries:
Heikin Ashi entries are trades that are calculated based on Heikin Ashi candles but their price is executed to Japanese candles, thus avoiding false results that occur in Heikin candlestick charts, this making in certain cases better results in strategies that are executed with this option compared to Japanese candlesticks.
📊Dashboard:
A more visual and organized way to see the results and necessary data produced by our strategy, among them we can see the dates between which our operations are made regardless if you have activated some time filter, usual data such as Profit, Win Rate, Profit factor are also displayed in this panel, additionally data such as the total number of operations, how many were gains and how many losses, the average profit and loss for each operation and finally the maximum profits and losses followed, which are data that will be very useful to us when we elaborate our strategies.
Feel free to use this template to program your own strategies, if you find errors or want to request a new feature let me know in the comments or through my social networks found in my tradingview profile.
| Update 1.1 | | EN |
➕Additions: '
Time sessions filter and days of the week filter added to the time filter section.
Option to add leverage to the strategy.
5 Moving Averages, RSI, Stochastic RSI, ADX, and Parabolic Sar have been added as indicators for the strategy.
You can choose from the 6 available indicators the way to trade, entry alert or entry filter.
Added the option of ATR for Take Profit.
Ticker information and timeframe are now displayed on the dashboard.
Added display customization and color customization of indicator plots.
Added customization of display and color plots of trades displayed on chart.
📝Changes:
Now when activating the time filter it is optional to add a start or end date and time, being able to only add a start date or only an end date.
Operation plots have been changed from plot() to line creation with line.new().
Indicator plots can now be controlled from the "plots" section.
Acceptable and deniable range of profit, winrate and profit factor can now be chosen from the "plots" section to be displayed on the dashboard.
Aesthetic changes in the section separations within the settings section and within the code itself.
The function that made the indicators give inputs based on heikin ashi candles has been changed, see the code for more information.
⚙️Fixes:
Dashboard label now projects correctly on all timeframes including custom timeframes.
Removed unnecessary lines and variables to take up less code space.
All code in general has been optimized to avoid the use of variables, unnecessary lines and avoid unnecessary calculations, freeing up space to declare more variables and be able to use fewer lines of code.
| Lanzamiento Inicial | | ES |
Una actualización de mi antiguo script, este script está diseñado para que pueda ser usado como una plantilla para todos aquellos traders que quieran ahorrar tiempo al programar su estrategia y hacer un backtesting de ella, teniendo funciones ya programadas que en el desarrollo normal te tomaría más tiempo programar, con esta plantilla puedes simplemente agregar tu indicador favorito y así poder aprovechar todas las funciones que tiene esta plantilla.
🔴Stop Loss y 🟢Take Profit:
No hace falta mencionar que es un Stop Loss y un Take Profit, dentro de estas funciones encontramos las opciones de: porcentaje fijo (%), precio fijo ($), ATR, en especial para Stop Loss encontramos los Pivot Points, adicionalmente a esto, el rango de precio entre la entrada y el Stop Loss se puede convertir en un trailing stop loss, en cambio, especialmente para el Take Profit tenemos una opción para elegir un ratio 1:X que se complementa muy bien con los Pivot Points.
📈Entradas Basadas en Heikin Ashi:
Las entradas Heikin Ashi son operaciones que son calculados en base a las velas Heikin Ashi pero su precio esta ejecutado a velas japonesas, evitando así́ los falsos resultados que se producen en graficas de velas Heikin, esto haciendo que en ciertos casos se obtengan mejores resultados en las estrategias que son ejecutadas con esta opción en comparación con las velas japonesas.
📊Panel de Control:
Una manera más visual y organizada de ver los resultados y datos necesarios producidos por nuestra estrategia, entre ellos podemos ver las fechas entre las que se hacen nuestras operaciones independientemente si se tiene activado algún filtro de tiempo, datos usuales como el Profit, Win Rate, Profit factor también son mostrados en este panel, adicionalmente se agregaron datos como el número total de operaciones, cuantos fueron ganancias y cuantos perdidas, el promedio de ganancias y pérdidas por cada operación y por ultimo las máximas ganancias y pérdidas seguidas, que son datos que nos serán muy útiles al elaborar nuestras estrategias.
Siéntete libre de usar esta plantilla para programar tus propias estrategias, si encuentras errores o quieres solicitar una nueva función házmelo saber en los comentarios o a través de mis redes sociales que se encuentran en mi perfil de tradingview.
| Actualización 1.1 | | ES |
➕Añadidos:
Filtro de sesiones de tiempo y filtro de días de la semana agregados al apartado de filtro de tiempo.
Opción para agregar apalancamiento a la estrategia.
5 Moving Averages, RSI, Stochastic RSI, ADX, y Parabolic Sar se han agregado como indicadores para la estrategia.
Puedes escoger entre los 6 indicadores disponibles la forma de operar, alerta de entrada o filtro de entrada.
Añadido la opción de ATR para Take Profit.
La información del ticker y la temporalidad ahora se muestran en el dashboard.
Añadido personalización de visualización y color de los plots de indicadores.
Añadido personalización de visualización y color de los plots de operaciones mostradas en grafica.
📝Cambios:
Ahora al activar el filtro de tiempo es opcional añadir una fecha y hora de inicio o fin, pudiendo únicamente agregar una fecha de inicio o solamente una fecha de fin.
Los plots de operaciones han cambiados de plot() a creación de líneas con line.new().
Los plots de indicadores ahora se pueden controlar desde el apartado "plots".
Ahora se puede elegir el rango aceptable y negable de profit, winrate y profit factor desde el apartado "plots" para mostrarse en el dashboard.
Cambios estéticos en las separaciones de secciones dentro del apartado de configuraciones y dentro del propio código.
Se ha cambiado la función que hacía que los indicadores dieran entradas en base a velas heikin ashi, mire el código para más información.
⚙️Arreglos:
El dashboard label ahora se proyecta correctamente en todas las temporalidades incluyendo las temporalidades personalizadas.
Se han eliminado líneas y variables innecesarias para ocupar menos espacio en el código.
Se ha optimizado todo el código en general para evitar el uso de variables, líneas innecesarias y evitar los cálculos innecesarios, liberando espacio para declarar más variables y poder utilizar menos líneas de código.
AlgoTrade DCA Bot Backtester█ OVERVIEW
This script can be used to backtest DCA Bots. It draws inspiration from 3Commas and has most settings that are available on 3Commas. It contains a few popular DCA Bot Presets that are well known in the community for you to test out! Preset used here: Kirigakure V4
█ FEATURES
DCA Preset (Custom, Standard TA,Urma Lite V3,Kirigakure V1,Kirigakure V3,Kirigakure V4)
Order Size Type (Fixed/% of equity to simulate compounding)
Base Order Size
Safety Order Size
Max Safety Trades Count
Price Deviation to open safety order %
Safety Order Volume Scale
Safety Order Step Scale
Take Profit %
Use ADR (Average Daily Range) as Take Profit
ADR length (if ADR as take profit is enabled)
Take Profit Type (% from total volume / % from base order)
Trailing Take Profit
Stop Loss
Deal Start Condition (Start ASAP) ▶ More Deal Starting Conditions will be added in the future
Bot Direction (Long / Short)
Start Time ▶ 1999-01-01 (Use this to always backtest the entire history)
End Time
This strategy also allows you to plot the Average Price and Take Profit of each trade, so it's easier to follow the trade and understand what's happening.
█ HOW TO USE
1. Select a DCA Preset and change the initial capital to the exact amount that is required (seen in the error message on top of the table). When using a Preset the following settings will be locked, meaning if you change them in the script's settings it won't have any effect:
Base Order Size
Safety Order Size
Max Safety Trades Count
Price Deviation to open safety order %
Safety Order Volume Scale
Safety Order Step Scale
Use ADR (Average Daily Range) as Take Profit
1.1 When using Presets you can choose the Order Size Type of Fixed or % of equity which simulates compounding
1.2 Choose a Direction and a Start and End Time
2. To backtest customized settings choose the preset "Custom"
2.1 All other settings are now "unlocked" and can be used
█ LIMITATIONS
Whenever a DCA preset is changed the initial_capital needs to be changed to the exact amount the settings require. If the initial_capital is not the same there will be an error of top of the table. To fix this error navigate to the Script's Settings and Properties and change the initial_capital to the same amount that is stated in the error.
DCA Bots with a high number of safety orders, e.g. 100, can run into an error that says "Maximum number of orders (9000) reached". If this error happens change the backtesting time to a shorter timeframe.
Using % of equity simulates compounding but is unrealistic because you cannot re-invest every single dollar
█ THANKS
This script in insipred by rouxam's "Backtesting 3commas DCA Bot v2" script
3C Reversal Filter v1In essence, this strategy is a heavily smoothed range filter.
This strategy includes a backtester and ability to connect it with your 3 commas bot(See adviced settings below)
The calculation steps below gives an example on how signals are made:
1. Calculating the price movement using ATR, % change, standard deviation etc..
2. Obtaining the smoothed price using SMA.
3. Obtaining the absolute value of the bar-to-bar change.
4. Applying EMA, twice, to the values in step 3.
5. Obtaining the slow trailing line by multiplying the result of step 4 by 1.618.
Think of it as a heavily smoothed price range
If the 1.618 value looks familiar, that’s because it’s used in Fibonacci sequences. You can of course experiment with other values. I’ve seen good results with both 2.618 and 4.236
What does the strategy do?
1. Determine Trend Detection
2. Detect Short-Term Momentum
3commas settings:
-For now you can only use simple bots.
-Create LONG and SHORT bots for the coins you like to trade and set up alerts(You can send long and short signal from the same alert)
-Set TP to 50% the strategy will handle buys and exits based on your inputs.
-Set safety orders to 0. I might add DCA to the strategy if testing proves that to be a good solution.
-When you have made the bots input the bot ID and token adress in the settings of the strategy.
-When creating the alert use this webhook :https://3commas.io/trade_signal/trading_view
-In the message field you use {{strategy.order.alert_message}} as the placeholder.
Cyatophilum 3Commas DCA Bot BacktesterAn indicator to backtest and automate 3Commas DCA Bots.
═════════════════════════════════════════════════════════════════════════
█ HOW IT WORKS
The indicator allows you to replicate your bot settings and get backtest results from the Strategy Tester and also a backtest panel with additional information on the safety orders.
You can also create alerts for each of the strategy events.
█ HOW TO USE
Choose a symbol that corresponds to your bot pair and exchange.
Pick a chart time frame as small as possible, usually 1 minute. The timeframe should always be smaller or equal to the deal start conditions timeframes.
Always use regular candle type.
Configure your deal start condition . You can combine several technical indicators to trigger an entry using a AND logical gate.
Configure your profit target
Use the Take Profit feature to set a target in percentage of price. You can also make it trail.
There is also a Stop Loss feature that is turned off by default.
Configure your safety orders
Replicate the safety orders from your bot into the indicator inputs.
Check your backtest parameters
Make sure that the initial capital and order size make sense. Since it is a pyramiding strategy with safety orders, the sum of all deals should not be bigger than the initial capital.
In this example: Initial capital is 0.02 BTC, which around 600$. I used 1000$ to be safe.
If you use % equity as order size, please note that it will create compounding.
Check the fees, by default they are set to 0.1%.
I also recommend to set a slippage that corresponds to your exchange's spread.
█ FEATURES
• Strategy direction
Configure wether to go long or short.
• Deal Start Conditions
The current conditions available are:
- Up to 4 MTF Trading View ratings conditions (Buy/Sell, Strong Buy/Sell)
- Up to 4 MTF RSI with configurable start conditions (Less/Greater than, Crossing Up/Down)
- Up to 2 MTF Ultimate Oscillator with configurable start conditions (Less/Greater than, Crossing Up/Down)
- MTF BB%-20-1 (length-deviation) with configurable start conditions (Less/Greater than, Crossing Up/Down)
- MTF BB%-20-2 (length-deviation) with configurable start conditions (Less/Greater than, Crossing Up/Down)
- Up to 2 MTF TA presets with the following options (Bollinger Bands, MFI, CCI, MACD, PSAR, SMA crosses, Heikin Ashi)
• Stop Loss and Take Profit
Configure your stop loss and take profit for long and short trades.
You can also make a trailing take profit.
• DCA (Safety orders)
Create up to 100 safety orders with configurable options for step and volume scaling, take profit from total volume, base and safety order size.
• Backtest Settings
Choose a backtest period, longs or shorts, wether to use limit orders or not.
Graphics
A Configuration panel with all the indicator settings, useful for sharing/saving a strategy.
A Backtest Results panel with additional information from the strategy tester.
█ ALERTS
The indicator is using the alert() calls: it only uses 1 alert slot to send order messages for each event (Long/Short entry, stop loss, take profit, safety order). This means free TV plans can create 1 complete strategy.
To set your alert messages, open the indicator settings and scroll to the bottom of the "inputs" tab.
Create your alert after you set the messages in the indicator settings, and make sure "Any alert() function call" is set in the alert option.
█ BACKTEST RESULTS
The backtest settings used in this snapshot are the following:
Initial Capital: 1000€
Order size: 0.003 BTC
Commission: 0.1 % per order
Slippage : 1 tick
Please read the author instructions below for access.
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
Zendog Backtest-DCA-Bot-3commasHi everyone,
This is a strategy that serves as a basic Backtester for 3commas DCA bots.
You can plugin your own studies into the Backtester, play around with their parameters as well with the DCA parameters and see how they can provide best result on historical data.
Features:
- Meaningful statistics that actually group orders under the same deal.
(base order + safety orders are the same deal, but Tradingview Strategy Tester shows them as separate trades)
See how many safety orders were used for each deal.
- Deal start condition: built in RSI-7 or external indicator
(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)
- Support for Long strategy for now (plan to add Short)
TTP Gavin's DCA BacktestPurpose:
The DCA Backtest script was designed to backtest the performance of any indicator using DCA bots.
"Open Deal ASAP" Deal Start Condition:
This script offers "open deal ASAP" deal start condition which will continuously open new deals. IT will wait for the current deal to close before opening a new one.
"Script" Deal Start Condition:
If you select the "Script" deal start condition we provide Bollinger Bands as an example. You can tweak the BB parameters from the indicator settings menu.
"Indicator" Deal Start Condition:
The third option is "Indicator". For this option to work you must have an indicator that plots a unique value that can be recognised as a BUY signal.
We recommend that your indicator plots 1 when it should buy and 0 when there's no signal.
Once you have in the same chart your indicator and your DCA backtest it's time to hook them up. For that follow these steps:
1) select "Indicator" as deal start condition
2) select your indicator from the list as "deal start source"
3) If you are following our recommendation then use 1 as "deal start value" so it can tell the DCA backtest when to open a deal. Make sure that your indicator only plots 0 or 1 so the DCA backtest can distinguish the BUY signal appropriately.
Limitations:
Each time you make changes and save your external indicator while you are backtesting, you will have to hook up the indicator again with the DCA backtest in the settings.
To avoid this, add as many parameters as you need to change in the external indicator so in that way you won't need to save changes to it and therefore will manage to avoid having to hook up the indicator with the DCA backtest.
Ultimate Strategy TemplateHello Traders
As most of you know, I'm a member of the PineCoders community and I sometimes take freelance pine coding jobs for TradingView users.
Off the top of my head, users often want to:
- convert an indicator into a strategy, so as to get the backtesting statistics from TradingView
- add alerts to their indicator/strategy
- develop a generic strategy template which can be plugged into (almost) any indicator
My gift for the community today is my Ultimate Strategy Template
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
For doing so:
1) Find in your indicator where are the conditions printing the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, ZigZag, Pivots, higher-highs, lower-lows or whatever indicator with clear buy and sell conditions
//@version=4
study(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
type_ma1 = input(title="MA1 type", defval="SMA", options= )
length_ma1 = input(10, title = " MA1 length", type=input.integer)
type_ma2 = input(title="MA2 type", defval="SMA", options= )
length_ma2 = input(100, title = " MA2 length", type=input.integer)
// MA
f_ma(smoothing, src, length) =>
iff(smoothing == "RMA", rma(src, length),
iff(smoothing == "SMA", sma(src, length),
iff(smoothing == "EMA", ema(src, length), src)))
MA1 = f_ma(type_ma1, close, length_ma1)
MA2 = f_ma(type_ma2, close, length_ma2)
// buy and sell conditions
buy = crossover(MA1, MA2)
sell = crossunder(MA1, MA2)
plot(MA1, color=color_ma1, title="Plot MA1", linewidth=3)
plot(MA2, color=color_ma2, title="Plot MA2", linewidth=3)
plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color_ma1, size=size.normal)
plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color_ma2, size=size.normal)
/////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Basically, I identified my buy, sell conditions in the code and added this at the bottom of my indicator code
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal , and -1 for the bearish signal
Now you can connect your indicator to the Strategy Template using the method below or that one
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings and in the Data Source field select your 🔌Connector🔌 (which comes from your indicator)
From then, you should start seeing the signals and plenty of other stuff on your chart
🔥 Note that whenever you'll update your indicator values, the strategy statistics and visual on your chart will update in real-time
Settings
- Color Candles : Color the candles based on the trade state (bullish, bearish, neutral)
- Close positions at market at the end of each session : useful for everything but cryptocurrencies
- Session time ranges : Take the signals from a starting time to an ending time
- Close Direction : Choose to close only the longs, shorts, or both
- Date Filter : Take the signals from a starting date to an ending date
- Set the maximum losing streak length with an input
- Set the maximum winning streak length with an input
- Set the maximum consecutive days with a loss
- Set the maximum drawdown (in % of strategy equity)
- Set the maximum intraday loss in percentage
- Limit the number of trades per day
- Limit the number of trades per week
- Stop-loss: None or Percentage or Trailing Stop Percentage or ATR
- Take-Profit: None or Percentage or ATR
- Risk-Reward based on ATR multiple for the Stop-Loss and Take-Profit
This script is open-source so feel free to use it, and optimize it as you want
Alerts
Maybe you didn't know it but alerts are available on strategy scripts.
I added them in this template - that's cool because:
- if you don't know how to code, now you can connect your indicator and get alerts
- you have now a cool template showing you how to create alerts for strategy scripts
Source: www.tradingview.com
I hope you'll like it, use it, optimize it and most importantly....make some optimizations to your indicators thanks to this Strategy template
Special Thanks
Special thanks to @JosKodify as I borrowed a few risk management snippets from his website: kodify.net
Additional features
I thought of plenty of extra filters that I'll add later on this week on this strategy template
Best
Dave
TradeChartist Donchian Channels Breakout Strategy™TradeChartist Donchian Channels Breakout Strategy is the strategy backtester version of ™TradeChartist Donchian Channels Breakout Filter .
===================================================================================================================
Features of ™TradeChartist Donchian Channels Breakout Strategy
========================================================
Option to plot Donchian Channels of user preferred length, based on the Source price in addition to High/Low Donchian Channels.
Generates trade entries based on user preferred Breakout Price. For example, if the user prefers HL2 as breakout price, irrespective of the Donchian Channels type, trade entries are generated only when hl2 price (average of high/low) breaks out of the upper or lower band.
Option to plot background colour based on Breakout trend. The bull zones are filled with green background, the Bear zones are filled with red background and the bar that broke out is filled with orange background.
Option to colour price bars using Donchian Channels price trend. The Donchian Channels basis line is plotted using the same colours as coloured bars as default.
Note: This script does not repaint. To use the script for trade entries, wait for the bar close without Backtester or Strategy entries (with Backtester) and use a second confirmator (includes fundamentals) based on asset type as some markets require users to have good pulse on the fundamentals as trading by Technicals/price action dynamic alone may not be safe.
Note: Trend Based Stochastic of the same DC Length can be used from ™TradeChartist Risk Meter for Trade Confirmations too.
===================================================================================================================
Best Practice: Test with different settings first using Paper Trades before trading with real money
===================================================================================================================
This is not a free to use strategy. Get in touch with me (PM me directly if you would like trial access to test the strategy)
Premium Scripts - Trial access and Information
Trial access offered on all Premium scripts.
PM me directly to request trial access to the scripts or for more information.
===================================================================================================================
Trading Safely Market Crusher Pro Strategy BuilderWith The Market Crusher Pro You Can Build Trading Strategies For Options, Futures, Cryptocurrencies, Equities, Commodities, Currencies, and Stock Market Indexes.
The Market Crusher Pro Buy And Sell Strategy Builder gives you the ability to back-test all tradeable markets. You can back test using specific trading times on any chart time frame before you execute any trades for both manual trading and automated trading.
The Market Crusher Pro Buy & Sell signals are determined utilizing our price range volatility algorithmic technical indicator designed to generate alpha.
The Market Crusher Pro Buy & Sell signals will only be visible during your specified trading times.
The Market Crusher Pro Profit Targets are determined in percentages and you can take profit up to 4 times per trade.
I suggest setting limit orders at profit targets.
To determine how much of position to close divide position size by number of profit targets
Example: If your position size is 100k and you are in a Long trade set 4 limit sell orders of 25k each at your 4 profit targets.
*Percentage of position to be closed for each trade is set to 25% however, you can adjust this to take profit 3 times by changing settings on 1st, 2nd, and 3rd profit targets to 33.3%, or 2 times by changing 1st and 2nd profit targets to 50%
Highlights:
Add to any ticker, and time frame
Specify trading times
Specify both long and short profit targets in percentages
Take profit up to 4 times per trade
Use either a fixed stop loss or a trailing stop loss or both
Set Strategy alerts
Prints on the current bar in real time
DOES NOT repaint several bars after the fact
*We only use candles for trading and back testing because, Heikin Ashi, Renko, Kagi, Point & Figure, and Range produce unrealistic results.
*Back test results below are based on a initial capital of $5000 and Trade using 10% of initial capital.
Please Note: For forex trading to enter a trade on EURUSD for example the spread is typically 1.2-2.0 pips to enter a trade so you are not charged a commission on every market buy or sell or for limit orders set at profit targets. We are not able to input this into back test settings.
Example: If you open a 100k position it will cost you $12-$20 assuming the spread is 1.2 to 2.0 pips
Please Note: All users get access to weekly trading and strategy building sessions and a interactive Q&A. You can get more information on these benefits as well as get access to the strategy builder by clicking the MC PRO link listed in signature section below
Bollinger Bands Breakout StrategyBollinger Bands Breakout Strategy is the strategy version of Bollinger Bands Filter study version, which can be found under my scripts page. The strategy goes long when price closes above the upper band and goes short signal when price closes below the lower band.
Bollinger Bands is a classic indicator that uses a simple moving average of 20 periods, along with plots of upper and lower bands that are 2 standard deviations away from the basis line. These bands help visualize price volatility and trend based on where the price is, in relation to the bands.
The strategy doesn't take into account any other parameters such as Volume / RSI / Fundamentals etc, so user must use discretion based on confirmations from another indicator or based on fundamentals. The strategy results are based on purely long and short trades and doesn't take into account any user defined targets or stop losses.
The strategy works great when the price closes above/below upper/lower bands with continuation on next bar. It is definitely useful to have this strategy or the Bollinger Bands filter along with other indicators to get early glimpse of breach/fail of bands on candle close during BB squeeze or based on volatility .
This can be used on Heikin Ashi candles for spotting trends, but HA candles are not recommended for trade entries as they don't reflect true price of the asset.
The strategy settings default is 55 SMA and 1 standard deviation for Bollinger Bands filter, but these can be changed from settings.
It is definitely worth reading the 22 rules of Bollinger Bands written by John Bollinger if interested in trading Bollinger Bands successfully.
TradeChartist PowerTracer Pro Backtester™TradeChartist PowerTracer Pro Backtester is the strategy script for backtesting ™TradeChartist PowerTracer Pro for best performance settings which can then be used with ™TradeChartist PowerTrader Pro to plot Trades emulating the backtester and use Alerts (once per bar) on real time price chart.
PowerTracer Backtester includes the following options in the settings.
PowerTracer setting - Power Plot Type - (PowerTracer, Bar-wise Power Holder)
PowerTracer setting - Timeframe Multiplier
PowerTracer setting - Smoothing Factor
Backtester setting - Trade Direction - (Both Longs and Shorts, Only Longs, Only Shorts)
Backtester setting - SL Type (Fixed Stop Loss, Trailing Stop Loss)
Backtester setting - Reference for Trailing SL (Close, High/Low)
Backtester setting - Stop Loss %
Backtester setting - Take Profit %
Backtester setting - Quantity to trade at TP %
Using combinations of the settings, the user can find optimal settings for the asset to deliver lucrative entry and exit signals with high ROI and minimal Drawdown which can then be used on PowerTracer Pro and PowerTrader Pro to plot signals and create alerts to start trading in real-time.
Example charts:
GBP-USD 1hr chart - (2,1,Trailing SL, close, 1,1,25)
BTC-USDT 15m chart - (4,5, Trailing SL, high/low, 3.9,1.2,15)
SPX 1hr chart - (1,3, Trailing SL, high/low, 3, 2, 50)
This backtester needs the following scripts to generate signals and plots on main price chart and for real-time alerts
™TradeChartist PowerTracer Pro
™TradeChartist PowerTrader Pro
===================================================================================================================
This is not a free to use indicator. Get in touch with me (PM me directly if you would like trial access to test the indicator)
Premium Scripts - Trial access and Information
Trial access offered on all Premium scripts.
PM me directly to request trial access to the scripts or for more information.
===================================================================================================================
[STRATEGY] Moving Average CrossoverThis is a backtester for the Moving Average Crossover indicator.
This tool allows you to backtest 4096 combinations of different MA types x customizable periods x customizable take-profits and stop-losses = almost limitless possibilities.
Study version can be found here:
Make Moving Averages Great Again!
Hull Suite StrategyConverted the hull suite into a strategy script for easy backtesting and added ability to specify a time periods to backtest over.
Why is it ok to backtest on TradingView from now on!TradingView backtester has bad reputation. For a good reason - it was producing wrong results, and it was clear at first sight how bad they were.
But this has changed. Along with many other improvements in its PineScript coding capabilities, TradingView fixed important bug, which was the main reason for miscalculations. TradingView didn't really speak out about this fix, so let me try :)
Have a look at this short code of a swing trading strategy (PLEASE DON'T FOCUS ON BACKTEST RESULTS ATTACHED HERE - THEY DO NOT MATTER). Sometimes entry condition happens together with closing condition for the already ongoing trade. Example: the condition to close Long entry is the same as a condition to enter Short. And when these two aligned, not only a Long was closed and Short was entered (as intended), but also a second Short was entered, too!!! What's even worse, that second short was not controlled with closing conditions inside strategy.exit() function and it very often lead to losses exceeding whatever was declared in "loss=" parameter. This could not have worked well...
But HOORAY!!! - it has been fixed and won't happen anymore. So together with other improvements - TradingView's backtester and PineScript is now ok to work with on standard candlesticks :)
Yep, no need to code strategies and backtest them on other platforms anymore.
----------------
Having said the above, there are still some pitfalls remaining, which you need to be aware of and avoid:
Don't backtest on HeikenAshi, Renko, Kagi candlesticks. They were not invented with backtesting in mind. There are still using wrong price levels for entries and therefore producing always too good backtesting results. Only standard candlesticks are reliable to backtest on.
Don't use Trailing Stop in your code. TradingView operates only on closed candlesticks, not on tick data and because of that, backtester will always assume price has first reached its favourable extreme (so 'high' when you are in Long trade and 'low' when you are in Short trade) before it starts to pull back. Which is rarely the truth in reality. Therefore strategies using Trailing Stop are also producing too good backtesting results. It is especially well visible on higher timeframe strategies - for some reason your strategy manages to make gains on those huge, fat candlesticks :) But that's not reality.
"when=" inside strategy.exit() does not work as you would intuitively expect. If you want to have logical condition to close your trade (for example - crossover(rsi(close,14),20)) you need to place it inside strategy.close() function. And leave StopLoss + TakeProfit conditions inside strategy.exit() function. Just as in attached code.
If you're working with pyramiding, add "process_orders_on_close=ANY" to your strategy() script header. Default setting ("=FIFO") will first close the trade, which was opened first, not the one which was hit by Stop-Loss condidtion.
----------------
That's it, I guess :) If you are noticing other issues with backtester and would like to share, let everyone know in comments. If the issue is indeed a bug, there is a chance TradingView dev team will hear your voice and take it into account when working on other improvements. Just like they heard about the bug I described above.
P.S. I know for a fact that more improvements in the backtesting area are coming. Some will change the game even for non-coding traders. If you want to be notified quickly and with my comment - gimme "follow".