tradingtudi

Full Range Trading Strategy with DCA - Crypto, Forex, Stocks

tradingtudi Atualizado   

Introduction

This is a Pine 4 range trading 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 range trading strategy, the behavior of the script is to buy on weakness and sell on strength. As such trade orders are placed in a counter direction to price pressure. What you will see on the chart is a short position on peaks and a long position on valleys. Just to be clear, the range as well as trends are merely illusions as the chart only receives prices. However, this script attempts to calculate pivot points from the price stream. Rising pivots are shorts and falling pivots are longs. I refer to pivots as a vertex in this script which adds structural components to the chart formation. When trading in “Ping Pong” mode long and short positions are intermingled continuously as long as there exists a detectable vertex. Unfortunately, this can work against your backtest profitability on long duration trends where prices continue in a single direction without pullback. I have designed various features in the script to compensate for this event. A well configured script should perform in a range bound market and minimize losses in a trend. I also have a trend following version of this script for those not interested in trading the range. Please be aware these are two types of traders. You should know who you are.

This script employs a DCA feature which enables users to experiment with loss recovery techniques. This is an 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. This implementation of DCA does not use pyramid levels. Only the order size on subsequent new trades are affected. Pyramids on the other hand increase the size of open positions. If you are interested in seeing pyramids in action please see the trend version of this script which features both DCA and pyramids. While DCA is a popular feature in crypto trading, it can make you a “bag” holder if your not careful. In other markets, especially margin trading, you’ll need a well funded account and much trading experience to manage this feature safely.

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 twelve indicators on a single time frame. 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 vertices are calculated using one of five featured indicators. Each indicator is actually a composite of calculations which produce a distinct mean. This mathematical distinction enables the script to be useful on various instruments which belong to entirely different markets. In other words, at least one of these indicators should be able generate pivots on an arbitrarily selected instrument. Try each one to find the best fit.

The entire script is around 1800 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 nearly two years 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. Although the script can be implemented on any interval, it has been optimized for small time frames down to 5 minutes. The 10 minute BTC/USD produces around 500 trades in 2 ½ months. The 1 hour BTC/USD produces around 1300 trades in 1 ½ years. 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.

Tackling this repainting issue has been a major project goal of this script. Based on my experience with Pine, most of the problems stem from TradingView’s implementation of multiple interval access. Whereas most platform provide a separate bar series for each interval requested, the Pine language interleaves higher time frames with the primary chart interval. The problem is exacerbated by allowing a look-ahead parameter to the Security function. The goal of my repaint prevention is simply to ensure that my signal trading bias remains consistent between the strategy, study and broker. That being said this is what I’ve done address this issue in this script:

1. This script uses only 1 time frame. The chart interval.
2. Every entry and exit condition is evaluated on closed bars only.
3. No security functions are called to avoid a look-ahead possibility.
4. Every contributing factor specified in the TradingView wiki regarding this issue has been addressed.
5. I’ve run a 10 minute chart live for a week and compared it to the same chart periodically reloaded. The two charts were highly correlated with no instances of completely opposite real-time signals.

