Get Updates:
Email
Twitter
RSS

In part one I discussed the use of the ZigZag function as the engine behind ThinkScripter AutoFibLines.* In part two, the methodology for saving the resulting swing highs and lows using the rec variable was added. At this point, every bar now “knows” the most recent swing high and low and can do the simple math required to calculate Fibonacci ratios:
def deltaHL = prevHigh - prevLow;
def ret1 = deltaHL * fib1;
def ret2 = deltaHL * fib2;
...

First we find the difference between the swing high and low and then calculate the various user-defined fib levels between them or extended beyond for ratios greater than one or less than zero.

Now the tricky part…There is only so much stuff you can put on a chart and have it be useful. I prefer a minimalist approach to studies and my charts and so I chose to plot the Fibonacci ratios in the “white space” to the right of the last bar. (If you don’t have any expansion bars to the right on your chart it is a simple change in the TOS styles panel).

First, before we plot anything, we need to know if we are on a reversal up or down:
rec direction = if(isLow, 1, if(isHigh, -1, direction[1]));
Here I’ve used rec again to remember if the last swing was a low or a high. We can use this so that the plotted fib lines are oriented in the proper direction.

With all our ducks in a row we can now plot a Fibonacci ratio line:
1) def f1c = if(direction > 0 , prevLow + ret1, prevHigh - ret1);
2) rec f1e = if(!isNan(close[-1]), f1c, f1e[1]);
3) plot f1 = if isNan(close[-1]) then f1e else double.nan;

Translation:
1) fib line #1 calculated = either the previous low + the ratio*(high-low) or the previous high – the ratio*(high-low)
2) fib line #1 extension = if the next bar is not empty (i.e. in the future or right expansion space) then the calculated fib line #1 otherwise carry forward the last value of fib line#1 extension
3) plot fib line #1 only if the next bar is empty (i.e. all bars forward without data – the right extension)

Phew! Sometimes I think it is much easier writing/debugging code than explaining it in a somewhat comprehensible manner. That’s all for now. I hope you learned a few of the nuanced techniques that can make thinkScript do out of the ordinary stuff. Until next time, thank you all for your support and good luck in your trading.

*The AutoFibLines code is available in the forum if you’d like it.

Leave a Reply