Bill Williams Fractal Indicator for ThinkorSwim

ykd2018x

Member
2019 Donor
Bill Williams Fractal Indicator for ThinkorSwim

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:

8Nick8

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

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
@novadolla
The author stated there was no scan and my attempts also failed :(
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 ,
As @diazlaz stated there is the built-in BW:
Hi @Nick

BW is built into the ToS Platform - no need for a custom indicator or scan.

Patterns, See below:

1JIWrJA.png
However I could only get the built-in ToS indicator to work if set to within 3 bars:
cjt7Wpr.png
 
Last edited:

greco26

Active member
I'm currently using Bill Williams Fractal Indicator with sequence count of 4 on a 1 min chart. I was wondering if there is a scan that could be utilized to scan for the Fractal when it appears on the chart. I would like to incorporate that into a Dynamic Watchlist so that i don't have to tab through multiple charts to get the Fractal. Any help would be appreciated. Thanks
I looked into this same idea about 2 weeks ago. I was able to scan for fractals using the code. The thing to remember is that it’s delayed by the offset. What I do is add the study to the scan and set the condition as fractal down is true 2 bars ago (of your offset is 2). That works for me.
 

mrp2021

New member
Bill Williams Fractal Indicator for ThinkorSwim

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
Hi Yogesh,
what script do you use for the reversal bubble shown on the chart?
 

solaris

Member
I looked into this same idea about 2 weeks ago. I was able to scan for fractals using the code. The thing to remember is that it’s delayed by the offset. What I do is add the study to the scan and set the condition as fractal down is true 2 bars ago (of your offset is 2). That works for me.
Thanks i was able to get the scan to work by following your suggestions. I'm using the code in a watchlist so i can monitor a group of stocks all at once, however i'm having issues trying to assign a background color based on the upfractal and downfractal. Any suggestions on how to write that piece of code. here's what i'm using in the watchlist so far. It generates a signal which will work, it just makes it easier on the eyes to see a background color.

BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago
 

greco26

Active member
Thanks i was able to get the scan to work by following your suggestions. I'm using the code in a watchlist so i can monitor a group of stocks all at once, however i'm having issues trying to assign a background color based on the upfractal and downfractal. Any suggestions on how to write that piece of code. here's what i'm using in the watchlist so far. It generates a signal which will work, it just makes it easier on the eyes to see a background color.

BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago
can you post your WL code and I will take a look at it?
 

solaris

Member
can you post your WL code and I will take a look at it?
This is what I'm using in the watchlist (BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago) it generates numercial values which plots the fractal from 2 bars ago on the chart. This is the code im using on the chart. Any help you can provide on the background color for the watchlist would be greatly appreciated. Thanks


# 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
 

greco26

Active member
This is what I'm using in the watchlist (BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago) it generates numercial values which plots the fractal from 2 bars ago on the chart. This is the code im using on the chart. Any help you can provide on the background color for the watchlist would be greatly appreciated. Thanks
Im confused on what you are looking for. You said you wanted the Watchlist background to change color but you mention numerical values being plotted on the chart. The code you posted is for the chart study and won't work in a watchlist column me for. Do you want the background to change on the chart or the WL column? If WL column, do you have working code for the WL?
 

solaris

Member
My apologies for the confusion the numerical value is being plotted in the watchlist, I want the background color to change in the watchlist column.
This is the code that is being used in the watchlist (BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago) I just want want the background to change to green when the condition is met. The other code as you mentioned is for the Chart.
 

greco26

Active member
BillWilliamsFractalRevised1212021()."upfractal" from 2 bars ago
Hmm...This line looks to be a custom study so not sure how you are able to load it into a watchlist column. Let me know how you were able to do this as its not something I know how to do. Screenshots would be great too.
 

greco26

Active member
Never mind. I figured out how you did it. The code below will color the words red or green. For some reason, the background color isn't working for this but not sure why. Try it on your side though as I left the code in there but commented it out. Hope this helps.

Code:
def cond1 = if WilliamsFractal()."UpFractal" from 2 bars ago is true then 1 else 0;
def cond2 = if WilliamsFractal()."DownFractal" from 2 bars ago is true then 1 else 0;

addlabel(yes, if cond1 then "UP " else if cond2 then "Down " else " ", if cond1 then color.green else if cond2 then color.red else color.black);

#assignbackgroundColor(if cond1 then color.green  else if cond2 then color.red else  color.black );
 

danjoh

Member
VIP
I looked into this same idea about 2 weeks ago. I was able to scan for fractals using the code. The thing to remember is that it’s delayed by the offset. What I do is add the study to the scan and set the condition as fractal down is true 2 bars ago (of your offset is 2). That works for me.
Probably a dumb question, I have a hard time breaking out of my literal thinking. I'm reading the Williams book Trading Choas (New Version). It say never use below 3 bars and use odd numbers. Curious how this is working for you all and what I might be missing that makes you comfortable to go down to 2. I am using 5 and 7.
 

greco26

Active member
Probably a dumb question, I have a hard time breaking out of my literal thinking. I'm reading the Williams book Trading Choas (New Version). It say never use below 3 bars and use odd numbers. Curious how this is working for you all and what I might be missing that makes you comfortable to go down to 2. I am using 5 and 7.
Well first off, if you're reading a book you're already smarter than me so its not a dumb question! :) I trade a system called TheStrat developed by Rob Smith. I use the indicator only to show me where broadening formations are occurring to gauge where price is in relation to one side of the triangle. What I'm actually doing is looking for price to take out a major fractal then I look for a reversal signal like a hammer or inside bar. In the screenshot below is an example of what I mean. One of 3 main universal truths of The Strat is that price always travels in a series of broadening formations (despite popular believe that broadening formations are very rare). We look for price to take out one side of the fractal then look for reversal signals to attempt to out the other side. Hope this makes sense.

 

danjoh

Member
VIP
Well first off, if you're reading a book you're already smarter than me so its not a dumb question! :) I trade a system called TheStrat developed by Rob Smith. I use the indicator only to show me where broadening formations are occurring to gauge where price is in relation to one side of the triangle. What I'm actually doing is looking for price to take out a major fractal then I look for a reversal signal like a hammer or inside bar. In the screenshot below is an example of what I mean. One of 3 main universal truths of The Strat is that price always travels in a series of broadening formations (despite popular believe that broadening formations are very rare). We look for price to take out one side of the fractal then look for reversal signals to attempt to out the other side. Hope this makes sense.

Thank you so much. Yes it makes sense. I see you do not use the Williams Allegator with the Fractals. I like your wedge theory, Do you think the allegator accomplishes something simular to your trangle? Dan 👍
 

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Top