Is there an indicator that would do PeakTroughMode.ATR ?
Author: lb1789
Creation Date: 2/2/2018 1:11 AM
profile picture

lb1789

#1
Good morning,

PeakTroughMode is a powerful indicator (thank You very much for posting it). It returns the peak or trough after a retracement. Currently, there are two types of retracement: in value or in percentage point. Along with PeakTroughMode come peakbar and troughbar that return the bars on which swings occurred.

Value works well for single markets. Percentage points do not incorporate volatility. Volatility is a more respectful measure than a blanket pct point. Big boring defensive stocks do not have the same volatility signature as bitcoin for example.

Is there already an indicator that would return peaktrough based on ATR or STDEV? I there an indicator that would return the peakbar and troughbar based on this indicator as well?

Thank You
profile picture

Eugene

#2
Hi Laurent,

UPDATE 02/10/2018: There is:

* SVEHLZZperc indicator
* ATR ZigZag framework: TASC 2013-07 | The Step Candle Pattern (Vervoort)


Unfortunately there isn't although I recall some forum discussions in the past. While not exactly what you're looking for, if your system buys when the price has moved N ATRs up from the recent "trough" (and vice versa for the short side) would a trailing reverse technique like NRTR_WATR work?
profile picture

lb1789

#3
Hello Eugene,

Thank You very much for your answer. Always food for thought.

Objective:
The objective is to build a PeakBar in ATR instead of percent.
In the chart attached below, there an indicator that divides the closing price by an ATR 20 days. The idea is to convert ATR in percentage points. An ATR based retracement is better suited at capturing subtle moves in low volatility periods (Typically around swings) and would find earlier entry/exit points than a cookie cutter percentage point retracement.
The (int) PeakBar.Value( bar, High, atr_pct, PeakTroughMode.Percent ) is accurate and robust but it uses Percent and not ATR. The objective is to build an ATR function.

In the (clunky) code attached, i declared a double and converted ATR in percentage by dividing ATR/Close. It compiles and works.

Problem
As shown in the chart, the Boolean that would switch on/off when a new peak is found does not work. This gets repeated over and over. Is there a simple elegant way to fix the problem?

In comparison, the trough conventional series works well. It identifies a unique condition. It cannot be easily substituted however as they would find the same peak on different bars.



Strategy Code

CODE:
Please log in to see this code.



Attached picture of the code

profile picture

Eugene

#4
Hi Laurent (and Alex aka Swissi by virtue of leaving similar request in another thread),

Nice attempt. It occurred to me that I had already implemented the ATR ZigZag in 2013 when writing the code for a series of Sylvain Vervoort's articles in S&C magazine. It's driven by his SVEHLZZperc indicator which needs to be switched to SVEHLZZperc_Type.ATR mode. It can also do Percent and Combined Percent+ATR but I don't remember what the combined mode is about.

Here's my ZigZag framework:

TASC 2013-07 | The Step Candle Pattern (Vervoort)

It defaults to Percent mode so you have to do two minor tweaks:

1. (Optional) Introduce StrategyParameters to control the number of ATRs and the ATR period via parameter sliders
2. The key change to do is this:
QUOTE:
DataSeries zz = SVEHLZZperc.Series(bars,percent,14,number_of_ATRs,SVEHLZZperc_Type.ATR);

See the indicator documentation (link above).

Retain the classes that build the framework. Optionally, you can safely delete some extra code:

1. Code inside this loop which concerns detection of the Upstep, Downstep and Harami patterns:
CODE:
Please log in to see this code.


2. This method marked [Obsolete]:
CODE:
Please log in to see this code.


That's all it takes.
profile picture

superticker

#5
QUOTE:
In the ... code attached, I declared a double and converted ATR into percentage by dividing ATR/Close.
You lost me there. Let's keep this straightforward. Simply compute: priceInTermsOfATR = Close/ATR and them pass that division into your peak detection routine to get peak detection in terms of ATR using the PeakTroughMode.Value mode.
CODE:
Please log in to see this code.

From the discussion that follows, I'm gathering you're trying to do something more complex than simply flagging peaks by ATR changes alone.

Editorial note: Personally, I don't like using ATR for gauging volatility, but it's the best robust volatility metric Wealth-Lab has to offer. One can't rely on a normal standard deviation metric because outliers will throw it completely off. In modern statistics, we do have something called "robust" standard deviation, which is what we should really be using in noisy environments (like stock trading), but it's harder to compute. And WL doesn't have an indicator for that. :(
profile picture

lb1789

#6
Thank You very much Eugene and SuperTicker for your answers

Eugene, the SVEHLZZperc.Series is not exactly what i am looking for. Whilst i appreciate the beauty of TASC 2013-07 | The Step Candle Pattern (Vervoort), this is probably a bit too advanced for what i am trying to accomplish. I will try with the NRTR_WATR indicator. It seems to be doing the job.

SuperTicker, thank you very much for the elegant simplicity of your solution. My coding is a bit rusty and this is the kind of inspiration i need to get back into the coding grove. I agree with You: ATR is probably not the best measure of volatility, but it is simple enough for simple things. And You are right, I am trying to do something a little more advanced:

The Floor/Ceiling method using ATRs
https://www.quora.com/What-is-the-most-precise-way-to-draw-support-and-resistance-lines-for-forex-trading/answer/Laurent-Bernut
Regime definition is one of the most vexing topic for traders. The Floor/Ceiling method is a simple robust way to define regime. A bull ends when ceiling collapses. A bear ends when floor rises. This eliminates restrictive conditions such as higher highs for bull and lower lows for bears.

