Bill Williams Fractal Indicator for ThinkorSwim

ykd2018x

Member
2019 Donor
VIP
I hope everybody know what fractals are and importance of fractals in trading. This version of study I use and like the most, with
RSI technique of trading which I use so far and using till the date for my personal trading.

jwFYdzG.jpg


happy trading
yogesh

Code:
# Bill Williams fractal indicator
# written by Mike Lapping
#
# Make sure that you change the settings for this indicator so that it plots arrows
# up for upfractal plots
# down for downfractal plots
#
# can be used and modified by anyone for any reason. do not sell.

def isupfractal;
def isdownfractal;

# Looking for high and low series of equalities
# checking for possible fractal formation

rec hicount = if (high == high[1], hicount[1] + 1, 0);
# if the last bar high is the same as this bar's high, increment
# otherwise set false(0)

rec hivalid = if ((hicount[1] == 0 and hicount == 1 and high > high[2] and high > high[3]) or (hicount[1] and hicount and hivalid[1] )
or (hicount[2] and hivalid[2] and high == high[2] and high > high[1]), 1, 0) ;
# set hivalid to true(1)
# if we are entering an equality series, check if the 2 bars preceding the first equal bar # are lower than the current bar
# or if the last bar was an equal bar and this bar is an equal bar and the current equal
# series is valid
# or if we skipped over a lower bar but two bars ago we had an equal bar and that was a
# valid fractal
# otherwise it is false

rec locount = if (low == low[1], locount[1] + 1, 0);
rec lovalid = if ((locount[1] == 0 and locount == 1 and low < low[2] and low < low[3])
or (locount[1] and locount and lovalid[1] )
or (locount[2] and lovalid[2] and low == low[2] and low < low[1]), 1, 0) ;



# Checking for a traditional or non-standard up fractal

isupfractal = if(((hicount and hivalid) or (high > high[1] and high > high[2])) and high > high[-1] and high > high[-2], high, 0);
# Ok this is complicated, basically its checking if there were a series of equal bars and
# if the two bars before the first equal bar were lower
# or if the last 2 bars were lower than the current bar
# and if the two following 2 bars are lower than the current bar

# Checking for a traditional or non-standard down fractal

isdownfractal = if(((locount and lovalid) or (low < low[1] and low < low[2])) and low < low[-1] and low < low[-2], low, 0);

plot upfractal = if( isupfractal, isupfractal + (1 * tickSize()), double.nan);
upfractal.SetPaintingStrategy(paintingStrategy.POINTS);

plot downfractal = if( isdownfractal, isdownfractal - (1 * tickSize()), double.nan);
downfractal.SetPaintingStrategy(paintingStrategy.POINTS);

# This business with the tickSize() function is basically putting the arrow further away fro
# from the bar so that the fractal is easier to read
 
Last edited by a moderator:

Gildes

New member
VIP
Hi, I am trying to get an alert on my watchlist when a fractal has formed using this script, I know I might get a delay on the alert.
all ideas are welcome.

Thank you

Code:
# Bill Williams Fractal Template
# Coded By: Rigel May 2018

#Define "n" as the number of periods and keep a minimum value of 2 for error handling.
input n=2;

# Williams Fractals are a 5 point lagging indicator that will draw 2 candles behind.
# The purpose of the indicator is to plot points of trend reversals.
# Often these are paired with trailing stop indicators such as Parabolic SAR, Volatility Stop, and SuperTrend.

# Down pointing fractals occur over candles when:
#   High(n-2) < High(n)
#   High(n-1) < High(n)
#   High(n + 1) < High(n)
#   High(n + 2) < High(n)
#dnFractal = (high[n-2] < high[n]) and (high[n-1] < high[n]) and (high[n+1] < high[n]) and (high[n+2] < high[n])

def isupfractal = if low < low[1] and low < low[2] and low < low[-1] and low < low[-2] then low else double.nan;
# Up pointing fractals occur under candles when:
#   Low(n-2) > Low(n)
#   Low(n-1) > Low(n)
#   Low(n + 1) > Low(n)
#   Low(n + 2) > Low(n)
#upFractal = (low[n-2] > low[n]) and (low[n-1] > low[n]) and (low[n+1] > low[n]) and (low[n+2] > low[n])
def isdownfractal = if high > high[1] and high > high[2] and high > high[-1] and high > high[-2] then high else double.nan;
# Plot the fractals as shapes on the chart.


