INVITE-ONLY SCRIPT

Full Range Trading Study with Alerts and DCA

Atualizado
snapshot
snapshot

Introduction

This is the study version of my range trading strategy. It is designed to be a “drop in” replacement for its twin strategy. I have replicated the analysis logic and entry and exit procedures to produce a nearly identical result set to the strategy. Other than the properties tab, the inputs dialog is exactly the same. Backtest the strategy to determine the best inputs to trade. Then apply the same inputs to this study to forward test. Alerts are available for trade entry, take profit close and stop-loss exit. Please see the strategy version for a complete description of the trading behavior of this script.

In brief, this script is intended to benefit from a range bound market. The trading behavior 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. This is accomplished by calculating pivot points from the price stream. Rising pivots are shorts and falling pivots are longs. I refer to pivots as a vertex in the inputs dialog box. The cone based measurement adds a peak, sides and a base to the calculation elements. This allows the inputs to focus on adjusting the location of trades and not just trend lines. The pivot points can be plotted on the backtest. You can use the vertex input values to move the pivots where you want trades to be. This script can be traded in four different modes: Long, Short, BiDir, and Ping Pong. When trading in “Ping Pong” mode long and short positions are intermingled continuously as long as there exists a detectable vertex. I also have a trend following version of this script for those not interested in trading the range.

This script employs a DCA feature which enables users to experiment with loss recovery techniques in the backtest. Here in the study the summary report displays the “Debt Sequence” number which can be used to manually increase the order size on subsequent trades at the broker. The script keeps track of debt incurred from losing trades. When the debt is recovered the “Debt Sequence” resets to zero so orders can return to the base size. Be sure to set the limiter to prevent your account from depleting capital during runaway markets.

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 consecutive loss limit to manually halt live trading on the broker side.

Design

This script uses twelve indicators on a single time frame and is approximately 1800 lines of Pine 4 code. 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: Volume, Histogram, Fractal, Candle and Macro. The backtest is used to determine the best fit for your desired trading instrument. The incorporation of five distinct pivot point calculations broadens the scope of the markets where this tool can be beneficial.

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

Indicator Repainting

Please see the strategy script for a more detailed description of the repaint problem. The goal of my repaint prevention in the study script is simply to ensure that my signal trading bias remains consistent between the strategy, study and broker. This script employs the following conventions in effort to avoid indicator repainting:

1. This script uses only 1 time frame. The chart interval.
2. Every entry and exit condition is evaluated on closed bars only.
3. Entry and exit plots are not triggered off trend line crossovers.
4. No security functions are called to avoid a look-ahead possibility.
5. Every contributing factor specified in the TradingView wiki regarding this issue has been addressed. Except the use of the exponential moving average which is essential to my strategy.
6. 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

This script does indeed bring up the TradingView warning dialog. The only reason for this is due to “peculiarities of the algorithm” regarding the EMA as stated in the wiki article.

The Bottom Line. Does this script repaint. Yes, it will repaint about as much as every other trading platform which combines backtest data with real time prices in a live trading scenario.

Usage

Please be aware that the purpose of the study script is to perform forward testing of the configuration established in the backtest process. Therefore, the usage here in the study begins with the backtest configuration parameters. The following steps provide instructions to get this study script connected to the TradingView alert notification system. For a detailed description of how to create a range trading system using this script please see the strategy version.

Step 1. Create a chart with the trading instrument and interval used in the backtest.
Step 2. Find this script in the “Invite Only” section of the Indicators Dialog and apply it to the current chart.
Step 3. Copy the values from the backtest input dialog to the study.
Step 4. Open the TradingView Alert window.
Step 5. In the “Condition” drop down field find and select the name of the script.
Step 6. A new drop down field will appear with the alerts available in the script. This script exposes the following six signals:
  • Long Entry Signal

  • Long Profit Signal

  • Long Stop-loss Signal

  • Short Entry Signal

  • Short Profit Signal

  • Short Stop-loss Signal

Select the signal for which you want notification.
Step 7. In the “Options” field select the frequency of the alert. Typically, "Once Per Bar" or "Once Per Bar Close" will be sufficient.
Step 8. Set the expiration date and time.
Step 9. Select the action of the alert. Currently TradingView offers six different actions:
  • Notify on App

  • Show Popup

  • Send Email

  • Webhook URL

  • Play Sound

  • Send Email to SMS

Step 10. Create a message to to transmitted with the alert. The script provides a default message which can be overridden with any custom description. The price, time and other reserved chart elements can be included in the message
Step 11. Click the “Create” button to generate this single alert.
Step 12. Repeat steps 1 through 11 for every signal you wish to receive.

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 76

This build contains many updates addressing various issues which surfaced during the ongoing beta test. Most of the changes are contained and featured in the strategy version of this script. The study (this script) mirrors those changes where applicable. Please use strategy version 107 with study version 76 as a matched set. Thank you all for your valuable input.

Complementary Mode

Complementary long and short modes are changed in this version. This modification broadens the scope of the feature thereby increasing the number of trades. This change is not backward compatible with previous versions and breaks existing templates. Complementary mode puts the system into a trend following bias long or short. The resultant script behavior is range trading along persistent price pressure.


Summary Report

Additional fields are added to the summary report in this build. The strategy version contains a margin call indicator which can be used to stress test the simulated account capital. The script summary report is the navy blue label that shows up at the live end of the chart. It contains useful information not produced in the TradingView performance report. The summary report has two sections the upper and lower. Elements of the lower section can be used to compare the study with the strategy version. The upper section contains elements useful in live trading.

Strategy Inputs

Two new fields are added to the inputs dialog box. The strategy version of this script has seven new inputs. These two plus five more intended to aid in producing a Sharpe Ratio for this script. The Sortino Ratio, R-Squared, Beta Calculation and others are also supported. Please see the strategy version for more information. The following fields have been added in this build:


- 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.

- Composite Strength/Weakness - A new field was added to the long and short sections of the input dialog. The “Buy Composite Strength” and “Sell Composite Weakness” feature exhibits trend following behavior in its titular direction. Similar to the “Complementary Long/Short Mode” except new trades are generated not just excluded. This feature only works when exclusively “Long” or “Short” trading modes are selected. The basic premise is fewer trades are generated during the backtest when unidirectional modes are enabled. However, trading opportunities apparent on the chart are not taken since the configuration requires a strong pullback entry. Loosening the configuration permits more trades but at worse price points. This feature attempts to solve this problem by determining the composite price pressure and generating trades in the commensurate direction. When enabled, a more complete backtest with fewer dead spots is created. The result of the backtest, ideally, is range trading during indecisive market sessions and trend following during complementary price moves.
Notas de Lançamento
Update - Build 85

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. This study replicates the code from its twin strategy. Strategy build 114 and study build 85 are a matched set. Thank you all for your many helpful suggestions during this beta test period.

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 85 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 107

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. Please see the strategy version of this script for information on how to establish the input parameters to this study.

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.

Build 107 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.

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.
Bill Williams IndicatorscryptointradayStocksswingtradingVolatilityVolume

Script sob 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.

O TradingView não sugere pagar por um script e usá-lo, a menos que você confie 100% no seu autor e entenda como o script funciona. Em muitos casos, você pode encontrar uma boa alternativa de código aberto gratuita nos nossos Scripts da Comunidade.

Instruções do autor

Quer usar esse script no gráfico?

Aviso: por favor leia antes de solicitar acesso.

Aviso legal