tradingtudi

Total Trend Follow Strategy with Pyramid and DCA

tradingtudi Mis à jour   

Introduction

This is a Pine 4 trend following strategy. It has a twin study with several alerts. The design intent is to produce a commercial grade signal generator that can be adapted to any symbol and interval. Ideally, the script is reliable enough to be the basis of an automated trading system web-hooked to a server with API access to crypto, forex and stock brokerages. The strategy can be run in three different modes: long, short and bidirectional.

As a trend following strategy, the behavior of the script is to buy on strength and sell on weakness. As such the trade orders maintain its directional bias according to price pressure. What you will see on the chart is long positions on the left side of the mountain and short on the right. Long and short positions are not intermingled as long as there exists a detectable trend. This is extremely beneficial feature in long running bull or bear markets. The script uses multiple setups to avoid the situation where you got in on the trend, took a small profit but couldn’t get back in because the logic is waiting for a pullback or some other intricate condition.

Deep draw-downs are a characteristic of trend following systems and this system is no different. However, this script makes use of the TradingView pyramid feature accessible from the properties tab. Additional trades can be placed in the draw-down space increasing the position size and thereby increasing the profit or loss when the position finally closes. Each individual add on trade increases its order size as a multiple of its pyramid level. This makes it easy to comply with NFA FIFO Rule 2-43(b) if the trades are executed here in America. The inputs dialog box contains various settings to adjust where the add on trades show up, under what circumstances and how frequent if at all. Please be advised that pyramiding is an advanced feature and can wipe out your account capital if your not careful. During the backtest use modest setting with realistic capital until you discover what you think you can handle.

In addition to pyramiding this script employs DCA which enables users to experiment with loss recovery techniques. This is another advanced feature which can increase the order size on new trades in response to stopped out or winning streak trades. The script keeps track of debt incurred from losing trades. When the debt is recovered the order size returns to the base amount specified in the TV properties tab. The inputs for this feature include a limiter to prevent your account from depleting capital during runaway markets. The main difference between DCA and pyramids is that this implementation of DCA applies to new trades while pyramids affect open positions. DCA is a popular feature in crypto trading but can leave you with large “bags” if your not careful. In other markets, especially margin trading, you’ll need a well funded account and much experience.

Consecutive loss limit can be set to report a breach of the threshold value. Every stop hit beyond this limit will be reported on a version 4 label above the bar where the stop is hit. Use the location of the labels along with the summary report tally to improve the adaptability of system. Don’t simply fit the chart. A good trading system should adapt to ever changing market conditions. On the study version the consecutive loss limit can be used to halt live trading on the broker side (Managed manually).

Design

This script uses nine indicators on two time frames. The chart (primary) interval and one higher time frame which is based on the primary. The higher time frame identifies the trend for which the primary will trade. I’ve tried to keep the higher time frame around five times greater than the primary. The original trading algorithms are a port from a much larger program on another trading platform. I’ve converted some of the statistical functions to use standard indicators available on TradingView. The setups make heavy use of the Hull Moving Average in conjunction with EMAs that form the Bill Williams Alligator as described in his book “New Trading Dimensions” Chapter 3. Lag between the Hull and the EMAs form the basis of the entry and exit points. The alligator itself is used to identify the trend main body.

The entire script is around 1700 lines of Pine code which is the maximum incidental size given the TradingView limits: local scopes, run-time duration and compile time. I’ve been working on this script for over a year and have tested it on various instruments stocks, forex and crypto. It performs well on higher liquidity markets that have at least a year of historical data. Though it can be configured to work on any interval between 5 minutes and 1 day, trend trading is generally a longer term paradigm. For day trading the 10 to 15 minute interval will allow you to catch momentum breakouts. For intraweek trades 30 minutes to 1 hour should give you a trade every other a day. Four hours and above are for seasoned deep pocket traders. Originally, this script contained both range trading and trend following logic but had to be broken into separate scripts due to the aforementioned limitations.

Inputs to the script use cone centric measurements in effort to avoid exposing adjustments to the various internal indicators. The goal was to keep the inputs relevant to the actual trade entry and exit locations as opposed to a series of MA input values and the like. As a result the strategy exposes over 50 inputs grouped into long or short sections. Inputs are available for the usual minimum profit and stop-loss as well as safeguards, trade frequency, DCA, modes, presets, reports and lots of calibrations. The inputs are numerous, I’m aware. Unfortunately, at this time, TradingView does not offer any other method to get data in the script. The usual initialization files such as cnf, cfg, ini, json and xml files are currently unsupported.

Example configurations for various instruments along with a detailed PDF user manual is available.

Indicator Repainting And Anomalies

Indicator repainting is an industry wide problem which mainly occurs when you mix backtest data with real-time data. It doesn't matter which platform you use some form of this condition will manifest itself on your chart over time. The critical aspect being whether live trades on your broker’s account continue to match your TradingView study. Since this trading system is featured as two separate scripts, indicator repainting is addressed in the study version. The strategy (this script) is intended to be used on historical data to determine the appropriate trading inputs to apply in the study. As such, the higher time frame of this strategy will indeed repaint. Please do not attempt to trade from the strategy. Please see the study version for more information.