plot upfractal = if( isupfractal, isupfractal+ (1 * tickSize()) , double.nan);
upfractal.SetPaintingStrategy(paintingStrategy.ARROW_UP);
plot downfractal = if( isdownfractal, isdownfractal - (1 * tickSize()), double.nan);
downfractal.SetPaintingStrategy(paintingStrategy.ARROW_DOWN);
 
Last edited by a moderator:

Nick

Active member
2019 Donor
VIP
Thanks Yogesh

I am wondering, can anyone out there write me a scan, to tell me which stock has closed above or below its most recent fractal, based on the code kindly provided by Yogesh?

Thanks again.
 

ykd2018x

Member
2019 Donor
VIP
I don't think there should be any such system or way to make such scan

so far fractals are good for below things on charts
1. creating actual and good trendlines those works
2. to see the market trend and movement
3. to understand where the buyers and sellers can be meeting together
4. to see the nature going on , on the charts and how swing highs and swing lows are so easily visible in up and down trend ,

Code:
# RSI with Williams Fractal Pivots
########START  Code
# Chat Room 04.20.2018

declare lower;

input length = 14;
input over_Bought = 70;
input over_Sold = 30;
input price = close;
input averageType = AverageType.WILDERS;
input New_HI_LO = 30;


def NetChgAvg = MovingAverage(averageType, price - price[1], length);
def TotChgAvg = MovingAverage(averageType, AbsValue(price - price[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;

plot RSI = 50 * (ChgRatio + 1);
plot OverSold = over_Sold;
plot OverBought = over_Bought;

RSI.DefineColor("OverBought", GetColor(5));
RSI.DefineColor("Normal", GetColor(7));
RSI.DefineColor("OverSold", GetColor(1));
RSI.AssignValueColor(if RSI > over_Bought then RSI.color("OverBought") else if RSI < over_Sold then RSI.color("OverSold") else RSI.color("Normal"));
OverSold.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(8));

plot NEWHIGH = if RSI == highest(RSI, new_HI_LO) then RSI else Double.NAN;
NEWHIGH.setpaintingStrategy(paintingStrategy.POINTS);
NEWHIGH.setdefaultColor(color.light_green);
NewHIGH.setlineWeight(1);

plot NEWLOW = if RSI == lowest(RSI, new_HI_LO) then RSI else Double.NAN;
NEWLOW.setpaintingStrategy(paintingStrategy.POINTS);
NEWLOW.setdefaultColor(color.light_RED);
NEWLOW.setlineWeight(1);

# Fractals
# 1/5/17 Amalia added Aggregation periods?

def H = RSI;
def L = RSI;

input sequenceCount = 2;

def maxSideLength = sequenceCount+1;
def upRightSide = fold i1 = 1 to maxSideLength
                  with count1
                  while count1 != sequenceCount and
                        count1 != -1
                  do if GetValue(H, -i1) > H or
                       (GetValue(H, -i1) == H and
                        count1 == 0)
                     then -1
                     else if GetValue(H, -i1) < H
                          then count1 + 1
                          else count1;
def upLeftSide = fold i2 = 1 to maxSideLength
                 with count2
                 while count2 != sequenceCount and
                       count2 != -1
                 do if GetValue(H, i2) > H or
                      (GetValue(H, i2) == H and
                       count2 >= 1)
                    then -1
                    else if GetValue(H, i2) < H
                         then count2 + 1
                         else count2;
def downRightSide = fold i3 = 1 to maxSideLength
                    with count3
                    while count3 != sequenceCount and
                          count3 != -1
                    do if GetValue(L, -i3) < L or
                         (GetValue(L, -i3) == L and
                          count3 == 0)
                          then -1
                        else if GetValue(H, -i3) > L
                             then count3 + 1
                             else count3;
def downLeftSide = fold i4 = 1 to maxSideLength
                   with count4
                   while count4 != sequenceCount and
                         count4 != -1
                   do if GetValue(L, i4) < L or
                        (GetValue(L, i4) == L and
                         count4 >= 1)
                      then -1
                      else if GetValue(L, i4) > L
                      then count4 + 1
                      else count4;

plot UpFractal = if upRightSide == sequenceCount and
                    upLeftSide == sequenceCount and
                    RSI > OverBought
                 then RSI
                 else Double.NaN;
plot DownFractal = if downRightSide == sequenceCount and
                      downLeftSide == sequenceCount and
                      RSI < oversold
                   then RSI
                   else Double.NaN;

UpFractal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
UpFractal.SetDefaultColor(color.RED);
UpFractal.SetLineWeight(2);
DownFractal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
DownFractal.SetDefaultColor(color.GREEN);
DownFractal.SetLineWeight(2);


def Pre_hi = if !isnan(upfractal) then upfractal else pre_hi[1];

plot high_line = pre_hi;
high_line.setpaintingStrategy(paintingStrategy.DASHES);
high_line.setdefaultColor(color.CYAN);

def Pre_lo = if !isnan(downFractal) then downFractal else pre_lo[1];

plot lo_line = pre_lo;
lo_line.setpaintingStrategy(paintingStrategy.DASHES);
lo_line.setdefaultColor(color.MAGENTA);

addlabel(yes, brilliant
if RSI >= OverBought && RSI >= RSI[1]
    then "RSI OB & Rising: " +round(RSI, 2)
else if RSI >= OverBought && RSI < RSI[1]
    then "RSI OB & Falling: " +round(RSI, 2)
else if RSI <= OverSold && RSI < RSI[1]
    then "RSI OS & Falling: " +round(RSI, 2)
else if RSI <= OverSold && RSI >= RSI[1]
    then "RSI OS & Rising: " +round(RSI, 2)
else if RSI < OverBought && RSI > OverSold && RSI >= RSI[1]
    then "RSI Rising: " +round(RSI, 2)
else if RSI < OverBought && RSI > OverSold && RSI < RSI[1]
    then "RSI Falling: " +round(RSI, 2)
else "",
if RSI >= OverBought && RSI >= RSI[1]
    then color.dark_orange
else if RSI >= OverBought && RSI < RSI[1]
    then color.yellow
else if RSI <= OverSold && RSI < RSI[1]
    then createcolor(000, 100, 100)
else if RSI <= OverSold && RSI >= RSI[1]
    then color.cyan
else if RSI < OverBought && RSI > OverSold && RSI >= RSI[1]
    then color.green
else if RSI < OverBought && RSI > OverSold && RSI < RSI[1]
    then color.red
else color.gray);


plot Buffer = if RSI <= OverSold then RSI - 10 else if RSI >= OverBought then RSI + 10 else double.nan;
Buffer.setdefaultColor(color.black);
Buffer.hidetitle();
Buffer.hidebubble();

####END Code
 

Bentley

New member
Hi @ykd2018x There's an error in the code as in the "addlabel" section, there's an unwanted text "brilliant". Post above is the working code. I've try to do a scan but failed. It seem that the Fractal is not a boolean condition. It give a value. So I change it to

Code:
plot UpFractal = upRightSide == sequenceCount and
                    upLeftSide == sequenceCount and
                    RSI > OverBought;
              

and also
plot UpFractal = if upRightSide == sequenceCount and
                    upLeftSide == sequenceCount and
                    RSI > OverBought
                 then 1
                 else 0;

Both doesn't work.

Seem like it's impossible to turn a value into a Boolean condition... or is it? :unsure: 😬
 

selfhigh05

New member
VIP
Here is an interesting strategy using the fractals as a breakout strategy. Basically if the underlying is over 200 EMA then its in an uptrend and you draw a horizontal line from the most recent fractal and when price break above that you go long. Short would be taken when below 200 EMA and when break down through the horizontal line from the most recent bottom fractal. Can anyone point me in the right direction on how to add a horizontal line based on the rules above? I would only want the most recent horizontal line so the chart doesnt get too cluttered up. I can code some but not sure on the logic behind only seeing the most recent line. Thanks!
 

Similar threads

Top