Logic
1) Swing calculation: conditions are symmetrical for swing highs and lows.
a) Swing high: retracement in n. ATRs from peak. peak = highest high since last swing low.
b) if trough is found then highest peak since last swing low highest peak = swing high
Sometimes market runs up without clocking a low, so peaks are reset higher until a trough is found on the other side,
2) Ceiling detection:
a) if (swing high >= top && swing high bar > floorBar) then swing high = top
else if (top - swing high) / ATR[20] > detection threshold then
top = ceiling; topBar = ceilingBar
The idea is to reset swing high to its highest level and then measure all subsequent swing highs against the top until there is enough distance to conclude that the market has hit a ceiling. detection threshold is express is retracement ATRs. For example, if retracement = 2 ATRs, then detection threshold could be = 2 * retracements = 2 * 2 = 4 ATRs
This turns everything into a multiple of retracements and makes optimisation a lot easier

Once a ceiling is found, market either goes sideways or bearish. Basic hypothesis is market goes sideways until there is evidence a trend is under way.

3) Range definition
Lower bound: is the lower range = trough since ceilingbar; lowerrangebar = troughbar;
Upper bound: there are two methods here. first one is easier to calculate
a) Upper bound is the highest point after a low range. upper bound = peak since troughBar; upper bound bar = peak bar since troughbar
b) Record the highest swing high after the top : if(swing high< top && swing high >= swing high[n-1] Then upper bound = swing high upper bound bar = swing high bar
Both methods are valid. The first one assumes that markets first rebound off a low and then bounces back from a peak. Ranges dynamically follow the evolution of the counter-trend. Second method assumes all swing highs between the ceiling and now are fair game. this gives a wider band. In practice, there is not much difference, except in shorter time frames.

4) Trend resumption:
a) There are many ways to identify trend resumption but let's go with one that traders are most familiar with: breakout/breakdown.
If Close > upper bound then bullish = true;
If Close < lower bound then bearish = true;
b) After a ceiling is detected, the lowest bound of the range serves as an anchor for floor detection. This illustrates the principle that bull markets do not just die, and then "voila" bear markets start. Bear markets begin as bulls die and vice versa. The practical application is that a floor can be found within a sideways range if distance to the lowest bound is big enough

Why ATRs instead of percentage retracement?
I have carbonara spaghetti coded this floor ceiling using peakbar and peak series in percent retracement mode (that code will give instantaneous eye cancer and brain tumors to any seasoned programmer). The problem is percent retracement ignores volatility. For some sleepy securities, regime is vastly lagging. For choppy stuff, regime flip-flops like a career congressman. Now that the volatility genie is out of the box, it might be useful to incorporate it in the strategy so that it does not resurface in the portfolio later on.

Difference with 1-2-3 method
This floor ceiling method resembles the 1-2-3 pattern but with a few differences. First, everything is done in volatility units. It is more respectful of the volatility signatures of different instruments. Secondly, swings do not have to be consecutive. The top is compared with every subsequent swing high until it either finds one low enough to warrant a ceiling or makes a fresh top. There is no ambiguity possible. It incorporates sideways markets in the form of ranges. (For full disclosure, I am a big fan of 1-2-3 that i discovered through WLD)

Strategy(ies)
This Floor/Ceiling method gives traders objective starting/ending points to deploy their strategies. For example, ceiling is detected: switch on mean reversion and turn off trend following and vice versa when trend resumes. There are of course endless variations on this theme, scaling-in/out, relative/absolute, multi-time frames etc, but for now, let's take a simple strategy that is still an enduring rendition:
A. Initial entry: Look for an entry on ceiling or floor detection
1) Ceiling detection: a) swing high detected && (top - swing high)/ATR[20] > detection threshold b) no active position
Sell short at bar +1
riskstoplevel = ceiling
2) Floor detection: b) swing low detected && (swing Low - bottom)/ATR[20] > detection threshold b) no active position
Buy Long at bar +1
riskstop level = floor
B. Reversal: close active positions and reverse side
1) Floor detection b) swing low detected && (swing Low - bottom)/ATR[20] > detection threshold b) active Short position
Buy to Cover at bar +1
Buy Long at bar +1
riskstoplevel = floor
2) Ceiling detection: a) swing high detected && (top - swing high)/ATR[20] > detection threshold b) active Long position
Sell Long at bar +1
Sell Short at bar +1
riskstoplevel = ceiling

This strategy assumes only two broad regimes: bull and bear. It goes long when a floor is detected assuming sideways to bull and short when a ceiling is found, sideways to bear. Since range is by definition contained below the ceiling and above the floor, setting the stop loss at either floor or ceiling enables traders to navigate through the sideways gyrations relatively unharmed.
It does not make explicit use of the ranges. A variation would be to cover a short and go long if Close > upper band (and vice versa on the short side) with stop loss somewhere along the range: aggressive = upper bound, prudent = mid-range, conservative = lower bound. Please feel to elaborate more sophisticated strategies. My objective is simply to provide traders with a solid skeleton to put muscle on.

Conclusion: simplicity, robustness and versatility
The Floor/Ceiling method is a simple answer to the complicated question of regime definition: bull, bear, sideways. Complexity is a form of laziness: no Ministry of Magic Fibonacci, no Christmas garland moving averages. As such, this method works across asset classes, time frames, relative to an index or in absolute, even multi-time frames (see the Quora post above). It is a powerful asset allocation tool as well. Trend following strategies work best in trending regimes and vice versa for mean reversion strategies in sideways markets. I would be immensely grateful if someone helped code the Floor/Ceiling method. As You start to play with this idea, You will probably realize that it can be noisy at times. As an expression of humble gratitude, i would offer a powerful gift to whomever would comes up with a simple elegant code.

Once again, thank You very much Eugene, SuperTicker and Swissi