The study does indeed bring up the TV warning dialog. The only reason for this is because the script uses an EMA indicator which according to TradingView is due to “peculiarities of the algorithm”.

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.

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 five 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 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 2. 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 2.
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 red markers and short trades on the blue.
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.
Step 8. Try a different indicator from Section 2 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. Go to Section 3 and enable “Apply Red Base To Base Margin”.
Step 10. Go to Section 4 and enable “Apply Blue Base To Base Margin”.
Step 11. Go to Section 2 and adjust “Minimum Base To Base Blue” and “Minimum Base To Base Red”. Observe the chart and note where the markers move relative to each other. Markers further apart will produce less trades but will reduce cutoffs in “Ping Pong” mode.
Step 12. Return to Section 3 and 4 and turn off “Base To Base Margin” which was enabled in steps 9 and 10.
Step 13. Turn off Show Markers in Section 2.
Step 14. Put in your Minimum Profit and Stop Loss in the first section. This is in pips or currency basis points (chart right side scale). Percentage is not currently supported. This is a fixed value minimum profit and stop loss. Also note that the profit is taken as a conditional exit on a market order not a fixed limit. The actual profit taken will almost always be greater than the amount specified. The stop loss, on the other hand, is indeed a hard number which is executed by the TradingView broker simulator when the threshold is breached. On the study version, the stop is executed at the close of the bar.
Step 15. Return to step 3 and select a Trading Mode (Long, Short, BiDir, Ping Pong). If you are planning to trade bidirectionally its best to configure long first then short. Combine them with “BiDir” or “Ping Pong” after setting up both sides of the trade individually. The difference between “BiDir” and “Ping Pong” is that “Ping Pong” uses position reversal and can cut off opposing trades less than the specified minimum profit. As a result “Ping Pong” mode produces the greatest number of trades.
Step 16. Take a look at the chart. Trades should be showing along the markers plotted earlier.
Step 17. Make adjustments to the Vertex fields in Section 2 until the TradingView performance report is showing a profit. This includes the “Minimum Base To Base” fields. If a profit cannot be achieved move on to Step 18.
Step 18. Improve the backtest profitability by adjusting the “Long Entry Net Change” and “Long Entry ROC” in Section 3.
Step 19. Improve the backtest profitability by adjusting the “Short Entry Net Change” and “Short Entry ROC” in Section 4.
Step 20. Improve the backtest profitability by adjusting the “Sparse Long Delta” in Section 3.
Step 21. Improve the backtest profitability by adjusting the “Chase Long Delta” in Section 3.
Step 22. Improve the backtest profitability by adjusting the “Long Adherence Delta” in Section 3. This field requires the “Adhere to Rising Trend” checkbox to be enabled.
Step 23. Try each checkbox in Section 3 and see if it improves the backtest profitability. The “Caution Lackluster Longs” checkbox only works when “Long Caution Mode” is enabled.
Step 24. Improve the backtest profitability by adjusting the “Sparse Short Delta” in Section 4.
Step 25. Improve the backtest profitability by adjusting the “Chase Short Delta” in Section 4.
Step 26. Improve the backtest profitability by adjusting the “Short Adherence Delta” in Section 4. This field requires the “Adhere to Falling Trend” checkbox to be enabled.
Step 27. Try each checkbox in Section 4 and see if it improves the backtest profitability. The “Caution Lackluster Shorts” checkbox only works when “Short Caution Mode” is enabled.
Step 28. Enable the reporting conditions in Section 5. 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 29. Examine the chart and see that trades are being placed in accordance with your desired trading goals. This is an important step. If your desired model requires multiple trades per day then you should be seeing hundreds of trades on the chart. Alternatively, you may be looking to trade fewer steep peaks and deep valleys in which case you should see trades at major turning points. Don’t simply settle for what the backtest serves you. Work your configuration until the system aligns with your desired model. Try changing indicators and even intervals if you cannot reach your simulation goals. Generally speaking, the histogram and Candle indicators produce the most trades. The Macro indicator captures the tallest peaks and valleys.
Step 30. 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.

Notas de Lançamento:

Update - Build 107

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

Strategy Inputs

Seven new fields are added to the inputs dialog box. Five of the new fields are located in the reports section of the inputs at the bottom of the inputs tab. The new report 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.

- Expand Reentry Scope - When enabled this feature extends the “Reentry Bar Window” beyond the number of bars specified. The “Reentry Bar Window” together with the “Reentry Minimum Span” are a loss prevention mechanism intended to reduce the number of consecutive counter trades during spiking price moves. For example, if the market exhibits a powerful down swing the natural behavior of the range trading script is to enter long trades in anticipation of a reversal. If the long trade is stopped new trades in the same direction will be reduced while the market remains within the period defined by the “Reentry Bar Window” and within the price range defined by the “Reentry Minimum Span”. When “Expand Reentry Scope” input is enabled trades will continue to be reduced in the same direction as the most recent stop-loss. This feature will reduce the number of trades the backtest will produce but can come in handy when trading instruments which routinely experience large price swings. It can be especially useful when trading on low volume cryptocurrency exchanges.
Notas de Lançamento:
Update - Build 114

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.