One issue that comes up when comparing the strategy with the study is that the strategy trades show on the chart one bar later than the study. This problem is due to the fact that “strategy.entry()” and “strategy_exit()” do not execute on the same bar called. The study, on the other hand, has no such limitation since there are no position routines. However, alerts that are subsequently fired off when triggered in the study are dispatched from the TradingView servers one bar later from the study plot. Therefore the alert you actually receive on your cell phone matches the strategy plot but is one bar later than the study plot. A lot can happen in four hours if you are trading off a 240 bar.

Please be aware that the data source matters. Cryptocurrency has no central tick repository so each exchange supplies TradingView its feed. Even though it is the same symbol the quality of the data and subsequently the bars that are supplied to the chart varies with the exchange. This script will absolutely produce different results on different data feeds of the same symbol. Be sure to backtest this script on the same data you intend to receive alerts for. Any example settings I share with you will always have the exchange name used to generate the test results.

Usage

The following steps provide a very brief set of instructions that will get you started but will most certainly not produce the best backtest. A trading system that you are willing to risk your hard earned capital will require a well crafted configuration that involves time, expertise and clearly defined goals. As previously mentioned, I have several example configs that I use for my own trading that I can share with you along with a PDF which describes each input in detail. To get hands on experience in setting up your own symbol from scratch please follow the steps below.

The input dialog box contains over 50 inputs separated into seven sections. Each section is identified as such with a makeshift separator input. There are three main areas that must to be configured: long side, short side and settings that apply to both. The rest of the inputs apply to pyramids, DCA, reporting and calibrations. The following steps address these three main areas only. You will need to get your backtest in the black before moving on to the more advanced features

Step 1. Setup the Base currency and order size in the properties tab.
Step 2. Select the calculation presets in the Instrument Type field.
Step 3. Select “No Trade” in the Trading Mode field.
Step 4. Select the Histogram indicator from section 3. You will be experimenting with different ones so it doesn’t matter which one you try first.
Step 5. Turn on Show Markers in Section 3.
Step 6. Go to the chart and checkout where the markers show up. Blue is up and red is down. Long trades show up along the blue markers and short trades on the red.
Step 7. Make adjustments to Base To Vertex and Vertex To Base net change and roc in section 3. Use these fields to move the markers to where you want trades to be. Blue is long and red is short.
Step 8. Try a different indicator from section 3 and repeat Step 7 until you find the best match for this instrument on this interval. This step is complete when the Vertex settings and indicator combination produce the most favorable results.
Step 9. Turn off Show Markers in Section 3.
Step 10. Enable the Symmetrical and Deviation calculation models at the top of section 5 and 6 (Symmetrical, Deviation).
Step 11. Put in your Minimum Profit and Stop Loss in the first section. This is in pips or currency basis points (chart right side scale)

Step 12. Return to step 3 and select a Trading Mode (Long, Short, BiDir, Flip Flop). If you are planning to trade bidirectionally its best to configure long first then short. Combine them with BiDir or Flip Flop after setting up both sides of the trade individually.

Step 13. Trades should be showing on the chart.
Step 14. Make adjustments to the Vertex fields in section 3 until the TradingView performance report is showing a profit.
Step 15. Change indicators and repeat step 14. Pick the best indicator.
Step 16. Use the check boxes in sections 5 and 6 to improve the performance of each side.
Step 17. Try adding the Correlation calculation model to either side. This model can sometimes produce a negative result but can be improved by enabling “Adhere To Markers” or “Narrow Correlation Scope” in the sections 5 and 6.
Step 18. Enable the reporting conditions in section 7. Look for long runs of consecutive losses or high debt sequences. These are indications that your trading system cannot withstand sudden changes in market sentiment.
Step 19. Examine the chart and see that trades are being placed in accordance with your desired trading model.
Step 20. Apply the backtest settings to the study version and perform forward testing.

This script is open for beta testing. After successful beta test it will become a commercial application available by subscription only. I’ve invested quite a lot of time and effort into making this the best possible signal generator for all of the instruments I intend to trade. I certainly welcome any suggestions for improvements. Thank you all in advance.

Notes de version:

Update - Build 475

This build contains many updates addressing various issues which surfaced during the ongoing beta test. Thank you all for your valuable input.

Strategy Inputs

Five new fields are added to the inputs dialog box. All of the new fields are located in the reports section of the inputs at the bottom of the inputs tab. The new inputs primarily provide support for calculating actual Sharpe Ratios and other risk / performance metrics. The TradingView performance report does not produce a scalable Sharpe Ratio which is unfortunate considering the limited data supplied to the backtest. The new fields made available in this build are intended to enable users to measure the performance of this script using various industry standard risk metrics. In particular, The Sharpe Ratio, Sortino Ratio, Alpha Calculation, Beta Calculation, R-Squared and Monthly Standard Deviation. Other than the performance metrics support, notional leverage has been added to simulate margin call likelihood. The following fields have been added in this build:

- Performance Bond Leverage - Integer number which specifies the leverage to apply to the margin call calculation. Basically, you want to know if the account capital you specified in the properties tab is sufficient to trade this script with the order size and DCA parameters needed. TradingView does not halt trading when the account capital is depleted nor do you receive notification of such an event. Input the leverage you intend to trade with and simulate the stress on your account capital. When the check box labeled “Report Margin Call” is enabled a marker will plot on the chart at the location where the threshold was breached. Additionally, the Summary Report will indicated such a breach has occurred during the backtest. Please note that the margin calculation uses a performance bond contract model which is the same type of leverage applied to Forex accounts. This is not the same leverage as stock margin accounts since shares are not actually borrowed. It is also not applicable to futures contracts since we do not calculate maintenance margin. Also note that the account margin and buying power are calculated using the U.S. Dollar as a funding currency.

- Report Margin Call - This checkbox is used to enable buying power calculations in the script. If, during the backtest, the buying power of the account becomes negative an orange label will plot below the bar where the threshold was breached. Please see input description “Performance Bond Leverage” for a detailed description of this feature.
Notes de version:
Update - Build 480

This build addresses several more issues from the final phase of the beta test. The beta test of this script is nearly complete and I expect it to be ready for commercial use by the 1st of the new year. Thank you all for your many helpful suggestions.

Pyramid Bale Out Offset

The “Pyramid Bale Out Offset” is changed in this version. The previous version used the “Snap Candle” value as part of the bale out threshold calculation. This proved to be unreliable as critical bale outs were missed. This version, Build 480, uses the “Rise Event” and “Fall Event” settings to determine the bale out point. This change is not backward compatible with previous versions and breaks existing templates.

Decay Minimum Span

This is a new input which appears in the long and short sections of the Inputs Dialog Box. During the beta test some instruments exhibited sudden trend changes where this script could not adapt until much later in the price move. The "Decay Minimum Span" can be used to provide some minor resistance to the primary trend so that a magnitude change in direction can be detected sooner. Although this feature was originally developed for the range trading script it has also proven to be beneficial in a trend following application. Especially, when the Histogram Indicator is selected. The “Decay Minimum Span” input is a floating point value which specifies the minimum distance from the vertex required for new trades. The span is specified in the quote currency exactly as is in the minimum profit and stop loss fields.
Notes de version:
Update - Build 490

This build is intended to reduce the script compile time and thereby prevent timeout errors when applied to the chart. To accomplish this goal the script code was heavily refactored and some lessor used features were removed. Specifically, the following features are removed from this build:

– Flip Flop Trading Mode
– Minimize Trade duration
– Volume Indicator
– Macro Indicator
– Report Debt Reset

As much as possible I tried to keep core functionality relevant to trend trading. Ideally, you can still use this tool to experiment with different trend following configurations. The backtest can be setup to use Pyramids, DCA and variable leverage ratios to provide you with an overall picture of what to expect from your selected input parameters. I decided to keep the Sharpe Ratio and Rate of Return reports since those features are an important metric to fund managers and portfolio investors.

This script contains approximately 1800 lines of Pine 4 code which consists mostly of math calculations with very little plotting. Even with the feature purge and streamlining of the code the script still requires 1.5 minutes (1 minute and 30 seconds) to initially load on the chart. TradingView does an excellent job of caching compiled Pine scripts so you will typically only incur the full compile the first time it is applied to the chart. Please wait for the hovering dots to disappear before clicking on the setting dialog icon.

On the BTC/USD backtest showing here I used 1 Bitcoin, a minimum profit of 500 dollars, a stop of 500 dollars, a limit offset of 50 dollars, the fractal indicator and a 5 pyramid max value. DCA is off. Also Mark Pyramid Levels (blue triangles) are enabled along with a 720 ROR Sample Period (red labels). The buying power reflects a leverage ratio of 2:1 (Performance Bond Leverage).

Script sur invitation seulement

L'accès à ce script est limité aux utilisateurs autorisés par l'auteur et nécessite généralement un paiement. Vous pouvez l'ajouter à vos favoris, mais vous ne pourrez l'utiliser qu'après avoir demandé et obtenu l'autorisation de son auteur. Contactez tradingtudi pour plus d'informations, ou suivez les instructions de l'auteur ci-dessous.

TradingView ne suggère pas de payer pour un script et de l'utiliser avant d'avoir 100% confiance en son auteur et de comprendre son fonctionnement. Dans de nombreux cas, vous pouvez trouver gratuitement une bonne alternative open-source dans nos Scripts communautaires.

Clause de non-responsabilité

Les informations et les publications ne sont pas destinées à être, et ne constituent pas, des conseils ou des recommandations en matière de finance, d'investissement, de trading ou d'autres types de conseils fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.

Vous voulez utiliser ce script sur un graphique ?

Avertissement : Veuillez lire avant de demander l'accès.