reees

Harmonic Pattern Detection, Prediction, and Backtesting Tool

reees Actualizado   
Overview:

The ultimate harmonic XABCD pattern identification, prediction, and backtesting system.

Harmonic patterns are among the most accurate of trading signals, yet they're widely underutilized because they can be difficult to spot and tedious to validate. If you've ever come across a pattern and struggled with questions like "are these retracement ratios close enough to the harmonic ratios?" or "what are the Potential Reversal levels and are they confluent with point D?", then this tool is your new best friend. Or, if you've never traded harmonic patterns before, maybe it's time to start. Put away your drawing tools and calculators, relax, and let this indicator do the heavy lifting for you.
 
-  Identification   - 
An exhaustive search across multiple pivot lengths ensures that even the sneakiest harmonic patterns are identified. Each pattern is evaluated and assigned a score, making it easy to differentiate weak patterns from strong ones. Tooltips under the pattern labels show a detailed breakdown of the pattern's score and retracement ratios (see the Scoring section below for details).

-  Prediction  -
After a pattern is identified, paths to potential targets are drawn, and Potential Reversal Zone (PRZ) levels are plotted based on the retracement ratios of the harmonic pattern. Targets are customizable by pattern type (e.g. you can specify one set of targets for a Gartley and another for a Bat, etc).

-  Backtesting  -
A table shows the results of all the patterns found in the chart. Change your target, stop-loss, and % error inputs and observe how it affects your success rate. 

//------------------------------------------------------
// Scoring
//------------------------------------------------------

A percentage-based score is calculated from four components:

(1)  Retracement % Accuracy  -  this measures how closely the pattern's retracement ratios match the theoretical values (fibs) defined for a given harmonic pattern. You can change the "Allowed fib ratio error %" in Settings to be more or less inclusive.
(2)  PRZ Level Confluence  -  Potential Reversal Zone levels are projected from retracements of the XA and BC legs. The PRZ Level Confluence component measures the closeness of the closest XA and BC retracement levels, relative to the total height of the PRZ. 
(3)  Point D / PRZ Confluence - this measures the closeness of point D to either of the closest two PRZ levels (identified in the PRZ Level Confluence component above), relative to the total height of the PRZ. In theory, the closer together these levels are, the higher the probability of a reversal.
(4)  Leg Length Symmetry - this measures the ΔX symmetry of each leg. You can change the "Allowed leg length asymmetry %" in settings to be more or less inclusive.

So, a score of 100% would mean that (1) all leg retracements match the theoretical fib ratios exactly (to 16 decimal places), (2) the closest XA and BC PRZ levels are exactly the same, (3) point D is exactly at the confluent PRZ level, and (4) all legs are exactly the same number of bars. While this is theoretically possible, you have better odds of getting struck by lightning twice on a sunny day.

Calculation weights of all four components can be changed in Settings.

//------------------------------------------------------
// Targets
//------------------------------------------------------

A hard-coded set of targets are available to choose from, and can be applied to each pattern type individually:

(1)  .618 XA  =  .618 retracement of leg XA, measured from point D
(2)  1.272 XA  =  1.272 retracement of leg XA, measured from point D
(3)  1.618 XA  =  1.618 retracement of leg XA, measured from point D
(4)  .618 CD  =  .618 retracement of leg CD, measured from point D
(5)  1.272 CD  =  1.272 retracement of leg CD, measured from point D
(6)  1.618 CD  =  1.618 retracement of leg CD, measured from point D
(7)  A = point A
(8)  B = point B
(9)  C = point C

//------------------------------------------------------
// Stops
//------------------------------------------------------

Stop-loss levels are also user-defined, in one of three ways:

(1)   % beyond the furthest PRZ level (below the PRZ level for bullish patterns, and above for bearish)
(2)  % beyond point D
(3)  % of distance to Target 1, beyond point D. This method allows for a proper Risk:Reward approach by defining your potential losses as a percentage of the potential gains. This is the default.

//------------------------------------------------------
// Results Table / Backtesting Statistics
//------------------------------------------------------

