tradingtudi

Total Trend Follow Study with Alerts, Pyramid and DCA

tradingtudi Cập nhật   

Introduction

This is the study version of my trend following 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, stop-loss exit and pyramid level. 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 long duration trending markets. The trading behavior 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. My trend following script uses the same pivot point calculations used by my range trader but this time rising pivots are long and falling pivots are short. 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 Flip Flop.

This script replicates the TradingView pyramid feature by adding a field to the inputs tab. Pyramiding works the same way in this script as its twin strategy. Each pyramid level increases the order size as a multiple of its level. This makes it easy to comply with NFA FIFO Rule 2-43(b) if the trades are executed here in America. The current pyramid level is reported in the summary label when reports are enabled. You can use this value to manually adjust the position size in your forward testing. I also expose an alert when the pyramid threshold is breached. Use the TradingView alert window to send yourself a message when the level increases.

In addition to pyramiding this script employs a DCA feature which can increase the order size in response to stopped out or winning streak trades. The number of losing trades is tracked through the “Debt Sequence” value displayed in the summary report. When the debt is recovered the sequence number resets to zero. You can use the “Debt Sequence” number to manually manage DCA on your forward test. The main difference between DCA and pyramids is that this implementation of DCA applies to new trades while pyramids affect open positions. If DCA is enabled be sure to set the limiter to prevent your account from depleting capital during runaway markets.

I also have a range trading version of this script for those not interested in trend following.

Design

This script is approximately 1800 lines of Pine 4 code and implements 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. 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.

Indicator Repainting

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 TradingView wiki has an in depth article on this subject in regard to the elements of the Pine language which contribute or are susceptible to this effect. In dealing with this problem from a prevention aspect in Pine, you have to accept some repaint to occur.

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 actually turned out to be kind of a job since it interfered with another project goal to synchronize the entry and exits between the strategy and study scripts. The script execution engines are different between the Pine strategy and study. While the primary chart interval is quite manageable the higher time frame requires the security() function. TradingViewʼs higher time frame implementation, which interleaves the chart interval, combined with the critical “lookahead” parameter makes the solution necessarily complex. According the wiki regarding this issue, best practice comes down to the following two methods:

1. a = security(syminfo.tickerid, 'D', close, lookahead=barmerge.lookahead_on)
2. indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrTF = barstate.isrealtime ? 0 : 1
a0 = security(syminfo.tickerid, 'D', close,lookahead=barmerge.lookahead_off)
a = a0

This script employs method 2 with the only problem being the Pine sar() function which does not expose its internal bar series. The best work around would require hand coding the parabolic but the script is at the maximum local scopes and run-time duration so that option is not viable. So far, this hasn't proven to be much of a problem. I'm currently running several symbols, forex and crypto, the strategy and study remain highly correlated with no instances of completely opposite real-time signals. However, I have received some alerts with no corresponding plot on the chart but so far it only occurred on one symbol. I will continue to monitor this problem.

The Bottom Line. Does this script repaint. Yes, it will repaint about as much as every other multi-interval script which employs the best practice solutions available in the Pine Language.

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 trend following 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 eight signals:
-- Long Entry Signal
-- Long Profit Signal
-- Long Stop-loss Signal
-- Long Pyramid
-- Short Entry Signal
-- Short Profit Signal
-- Short Stop-loss Signal
-- Short Pyramid
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.
Phát hành các Ghi chú:
Update - Build 101

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 475 with study version 101 as a matched set. Thank you all for your valuable input.

Pyramids

The precision of the pyramid entry point has been improved in this build. This change results in overall less number of pyramid trades but at better prices. Correspondingly, lower draw-downs are also noted over the course of the backtest period. Although the pyramid count can be increased to any number in the Properties tab, the Trend-V2 script is internally fixed at a maximum value of 5 pyramids. The total number of trades in an open position will not exceed a maximum of six trades regardless of the pyramid value in the TradingView properties tab. That is, the original trade plus five pyramids.

Indirectly, the “Pyramid Bale Out Offset” is also affected by this change in that the overall “weight” of the pyramid has been reduced in most cases. Whether a pyramid trade exits early or not is determined by the size of the trade and the minimum gain specified in the “Pyramid Bale Out Offset” field. Since a backtest now has fewer pyramid levels a backtest position may not exit at the same price as previously tested.

Summary Report

Additional fields are added to the summary report in this build. The strategy version contains a margin call indicator which can 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.
Phát hành các Ghi chú:
Update - Build 104

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 480 and study build 104 are a matched set. Thank you all for your many helpful suggestions during this beta test period

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 104, 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.
Phát hành các Ghi chú:
Update - Build 109

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

Please be aware that the TradingView servers experience ebb and flow of peak usage. This script exposes 8 different alerts which if configured enables the script to run as a TradingView service. During peak periods it is possible for this script to stop running in which case the Manage Alerts panel will show a red dot next to the script name. Simply restart the script by clicking the play icon if this happens. It's best to check the Manage Alerts panel periodically especially if you are using the signal in a live trading scenario.

Tập lệnh chỉ hiển thị cho người được mời

Quyền truy cập vào tập lệnh này bị hạn chế đối với người dùng được tác giả ủy quyền và thường yêu cầu thanh toán. Bạn có thể thêm nó vào mục yêu thích của mình, nhưng bạn sẽ chỉ có thể sử dụng nó sau khi yêu cầu sự cho phép từ tác giả. Liên hệ tradingtudi để thêm thông tin, hoặc làm theo hướng dẫn của tác giả bên dưới.

TradingView không đề xuất trả tiền cho một tập lệnh và sử dụng cho đến khi bạn hoàn toàn tin tưởng tác giả và hiểu cách thức hoạt động của tập lệnh. Trong nhiều trường hợp, bạn có thể tìm thấy một giải pháp thay thế nguồn mở miễn phí trong Thư viện Công cộng của chúng tôi.

Thông báo miễn trừ trách nhiệm

Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.

Bạn muốn sử dụng tập lệnh này trên biểu đồ?

Cảnh báo: vui lòng đọc trước khi yêu cầu quyền truy cập.