Candle Indicator

The candle indicator calculation is changed in this version. The previous version used the “Snap Candle” input as part of the indicator calculation which created a conflict with several other features that also used the snap candle measurement. As of Build 114 the candle indicator can only be adjusted via the six vertex settings. 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. The beta test surfaced numerous instances of trades being prematurely cut off by an opposing trade. Back in the day of currency hedging this wouldn’t be a problem but nowadays a trade in the opposite direction causes a position reversal. In “Ping Pong” mode a position reversal occurs according to the vertex structure established by the six vertex inputs. Blue vertices are short and red vertices are long. There are currently six anti-cutoff adjustments available.

– Entry Net Change

– Interleave Delta

– Decay Minimum Span

– Mandatory Snap

– Preserve Opportunistic

– Preserve Maturation

The “Decay Minimum Span” input is a floating point value which specifies the minimum distance from the vertex required for new opposing trades. The span is specified in the quote currency exactly as is in the minimum profit and stop loss fields.
Notas de Lançamento:
Update - Build 150

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:

– Volume Indicator
– Report Debt Reset
– Caution Lackluster Trades

As much as possible I tried to keep core functionality relevant to range trading. The intent of this tool is to experiment with different range trading configurations. The backtest can be setup to use 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 minute and 50 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.

New Inputs

Build 150 contains five new inputs which attempt to remedy problems reported during the ongoing beta test.

– Minimum Maturation
– Anti-chop Mode
– Follow Snap Direction
– Preserve Indebted Trades
– Mark Symbol Debt Sequence

Minimum Maturation

The “Minimum Long/Short Maturation” input supplies a value to the “Preserve Long/Short Maturation” checkbox. The two fields form an anti-cutoff mechanism effective only in “Ping Pong” mode. The longevity of the open position must exceed at least the number of bars designated by the minimum maturation value. “Ping Pong” mode will ignore position reversal signals until either the trade has exceeded the time specified or an outlier condition occurs.

Anti-chop Mode

The “Long/Short Anti-Chop” checkbox is intended to reduce position reversals after extreme price moves. Internally the scripts goes into a tug-of-war after the price has moved continuously in one direction. Since this is a range trading program, the natural tendency is for it to buy on weakness and sell on strength. However, the loss prevention logic of the script changes the trading bias according to price pressure. When enabled the “Anti-chop Mode” forces the script to counter trade exaggerated moves. During this time “Ping Pong” mode will ignore position reversal signals until the price has recovered. Please be advised that this feature may cause the backtest to sustain losses for the duration of a bull or bear run.

Follow Snap Direction

The “Follow Long/Short Snap Direction” checkbox is intended to reduce position reversals by adhering to the directional bias established by the most recent snap candle. When enabled new positions can only be created in the snap candle direction. The user can control the frequency of reversal by adjusting the snap candle magnitude. A larger snap candle may increase the accuracy of the backtest by sacrificing the total number of trades. In this case, the gain of the backtest may also be reduced.

Script apenas com convite

O acesso a este script é restrito aos usuários autorizados pelo autor e pode requerir pagamento. Você pode adicioná-lo a seus favoritos, mas só poderá utilizá-lo após solicitar permissão e obtê-la do autor. Contate tradingtudi para mais informações, ou siga as instruções do autor abaixo.

TradingView não sugere pagar por um script e usá-lo até que você confie 100% em seu autor e entenda como o script funciona. Em muitos casos você pode encontrar uma boa alternativa de código aberto gratuitamente nos Scripts da Comunidade.

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.

Quer usar esse script no gráfico?

Aviso: por favor leia antes de solicitar acesso