To properly assess the effectiveness of a specific pattern type, a time limit is enforced for a completed pattern to reach the targets or the stop level. When this time limit expires, the pattern has "timed out", and is no longer considered in the Success Rate statistics. During the time limit period, if price reaches Target 1 before reaching the Stop level, the pattern is considered successful. Conversely, if price reaches the Stop level before reaching Target 1, the pattern is considered a failure. The time limit can be changed in Settings, and is defined in terms of the total pattern length (point X to point D). It is set to 1.5 by default.

Increasing the time limit value will give you more realistic Success Rate values, but will less accurately represent the success rate of the harmonic patterns (i.e. the more time that elapses after a pattern completes, the less likely it is that the price action is related to that pattern).

//------------------------------------------------------
// Coming soon...
//------------------------------------------------------

I have a handful of other features in development, including:

(1)  Drawing incomplete patterns as they develop. This will allow you more time to plan entries and stops, or potentially trade reversals from point C to point D PRZ levels.
(2)  Support for the Shark and Cypher patterns
(3)  Alerts

Please report any bugs, runtime errors, other issues or enhancement suggestions.

I also welcome any feedback from experienced harmonic pattern traders, especially regarding your strategy for setting targets and stop-losses.

@reees
Notas de prensa:
Various bug fixes:
- reduce probability of bar history reference RT error
- keep track of multiple pending/in progress patterns
Notas de prensa:
Fix for not re-drawing patterns > 400 bars back
Notas de prensa:
BIG UPDATE: Potential patterns will now be drawn after pivot point C is formed, along with projections to the PRZ levels.
Notas de prensa:
Fixed issue with updating label for pending patterns when target or stop is hit before time expires.
Notas de prensa:
Adjusted scoring so that PRZ level confluence and Point D/PRZ confluence are calculated relative to the height of the pattern (rather than the height of the PRZ). This ensures equity across pattern types (PRZ is defined differently for each type of pattern, so it's only a valid measure when comparing patterns of the same type).
Notas de prensa:
Fixed issue with incomplete patterns not getting deleted when no longer valid
Notas de prensa:
- Calculate PRZ confluence and Point D/PRZ confluence relative to the height of the XA leg (this is most equitable across pattern types)
- Project reversal targets from PRZ levels (rather than all from current point D)
- Consolidated addValidPattern()
- Removed unused code
Notas de prensa:
Removed comments
Notas de prensa:
(1) Added alerts
(2) Now including score on potential/incomplete patterns
(3) Now showing % error for each leg retracement in the pattern tooltip
(4) Minor bug fixes
Notas de prensa:
Improved tooltip formatting
Notas de prensa:
Display changes
Notas de prensa:
(1) Now showing target/stop locations for each completed pattern
(2) Bug fixes
Notas de prensa:
(1) Updated to latest version of TA library, which includes a bug fix for the XABCD pattern search algorithm
(2) Added decimal places to the display of stops, targets, and PRZ levels
Notas de prensa:
Increased default leg length asymmetry. May need to consider adjusting asym validation to consider length of XA and CD separately from AB and BC.
Notas de prensa:
Updated to latest version of TA library, which fixes a bug where intermediate lows were not being detected between points C and D.
Notas de prensa:
Color adjustment
Notas de prensa:
BIG UPDATE: Introducing the concept of entries. Choose to enter trades after point C, after point D, or both, based on pattern score and your specified entry level.
- Entries after point C are specified relative to PRZ levels
- Entries after point D are specified as limit orders relative to point D.

The results table now includes statistics for Return %, giving much more valuable feedback regarding your inputs for stop, target, entry levels, and score weights. Play around with the settings and see how it affects your returns!

I've also added a parameter for the number of trailing bars to validate a pattern, and fixed a number of bugs.
Notas de prensa:
bug fix
Notas de prensa:
Bug fixes
Notas de prensa:
(1) Linefilling background between confluent PRZ levels rather than entire PRZ
(2) bug fixes
Notas de prensa:
Added Shark and Cypher patterns.
Notas de prensa:
Updated to newest version of TA script, bug fix for Shark validation
Notas de prensa:
- Added AD-based targets
- Added Point X-based stop loss
Notas de prensa:
Fixed bug with validation of cypher CD leg (now validating against XC rather than XA)
Notas de prensa:
(1) Updating in-progress patterns when entry window has timed out
(2) Removed redundant "==true" comparisons
Notas de prensa:
Updated to latest version of TA library, which includes bug fix for Cypher PRZ level (affects cypher entries after point C)
Notas de prensa:
Fixed spacing on incomplete pattern tooltip
Notas de prensa:
Added .5 AD as a target option
Notas de prensa:
(1) Added parameter for toggling Potential/Incomplete patterns
(2) Bug fix for issue with targets/stops erroneously hit on entry bar
Notas de prensa:
A number of bug fixes including:
(1) better handling of incomplete patterns
(2) more efficient entry and target checks
Notas de prensa:
Fixed "Objects cannot be positioned more than 500 bars in the future" runtime error
Notas de prensa:
Disabling display of Potential/Incomplete patterns by default until issues are resolved. This will not affect trades/backtest results.
Notas de prensa:
Fixed bug with invalid incomplete patterns being added
Notas de prensa:
Bug fixes for drawing/updating incomplete/potential patterns
Notas de prensa:
(1) Removed Leg Length Asymmetry component of pattern score (my research shows no correlation with pattern success). The asymmetry parameter is still available for pattern validation/filtering.
(2) Fixed issue with incomplete pattern scores when PRZ level values are <0
(3) Fixed issue with incomplete pattern projection arrows. No longer showing the arrow when if it points to an entry/PRZ level at or below 0.
Notas de prensa:
Major improvements to incomplete/potential patterns:
(1) fixed bug where potential patterns were being missed when there were multiple pattern types with the same ABC coordinates. This was preventing the patterns from being drawn, and also preventing "After point C" entries to be made.
(2) now drawing incomplete pattern labels on projected point D/entry/PRZ level to reduce label overlapping:
Notas de prensa:
Updated to use latest version of Fib library (improved efficiency for precise fibs)
Notas de prensa:
Firing alert only on bar close until issue with real-time bar alert spamming is resolved
Notas de prensa:
Added parameter to only include patterns that meet your "If score is above" entry requirement
Notas de prensa:
Force inclusion of completed patterns added when entry is hit after point C, regardless of score or "Only high scoring" param
Notas de prensa:
Added parameter to set number of bars to look back. Improves performance somewhat, but I'm unable to implement this the way I'd like to, so there's still a lot of room for improvement.
Notas de prensa:
Major rewrite to use xabcd_harmonic UDT object. Runtime performance has improved, but minimally (extremely disappointing). Compile time improved drastically (down to 20 seconds from ~2 minutes).
Rewrite also includes a plethora of bug fixes and minor enhancements, including:
- more details on the pattern label tooltip (now showing Entry, Stop, T1 & T2 levels so they're always available for reference, regardless of whether they're currently drawn on the chart).
- a dashed line from point C to point D when point D is unconfirmed (i.e. pattern was created from an entry on a Potential/incomplete pattern after Point C, not from a valid pivot).
Notas de prensa:
- Updated to use point objects (with latest version of xabcd_harmonic object)
- various bug fixes
Notas de prensa:
Big Update:
- Major reduction in calculation time
- Improvements to pattern finding algorithm. Now identifies and displays incomplete patterns sooner (1 bar after C) and finds more patterns.
- "Enter after point C" is turned off by default because average return rate is better without it
- Projection arrow from entry level rather than arrows from all PRZ levels
- Bug fixes
Notas de prensa:
Bug fixes
Notas de prensa:
Added "None" option to disable Target 2

Script de código abierto

Siguiendo el verdadero espíritu de TradingView, el autor de este script lo ha publicado en código abierto, para que los traders puedan entenderlo y verificarlo. ¡Un hurra por el autor! Puede utilizarlo de forma gratuita, aunque si vuelve a utilizar este código en una publicación, debe cumplir con lo establecido en las Normas internas. Puede añadir este script a sus favoritos y usarlo en un gráfico.

Exención de responsabilidad

La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.

¿Quiere utilizar este script en un gráfico?