Repaints Cup and Handle Indicator for ThinkorSwim

Repaints

bulusufinances

New member
VIP
The cup and handle pattern is a bullish continuation pattern used in technical analysis to identify potential buying opportunities in the market. It typically forms after a prolonged uptrend
KPo0QC0.jpeg

@halcyonguy created the cup pattern based on https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
see his script in the next post
 
Last edited by a moderator:
UII88V6.jpg


Code:
#cup_n_handle_03g


# test with EBAY  day chart


#https://usethinkscript.com/threads/attempt-at-cup-and-handle-pattern.17536/#post-135874
#Attempt at Cup and Handle Pattern
#bulusufinances  12/24


# from current bar, look back for a cup-handle

# copy and rewrite rules from this site
# https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
# replace days , with bars

# r01  Current Close ,  close >= 6 and close >= ( 0.95 of ma200)

# r02  Pivot  , Highest high , end of cup, beginning of the Handle.  within last 90 bars

# r03  Pivot price % of Left Cup ,  Difference between the Left Cup and the Pivot, expressed as a percentage of the Left Cup.   %  <= +5% and % >= -40%

# r04  Left Cup , Highest high , beginning of the correction.    >= 25 days and <=325 bars from the pivot

# r05  Cup length to Handle length Ratio , cup bars >= ( 3 x handle bars)

# r06 , Prior Low  , lowest low before the cup left,   price Rise from Prior Low to Left Cup >=30%
# r06b  Setup Gain %    The rise from the prior low to the left cup measured as a percentage of the prior low , >= 30%

# r07  Base Low    Lowest low within the Cup.

# r08  Cup Depth   price Difference between the Left Cup and Base Low, expressed as a percentage of the Left Cup.   <=60%

# r09  Handle Depth    Difference between the Pivot and the Handle Low, expressed as a percentage of the Pivot.    <= 30%

# r10  Midpoint of Base    Price which marks half the distance between the Left Cup and the Base Low.    None

# r11  Midpoint of Handle    Price which marks half the distance between the Pivot and the Handle Low.    >= Midpoint of Base

#The stock must also meet these technical criteria to improve the chances of a successful breakout:     
# r1b  Current Close    The price at which the stock closed today.    >= $6

# r12  Average Volume    The average daily volume over the last 50 days    >=30,000

# r13  Relative Strength (RS)Rank    The stock’s weighted price appreciation over the prior year, as ranked against all other stocks in our database.    >=80




#---------------



#-----------------------
# copy the rules and add code


def na = double.nan;
def bn = barnumber();
def cls = close;
#def lastbar = (!isnan(close) and isnan(close[-1]));
def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
#def lastbar = if l
def big = 99999;


# choose_wick_body01
input candle_levels = {default "wick" , "body" };
def highx;
def lowx;
switch (candle_levels) {
case "wick":
  highx = high;
  lowx = low;
case "body":
  highx = max(open, close);
  lowx = min(open, close);
}


#--------------------------
#https://usethinkscript.com/threads/zigzag-high-low-with-supply-demand-zones-for-thinkorswim.172/#post-7048
#post10  robert
#  +------------------------------------------------------------+
#  |  Example: How to extend levels to the right of the chart   |
#  |                        Robert Payne                        |
#  |               https://funwiththinkscript.com               |
#  +------------------------------------------------------------+
# define peaks / valleys
#def na = double.nan;
#def bn = BarNumber();
input peak_length = 10;
#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def offset = Min(peak_length - 1, lastBar - bn);
def peak = highx > Highest(highx[1], peak_length - 1) and highx == GetValue(Highest(highx, peak_length), -offset);
def valley = lowx < Lowest(lowx[1], peak_length - 1) and lowx == GetValue(Lowest(lowx, peak_length), -offset);

input peak_valley_arrows = yes;
plot zhi = if peak_valley_arrows and peak then high*1.001 else na;
plot zlo = if peak_valley_arrows and valley then low*0.999 else na;
zlo.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zlo.SetDefaultColor(Color.red);
zlo.setlineweight(1);
zlo.hidebubble();
zhi.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
zhi.SetDefaultColor(Color.green);
zhi.setlineweight(1);
zhi.hidebubble();


#------------------------







#-------------------------------
# rules and code
#  find offsets to signals, then calc barnumbers


# r01  Current Close ,  close >= 6 and close >= ( 0.95 of ma200)
input min_price = 6.0;
input avg1_type = AverageType.Simple;
input avg1_length = 200;
def avg1 = MovingAverage(avg1_type , cls , avg1_length );
input avg_factor = 0.95;
def r01 = (cls >= min_price) and (cls >= (avg_factor * avg1));
input show_average_line = no;
plot zavg1 = if show_average_line then avg1 else na;


# r02  Pivot  , Highest high , end of cup, beginning of the Handle.  within last 90 bars
#   my added rule -  pivot should be higher than current price
# offset to pivot bar , handle_len
def pivot_len = 90;
# pivot_off
def handle_len = fold a1 = 0 to pivot_len
  with p1
  while !getvalue(peak,a1)
  do p1+1;

def pivot_bn = if handle_len == pivot_len then 0 else highestall(if isnan(close) then 0 else (bn - handle_len));
def pivot = getvalue(highx, (bn - pivot_bn));

input test_r2 = no;
addchartbubble(test_r2, low*0.998,
bn + " bn\n" +
handle_len + " pivoff\n" +
pivot_bn + " pivbn\n" +
pivot + " piv"
, color.white, no);


# move down and add conditions to this formula
def cancel = if (pivot_bn == 0 or 0) then 1 else 0;
addlabel(cancel, " cancel , no cup-handle found ", color.cyan);


# r03


# r04  Left Cup , Highest high , beginning of the correction.    >= 25 days and <=325 bars from the pivot

def pivotleftoffmin = 25;
def pivotleftoffmax = 325;
def left_start = (handle_len + pivotleftoffmin);
#def leftlenmax = pivotleftoffmax - left_start;
def leftlenmax = (handle_len + pivotleftoffmax);


# find prev peak , left side of cup
def left_off = fold a2 = handle_len + 1 to (pivotleftoffmax + handle_len)
  with p2 = handle_len+1
  while !getvalue(peak,a2)
  do p2+1;

def left_bn = if left_off == leftlenmax then 0 else highestall(if isnan(close) then 0 else (bn - (handle_len + left_off)));
def left = getvalue(highx, (bn - left_bn));

def cup_bars = pivot_bn - left_bn;


input test_r4 = no;
addchartbubble(test_r4, low*0.99,
bn + " bn\n" +
left_off + " leftoff\n" +
left_bn + " leftbn\n" +
left + " left\n" +
cup_bars + " cup"
, color.white, no);



# r03  Pivot price % of Left Cup ,  Difference between the Left Cup and the Pivot, expressed as a percentage of the Left Cup.   %  <= +5% and % >= -40%

def leftpivpermin = -40;
def leftpivpermax = 5.0;
def leftpivot_per = round(100*(left-pivot)/left,1);
def isleftper = leftpivot_per > leftpivpermin and leftpivot_per < leftpivpermax;


input test_r3 = no;
addchartbubble(test_r3, low*0.99,
 bn + " bn\n" +
 left + " lt\n" +
 pivot + " piv\n" +
 leftpivot_per + " %\n" +
 isleftper + "\n"
, color.white, no);





# r05  Cup length to Handle length Ratio , cup bars >= ( 3 x handle bars)
def ratio_min = 3.0;
def cuphandleratio = cup_bars/handle_len;
def iscupratio = cuphandleratio >= ratio_min;

input test_r5 = no;
addchartbubble(test_r5, low*0.99,
 bn + " bn\n" +
"cup len ratio\n" +
 cuphandleratio + "\n" +
 iscupratio + " is"
, color.white, no);




# r06 , Prior Low  , lowest low before the cup left,   price Rise from Prior Low to Left Cup >=30%
# r06b  Setup Gain %    The rise from the prior low to the left cup measured as a percentage of the prior low , >= 30%




# r07  Base Low    Lowest low within the Cup.
# offset to base low, from pivot
#def base_off = GetMinValueOffset(lowx[handle_len], cup);
def base_min = fold a3 = handle_len to cup_bars + handle_len
with p3 = big
do min(p3,getvalue(lowx,a3));

def base_off = fold a4 = handle_len to cup_bars + handle_len
  with p4
  do if base_min == getvalue(lowx, a4) then a4 else p4;
 

def base_bn = highestall(if isnan(close) then 0 else (bn - (base_off+handle_len)));
def base = getvalue(lowx, (bn - base_bn));



input test_r7 = no;
addchartbubble(test_r7, low*0.99,
 bn + " bn\n" +
base_off + " Basoff\n" +
base_bn + " Bbn"
, color.white, no);



# r08  Cup Depth   price Difference between the Left Cup and Base Low, expressed as a percentage of the Left Cup.   <=60%

# r09  Handle Depth    Difference between the Pivot and the Handle Low, expressed as a percentage of the Pivot.    <= 30%

# r10  Midpoint of Base    Price which marks half the distance between the Left Cup and the Base Low.    None

# r11  Midpoint of Handle    Price which marks half the distance between the Pivot and the Handle Low.    >= Midpoint of Base

#The stock must also meet these technical criteria to improve the chances of a successful breakout:     
# r1b  Current Close    The price at which the stock closed today.    >= $6

# r12  Average Volume    The average daily volume over the last 50 days    >=30,000

# r13  Relative Strength (RS)Rank    The stock’s weighted price appreciation over the prior year, as ranked against all other stocks in our database.    >=80





input test_bn = no;
addchartbubble(test_bn, low*0.99,
 bn + " bn"
, color.white, no);


#def bubs = (pivot_bn == bn or left_bn == bn or base_bn == bn);

input test1_data = yes;
addchartbubble(test1_data and pivot_bn == bn, high*1.01,
# bn + "  BN\n" +
 "PIVOT\n" +
 pivot_bn + " bn\n" +
 pivot
, color.cyan, yes);


addchartbubble(test1_data and left_bn == bn, high*1.01,
# bn + "  BN\n" +
 "LEFT\n" +
 left_bn + "\n" +
 left
, color.cyan, yes);


addchartbubble(test1_data and base_bn == bn, low*0.99,
# bn + "  BN\n" +
 "BASE\n" +
 base_bn + "\n" +
 base
, color.cyan, no);





#///////////////////////////////////////////





#///////////////////////////////////////////

#  circle

# circle_2points_0e

#https://usethinkscript.com/threads/experimental-draw-an-oval-circle-in-thinkorswim.11517/
#draw 2 ovals.

#define 2 points, by entering a date and time for each.
#draw a line connecting those points. this line will be the diameter and will be diagonal.
#calculate a horizontal diameter. (the oval will be wider than the 2 points)
#draw 2 arcs, for the top half and bottom half of the oval.
#this will be the outer oval.
#the center is marked with a yellow square.

#a 2nd smaller oval is drawn.
#it will have a width of the time span between the 2 points.
#the arc lines are not drawn on the date-time bars. (i don't remember why)

#i used different colors on the arcs, to show how they are drawn.

#i set the 2 dates as 5/20 and 5/31.
#set a chart to 30 days. mine is at 15min 30days


# circle_2points_0e

# https://usethinkscript.com/threads/drawing-a-circle-on-the-chart.10485/
# Drawing a Circle on the chart

#-------------------------------------------
#https://www.math.net/circle-formula
#Given that point (x, y) lies on a circle with radius r centered at the origin of the coordinate plane, it forms a right triangle with sides x and y, and hypotenuse r. This allows us to use the Pythagorean Theorem to find that the equation for this circle in standard form is:

#x^2 + y^2 = r^2

# adjusted radz  -  pythagorean
#  r^2 = x^2 + y^2

# calc y
#  y^2 = r^2 - x^2
#  y = sqrt ( r^2 - x^2 )

#-------------------------------------------
#https://jshingler.github.io/TOS-and-Thinkscript-Snippet-Collection/TOS%20&%20Thinkscript%20Collection.html#c-draw-a-line-between-two-price-points
# jshingler web site
#C-DRAW A LINE BETWEEN TWO PRICE POINTS
#Hint: Draws a line between to points defined by dates, times and price type
#Developed by RCG3 and StanL on the ThinkScript Lounge 1/2/14
#-------------------------------------------

#def na = double.nan;
#def bn = barnumber();

def bn1_date = if bn == 1 then GetYYYYMMDD() else bn1_date[1];

input time1 = 1130; #hint time1: EST , Time of first point using the 24-hour clock
input date1 = 20230911; #hint date1:Date of the first point in YYYYMMDD format
input time2 = 1300; #hint time2: EST , Time of second point using the 24-hour clock
input date2 = 20231211; #hint date2: Date of the first point in YYYYMMDD format
input price = close; #hint price: Select the price type desired


def date1ok = (date1 < bn1_date);
input show_dates = no;
addlabel(show_dates and date1ok, "1st date is off the chart", (if date1ok then color.red else color.gray));
#addlabel(show_dates, "1st bar date " + bn1_date, color.yellow);
addlabel(show_dates, "1st date " + date1, color.yellow);
addlabel(show_dates, "2nd date " + date2, color.yellow);

def date= getyyyymmdd();
def x1= if secondsfromtime(time1) == 0 and date1==date then barnumber() else x1[1];
def y1= if secondsfromtime(time1) == 0 and date1==date then price else y1[1];
def x2= if secondsfromtime(time2) == 0 and date2==date then barnumber() else x2[1];
def y2= if secondsfromtime(time2) == 0 and date2==date then price else y2[1];

#def x11= highestall(x1);
#def y11= highestall(y1);
#def x22= highestall(x2);
#def y22= highestall(y2);


def cup_top = max(left, pivot);
def cup_ht = cup_top - base;


def x11 = left_bn;
def y11 = cup_top;
def x22 = pivot_bn;
def y22 = cup_top;



def slope= (y22-y11)/(x22-x11);

#plot line = if x1!=0 and x2[1]==0 then y1+((barnumber()-x1)*slope) else double.nan;
#line.setdefaultcolor(color.pink);



#def  Angle_deg = ATan(slope) * 180 / Double.Pi;

#addLabel(yes, "Slope = " +  Angle_deg + "degrees", color.CYAN);#Angle printout has no consistency at various aggs
#alert(price crosses line, "Price crossed trendline", alert.once,sound.chimes);# uncomment this line if used as a trendline

#  ----------------------------------
# width of 2 points
def point_width = x22 - x11;

# horz width between 2 points
def point_width_half = floor(point_width/2);

#  ----------------------------------
# height of 2 points
def maxy = max(y11, y22);
def miny = min(y11, y22);

def point_height = maxy - miny;
def point_height_half = round(point_height/2, 2);

#  ----------------------------------
# center point of circle
def centerx = (x11 + point_width_half);
def centery = (miny + point_height_half);

#  ----------------------------------

input test_arc_labels = no;

#addlabel(test_arc_labels, "bars |" + x1 + "|" + width + "|" + x22 , color.yellow);
#addlabel(test_arc_labels, "$$ |" + y1 + "|" + height + "|" + y22 , color.yellow);

addlabel(test_arc_labels, "bars " + x22 + " - " + x11 + " = " + point_width + " |  1/2 = " + (point_width/2), color.yellow);
addlabel(test_arc_labels, "$$ " + maxy + " - " + miny + " = " + point_height, color.yellow);

#  ----------------------------------

# adjusted rad  -  pythagorean
#input height_factor = 13.0;
input height_factor = 1.0;
#def height0 = halfheight * height_factor;
def point_yfac = point_height_half * height_factor;


# use center x,y point and one x,y point, into pathagorean therum to calc hypot = radius
# horz rad , adjusted bar qty of a radius that spans the circle
def radz = floor(sqrt( point_width_half*point_width_half + point_yfac*point_yfac));

addlabel(test_arc_labels, "x " + point_width_half + " |  y " + point_yfac, color.white);
addlabel(test_arc_labels, "adj rad, bars " + radz, color.white);


#  ----------------------------------
#////////////////////////////////////////////


# the bars within the circle
#def circle_bars3 = if ( bn >= floor(x11 - radz) and bn <= floor(x22 + radz)) then 1 else 0;
def circle_bars3 = if ( bn >= floor(centerx - radz) and bn <= floor(centerx + radz)) then 1 else 0;

def barx3 = if !circle_bars3 then na else floor(absvalue(centerx - bn));

def arc_ht = sqrt(radz * radz);



input test4 = no;
addchartbubble(test4 and circle_bars3,low,
 bn + "\n" +
 x11 + " x1\n" +
 x22 + " x2\n" +
 circle_bars3 + "\n" +
 centerx + " c\n" +
 radz + " Rz\n" +
 arc_ht + " Aht"
, (if circle_bars3 then color.yellow else color.gray),no);


# y = sqrt ( r^2 - x^2 )

#def y = sqrt( radz*radz -
def circle_y3 = if !circle_bars3 then na else sqrt( (radz * radz) - (barx3 * barx3) );

#def facy = cup_ht / (centery - circle_y3);
# ratio of arc ht to cup ht.  to scale the arc
def facy = cup_ht / arc_ht;


addchartbubble(0 and circle_bars3, low, facy, color.white, no);





#input yfactor3 = .08;
#input yfactor3 = .2;
#input yfactor = .04;
def yfactor3 = facy;


#plot ytop3 =  centery + (circle_y3 * yfactor3);
plot ybot3 = centery - (circle_y3 * yfactor3);
#ytop3.SetDefaultColor(Color.cyan);
ybot3.SetDefaultColor(Color.cyan);


#  ----------------------------------

input rad_factor = 0.5;
#input y_factor = 0.5;
def rad_fac_num = floor(x11*rad_factor);
def bnsmall = x11 - rad_fac_num;
def bnbig = x22 + rad_fac_num;

# ---------------------

# pythag  radz
#def bnsmall = x11 - rad_fac_num;
#def bnbig = x22 + rad_fac_num;

# ----------------------

addlabel(0, "small bns " + bnsmall + " " + x11, color.cyan);
addlabel(0, "big bns " + x22 + " " + bnbig, color.cyan);


#def circle_bars = if ( bn >= x11 and bn <= x22) then 1 else 0;
def circle_bars = if ( bn >= floor(x11*(1-rad_factor)) and bn <= floor(x22*(1+rad_factor))) then 1 else 0;



# -----------------------------------------
# def y = (pt1price + pt2price ) / 2;
#calc x and y center

#calc
#calc y
# y^2 = r^2 - x^2
# y = sqrt ( r^2 - x^2 )


# radius bars
def rad1 = centerx - x11;
#def rad2 = floor((x11 + x22)/2);

#addlabel(1, "rad0 " + rad0, color.yellow);
addlabel(test_arc_labels, "point_x " + point_width_half, color.yellow);


addlabel(test_arc_labels, "rad1 " + rad1, color.cyan);
#addlabel(1, "rad2 " + rad2, color.cyan);


# 2 pt height diff  used to make factor ??
#input rad_factor = 1.0;


# if bars >= circle bars <=  ,   centerx - bn
def barx = if !circle_bars then na else floor(absvalue(centerx - bn)*rad_factor);


#def radx = rad0 * rad_factor;
def radx = point_width_half * rad_factor;

# y = sqrt ( r^2 - x^2 )
# circle_bars
#def circley = if !circle_bars then na else sqrt( (rad0 * rad0) - (barx * barx) );
def circley = if !circle_bars then na else sqrt( (radx * radx) - (barx * barx) );


#input yfactor = .08;
#input yfactor = .04;
#plot ytop =  centery + (circley * yfactor);
#plot ybot =  centery - (circley * yfactor);
#ytop.SetDefaultColor(Color.magenta);
#ybot.SetDefaultColor(Color.violet);


addlabel(test_arc_labels, "center x " + centerx, color.yellow);
addlabel(test_arc_labels, "center y " + centery, color.yellow);

# center point
input show_arc_center = no;
plot ctr = if show_arc_center and bn == centerx then centery else na;
ctr.SetPaintingStrategy(PaintingStrategy.SQUARES);
ctr.SetDefaultColor(Color.yellow);
ctr.setlineweight(4);
#ctr.hidebubble();


# --------------------------------
# test codes

input test2 = no;
addchartbubble(test2, low,
 bn + "\n" +
 centerx + "\n" +
 centery
, ( if ( bn == centerx) then color.yellow else color.gray), no);


input test1 = no;
addchartbubble(test1, low,
x1 + "\n" +
y1 + "\n" +
x2 + "\n" +
y2 + "\n" +
x22 + "\n" +
y22 + "\n" +
slope
, color.yellow, no);


#-------------------------------------------

# ref codes

#from tos chat - mobius
def data = getYYYYMMDD();
def year = Round(data/10000, 0);
def month = Round((data % 10000) / 100, 0);
def day = (data % 100);
#addLabel(1, "date: " + month + "/" + day + "/" + AsPrice(year), color.white);
#


#AMZN 15min 5/2022

#//////////////////////////////////////
#
 
Last edited by a moderator:
try my attempts. you may combine it with @halcyonguy code.
https://usethinkscript.com/threads/cup-and-handle-indicator-for-thinkorswim.405/page-3#post-136060

CSS:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9
# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html

input sensitivty = 10;    #Hint sensitivty: No of Conditions to considered. Max Value = 11
input showsetupLines = yes;
input pivotLookback = 90;
input cupLookback = 325;
input showMovAvgLine = yes;
input movAvgType = AverageType.SIMPLE;
input movAvgLength = 200;

def na = Double.NaN;
def last = isNaN(Close);
def sens = Min(11, Max(sensitivty, 1));
def n = barNumber();
def bar = if !last then n else bar[1];
def movAvg = MovingAverage(movAvgType, close, movAvgLength);
def PvtHH = Highest(high, pivotLookback);
def leftCupHH = Highest(high, cupLookback);
def priorLL = lowestAll(low);
def currentClose = close;
def pvtOfst     = GetMaxValueOffset(high, pivotLookback);
def leftCupOfst = GetMaxValueOffset(high, cupLookback);
def pivotOffset   = if (isNaN(pvtOfst) or pvtOfst==0) then 1 else pvtOfst;
def leftCupOffset = if (isNaN(leftCupOfst) or leftCupOfst==0) then 1 else leftCupOfst;
def leftCupLL = fold i = 1 to leftCupOffset with p = low do
                 if p <= GetValue(low, i) then p else GetValue(low, i);
def depth = fold j = 1 to pivotOffset with q=low do
                 if q <= GetValue(low, j)  then q else GetValue(low, j);
# Calculate leftCup and offset
#def leftCupOffset = Bar - pivotOffset;
def handleLength = pivotOffset;
def cupLength = leftCupOffset - pivotOffset;
def priorLow = priorLL;
def leftCup  = HighestAll(InertiaAll(leftCupHH, 2));
def baseLow  = HighestAll(InertiaAll(leftCupLL, 2));
def pivot    = HighestAll(InertiaAll(PvtHH, 2));
def handlelow = HighestAll(InertiaAll(depth, 2));

def handleDepthPct     = (pivot - handlelow) / handlelow * 100;
def cupToHandleRatio   = cupLength / (cupLength + handleLength) * 100;
def pivotPctOffLeftCup = (pivot - leftCup) / leftCup * 100;
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def cupDepthPct  = (leftCup - baseLow) / leftCup * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + handlelow) / 2;

def r01 = currentClose >= 1;
def r02 = (currentClose >= 0.95 * movAvg);
def r03 = (pivotPctOffLeftCup <= 5);
def r04 = (pivotPctOffLeftCup >= -40);
def r05 = (leftCupOffset >= 25);
def r06 = (leftCupOffset <= cupLookback);
def r07 = (cupToHandleRatio >= 3);
def r08 = (setupGainPct >= 3);
def r09 = (cupDepthPct <= 60);
def r10 = (handleDepthPct <= 30);
def r11 = (midpointHandle >= midpointBase);

def totCond = r01 + r02 + r03 + r04 + r05 + r06 + r07 + r08 + r09 + r10 + r11;


def active;
def sigCond = totCond>=sens and totCond[1] < sens and active[1];
if leftCupHH!= leftCupHH[1] and !active[1] {
    active = yes;
    } else if sigCond {
    active = no;
   } else {
    active = active[1];
}
def break;
def breakSig;
def cnt;
if sigCond {
    cnt   = 0;
    break =  yes;
    breakSig = high;
    } else {
    cnt   = if cnt[1] > cupLookback then 0 else cnt[1] + 1;
    break = if low[1] > breakSig[1] then no else yes;
    breakSig = if !break or cnt == 0 then na else breakSig[1];
}
AddChartBubble(!break and break[1], low, "break", color.CYAN, no);

plot breakLine = if breakSig then breakSig else na;
breakLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
breakLine.SetDefaultColor(Color.YELLOW);


plot movAvgLine = if showMovAvgLine then movAvg else na;
movAvgLine.SetDefaultColor(Color.RED);

plot CupAndHandle = if  active and !active[1] then low else na;#cupAndHandleCondition;
CupAndHandle.SetLineWeight(2);
CupAndHandle.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
CupAndHandle.SetDefaultColor(Color.YELLOW);


#-- END of CODE
 
Last edited by a moderator:
@samer800 or @BenTen or someone with more expertise check below?

I used the conditions from https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html and took a shot at building the cup and handle indicator. But I don't see any result. I am not sure if I misunderstood the conditions or plotted wrongly.

I used the previously posted scan scripts, but the results seemed to be a lot of false positives. I am not an expert at coding this, but figured I will give it a try.

Help please.

Code:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9

# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
def currentClose = close;
def pivot = highest(high, 90);
def pivotPctOffLeftCup = (pivot - highest(high, 325)) / highest(high, 325) * 100;
def leftCup = highest(high, 325);
def cupToHandleRatio = (leftCup - pivot) / (pivot - low);
def priorLow = lowest(low, 325);
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def baseLow = lowest(low, 325);
def cupDepthPct = (leftCup - baseLow) / leftCup * 100;
def handleDepthPct = (pivot - low) / pivot * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + low) / 2;

# Cup and Handle Conditions
def cupAndHandleCondition = currentClose >= 1
    and currentClose >= 0.95 * simpleMovingAvg(close, 200)
    and pivotPctOffLeftCup <= 5
    and pivotPctOffLeftCup >= -40
    and leftCup - pivot >= 25
    and leftCup - pivot <= 325
    and cupToHandleRatio >= 3
    and priorLow - lowest(low, 25) >= 0.3 * priorLow
    and setupGainPct >= 30
    and baseLow == lowest(low, 325)
    and cupDepthPct <= 60
    and handleDepthPct <= 30
    and midpointHandle >= midpointBase;

plot CupAndHandle = cupAndHandleCondition;

# Plot Curve Connecting Data Points
plot ConnectingCurve_priorLow = if cupAndHandleCondition then priorLow else Double.NaN;
ConnectingCurve_priorLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_priorLow.SetDefaultColor(Color.CYAN);
ConnectingCurve_priorLow.SetLineWeight(3);

plot ConnectingCurve_LeftCup = if cupAndHandleCondition then leftCup else Double.NaN;
ConnectingCurve_LeftCup.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_LeftCup.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_baseLow = if cupAndHandleCondition then baseLow else Double.NaN;
ConnectingCurve_baseLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_baseLow.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_Pivot = if cupAndHandleCondition then pivot else Double.NaN;
ConnectingCurve_Pivot.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_Pivot.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_CurrentClose = if cupAndHandleCondition then currentClose else Double.NaN;
ConnectingCurve_CurrentClose.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_CurrentClose.SetDefaultColor(Color.CYAN);

# Alerts
alert(cupAndHandleCondition, "Cup and Handle Pattern Detected", alert.Bar, Sound.Bell);

one thing,
these formulas are working with price values, not time,
and leftCup - pivot >= 25
and leftCup - pivot <= 325
so they will not produce a quantity of days.

might be able to use this to count bars between 2 points...
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/GetMaxValueOffset


a search
https://usethinkscript.com/search/1424881/?q=cup+and+handle&o=date

a programmer who created a cup and handle (for sale elsewhere)
robert payne
https://usethinkscript.com/threads/cup-and-handle-indicator-for-thinkorswim.405/#post-5119

this may be of use
https://usethinkscript.com/threads/...nel-prc-quadratic-regression.1491/#post-33306
 
Last edited:
Thanks so much @halcyonguy

I modified the logic a bit and also added labels to make it easy to verify the match. It does look better. I think I am coding something wrong as I have been getting ZERO values in the last 60 days. But I know tickers SLN, ML clearly match the condition when I do a visual inspection.

Below is my revised code.

Code:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9

# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
def currentClose = close;
def pivotOffset = Highest(high, 90);
def pivot = GetValue(pivotOffset, 0);
def pivotOffsetMax = HighestAll(pivotOffset);
def pivotIndex = CompoundValue(1, if (pivotOffset == pivotOffsetMax) then BarNumber() else GetValue(pivotIndex, 1), 0);

# Calculate leftCup and offset
def leftCup = Highest(high, 325);
def leftCupOffset = BarNumber() - pivotIndex;
def pivotPctOffLeftCup = (pivot - Highest(high, 325)) / Highest(high, 325) * 100;
def cupToHandleRatio = (leftCup - pivot) / (pivot - low);
def priorLow = Lowest(low, 325);
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def baseLow = Lowest(low, 325);
def cupDepthPct = (leftCup - baseLow) / leftCup * 100;
def handleDepthPct = (pivot - low) / pivot * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + low) / 2;

# Cup and Handle Conditions check
def cupAndHandleCondition = currentClose >= 1
    and currentClose >= 0.95 * SimpleMovingAvg(close, 200)
    and pivotPctOffLeftCup <= 5
    and pivotPctOffLeftCup >= -40
    and leftCupOffset >= 25
    and leftCupOffset <= 325
    and cupToHandleRatio >= 3
    and priorLow - Lowest(low, 25) >= 0.3 * priorLow
    and setupGainPct >= 30
    and baseLow == Lowest(low, 325)
    and cupDepthPct <= 60
    and handleDepthPct <= 30
    and midpointHandle >= midpointBase;

plot CupAndHandle = cupAndHandleCondition;

# Plot Curve Connecting Data Points
plot ConnectingCurve_priorLow = if cupAndHandleCondition then priorLow else Double.NaN;
ConnectingCurve_priorLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_priorLow.SetDefaultColor(Color.CYAN);
ConnectingCurve_priorLow.SetLineWeight(3);

plot ConnectingCurve_LeftCup = if cupAndHandleCondition then leftCup else Double.NaN;
ConnectingCurve_LeftCup.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_LeftCup.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_baseLow = if cupAndHandleCondition then baseLow else Double.NaN;
ConnectingCurve_baseLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_baseLow.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_Pivot = if cupAndHandleCondition then pivot else Double.NaN;
ConnectingCurve_Pivot.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_Pivot.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_CurrentClose = if cupAndHandleCondition then currentClose else Double.NaN;
ConnectingCurve_CurrentClose.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_CurrentClose.SetDefaultColor(Color.CYAN);

# Alerts
Alert(cupAndHandleCondition, "Cup and Handle Pattern Detected", Alert.BAR, Sound.Bell);

# DEBUG Check for conditions

AddLabel(yes, "Close = " + currentClose, Color.MAGENTA);
AddLabel(yes, "PivotPctOffLeftCup = " + pivotPctOffLeftCup, Color.MAGENTA);
AddLabel(yes, "LeftCup Offset = " + leftCupOffset, Color.MAGENTA);
AddLabel(yes, "Pivot = " + pivot, Color.MAGENTA);
AddLabel(yes, "CupToHandleRatio = " + cupToHandleRatio, Color.MAGENTA);
AddLabel(yes, "priorLow = " + priorLow, Color.MAGENTA);
AddLabel(yes, "setupGainPct = " + setupGainPct, Color.MAGENTA);
AddLabel(yes, "baseLow = " + baseLow, Color.MAGENTA);
AddLabel(yes, "cupDepthPct = " + cupDepthPct, Color.MAGENTA);
AddLabel(yes, "handleDepthPct = " + handleDepthPct, Color.MAGENTA);
AddLabel(yes, "midpointHandle = " + midpointHandle, Color.MAGENTA);
AddLabel(yes, "midpointBase = " + midpointBase, Color.MAGENTA);
AddLabel(yes, "cupAndHandleCondition = " + cupAndHandleCondition, Color.MAGENTA);

Thanks in advance for any help

Merry Christmas and Happy Holidays.
 
Thanks so much @halcyonguy

I modified the logic a bit and also added labels to make it easy to verify the match. It does look better. I think I am coding something wrong as I have been getting ZERO values in the last 60 days. But I know tickers SLN, ML clearly match the condition when I do a visual inspection.

Below is my revised code.

Code:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9

# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
def currentClose = close;
def pivotOffset = Highest(high, 90);
def pivot = GetValue(pivotOffset, 0);
def pivotOffsetMax = HighestAll(pivotOffset);
def pivotIndex = CompoundValue(1, if (pivotOffset == pivotOffsetMax) then BarNumber() else GetValue(pivotIndex, 1), 0);

# Calculate leftCup and offset
def leftCup = Highest(high, 325);
def leftCupOffset = BarNumber() - pivotIndex;
def pivotPctOffLeftCup = (pivot - Highest(high, 325)) / Highest(high, 325) * 100;
def cupToHandleRatio = (leftCup - pivot) / (pivot - low);
def priorLow = Lowest(low, 325);
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def baseLow = Lowest(low, 325);
def cupDepthPct = (leftCup - baseLow) / leftCup * 100;
def handleDepthPct = (pivot - low) / pivot * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + low) / 2;

# Cup and Handle Conditions check
def cupAndHandleCondition = currentClose >= 1
    and currentClose >= 0.95 * SimpleMovingAvg(close, 200)
    and pivotPctOffLeftCup <= 5
    and pivotPctOffLeftCup >= -40
    and leftCupOffset >= 25
    and leftCupOffset <= 325
    and cupToHandleRatio >= 3
    and priorLow - Lowest(low, 25) >= 0.3 * priorLow
    and setupGainPct >= 30
    and baseLow == Lowest(low, 325)
    and cupDepthPct <= 60
    and handleDepthPct <= 30
    and midpointHandle >= midpointBase;

plot CupAndHandle = cupAndHandleCondition;

# Plot Curve Connecting Data Points
plot ConnectingCurve_priorLow = if cupAndHandleCondition then priorLow else Double.NaN;
ConnectingCurve_priorLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_priorLow.SetDefaultColor(Color.CYAN);
ConnectingCurve_priorLow.SetLineWeight(3);

plot ConnectingCurve_LeftCup = if cupAndHandleCondition then leftCup else Double.NaN;
ConnectingCurve_LeftCup.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_LeftCup.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_baseLow = if cupAndHandleCondition then baseLow else Double.NaN;
ConnectingCurve_baseLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_baseLow.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_Pivot = if cupAndHandleCondition then pivot else Double.NaN;
ConnectingCurve_Pivot.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_Pivot.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_CurrentClose = if cupAndHandleCondition then currentClose else Double.NaN;
ConnectingCurve_CurrentClose.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_CurrentClose.SetDefaultColor(Color.CYAN);

# Alerts
Alert(cupAndHandleCondition, "Cup and Handle Pattern Detected", Alert.BAR, Sound.Bell);

# DEBUG Check for conditions

AddLabel(yes, "Close = " + currentClose, Color.MAGENTA);
AddLabel(yes, "PivotPctOffLeftCup = " + pivotPctOffLeftCup, Color.MAGENTA);
AddLabel(yes, "LeftCup Offset = " + leftCupOffset, Color.MAGENTA);
AddLabel(yes, "Pivot = " + pivot, Color.MAGENTA);
AddLabel(yes, "CupToHandleRatio = " + cupToHandleRatio, Color.MAGENTA);
AddLabel(yes, "priorLow = " + priorLow, Color.MAGENTA);
AddLabel(yes, "setupGainPct = " + setupGainPct, Color.MAGENTA);
AddLabel(yes, "baseLow = " + baseLow, Color.MAGENTA);
AddLabel(yes, "cupDepthPct = " + cupDepthPct, Color.MAGENTA);
AddLabel(yes, "handleDepthPct = " + handleDepthPct, Color.MAGENTA);
AddLabel(yes, "midpointHandle = " + midpointHandle, Color.MAGENTA);
AddLabel(yes, "midpointBase = " + midpointBase, Color.MAGENTA);
AddLabel(yes, "cupAndHandleCondition = " + cupAndHandleCondition, Color.MAGENTA);

Thanks in advance for any help

Merry Christmas and Happy Holidays.

having a formula with 13 rules is a lot to debug.
i would disable all of the rules, except the 1st one. get it to work.
then add a 2nd rule. get it to work.
repeat.....

--------------------------

you don't seem to be checking if the signals are in the correct sequence. just looking for price levels.
could use GetMaxValueOffset() to get an offset to the possible signals
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/GetMaxValueOffset

or several fold loops to look back at the bars.
once you have offsets, then use getvalue() to read price levels, and compare them

------------------------------

not a fix, just some debugging,
i didn't study the formulas or the source of the info. in early stages of debugging, i try to get something to appear on the chart. after that tweak it.


labels only show data from the last bar. so not very helpful in debugging. it is better to use bubbles, to display values on many bars.

why are you plotting a logic value?
plot CupAndHandle = cupAndHandleCondition;
that will make a line at 0 and 1.
better to plot a shape,
CupAndHandle.SetPaintingStrategy(PaintingStrategy.BOOLEAN_wedge_up);

or use addverticalline(CupAndHandle, "-"); to draw vertical lines when a signal happens

after adding the wedge and vertical line codes, i don't see anything on SLN or ML.

--------------------------

so the next step would be to display some variables with a bubble
i would copy the whole , def cupAndHandleCondition = formula and put in a bubble.
if wanting to display a condition result, in a bubble, put parenthesis around it.
( currentClose >= 1 )
\n forces a new line


Code:
addchartbubble(1, low*0.99,
(currentClose >= 1) + "\n" +
(currentClose >= 0.95 * SimpleMovingAvg(close, 200)) + "\n" +
(pivotPctOffLeftCup <= 5) + "\n" +
(pivotPctOffLeftCup >= -40) + "\n\n" +
(leftCupOffset >= 25) + "\n" +
(leftCupOffset <= 325) + "\n" +
(cupToHandleRatio >= 3) + "\n" +
(priorLow - Lowest(low, 25) >= 0.3 * priorLow) + "\n\n" +
(setupGainPct >= 30) + "\n" +
(baseLow == Lowest(low, 325)) + "\n" +
(cupDepthPct <= 60) + "\n" +
(handleDepthPct <= 30) + "\n\n" +
(midpointHandle >= midpointBase) + "\n" +
cupAndHandleCondition + "\n"
, color.yellow, no);


the 7th, 8th, 11th signals seem be be 0 often. check them out with another bubble. and split up the sub sections.

Code:
addchartbubble(1, low*0.99,
#(cupToHandleRatio >= 3) + "\n" +
cupToHandleRatio + "\n" +

#(priorLow - Lowest(low, 25) >= 0.3 * priorLow) + "\n\n" +
priorLow + "\n" +
Lowest(low, 25) + "\n" +

#(cupDepthPct <= 60) + "\n"
cupDepthPct
, color.yellow, no);


cupToHandleRatio
this is changing, sometimes this rule is true when price is rising. skip it for now.


(priorLow - Lowest(low, 25) >= 0.3 * priorLow)
this seems to never be true.
(priorLow - Lowest(low, 25) this part seems to be negative, so always false


cupDepthPct
this seems to be > 70, so false



summary, look at these formulas, and the variables driving them,
(priorLow - Lowest(low, 25) >= 0.3 * priorLow)
cupDepthPct



----------------------

i would have made formulas for each of the rules of def cupAndHandleCondition =
so they could be referenced easily, more than once.

Code:
def r01 = currentClose >= 1;
def r02 = (currentClose >= 0.95 * SimpleMovingAvg(close, 200));
def r03 = (pivotPctOffLeftCup <= 5);
def r04 = (pivotPctOffLeftCup >= -40);
def r05 = (leftCupOffset >= 25);
def r06 = (leftCupOffset <= 325);
def r07 = (cupToHandleRatio >= 3);
def r08 = (priorLow - Lowest(low, 25) >= 0.3 * priorLow);
def r09 = (setupGainPct >= 30);
def r10 = (baseLow == Lowest(low, 325));
def r11 = (cupDepthPct <= 60);
def r12 = (handleDepthPct <= 30);
def r13 = (midpointHandle >= midpointBase);

def cupAndHandleCondition = r01 and r02 and r03 and r04 and r05 and r06 and r07 and r08 and r10 and r11 and r12 and r13;


my test code
Code:
#cup_n_handle_2

#https://usethinkscript.com/threads/attempt-at-cup-and-handle-pattern.17536/#post-135874
#Attempt at Cup and Handle Pattern


# Cup and Handle Indicator
# bulusufinances
# version - 0.9

# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
def currentClose = close;
def pivotOffset = Highest(high, 90);
def pivot = GetValue(pivotOffset, 0);
def pivotOffsetMax = HighestAll(pivotOffset);
def pivotIndex = CompoundValue(1, if (pivotOffset == pivotOffsetMax) then BarNumber() else GetValue(pivotIndex, 1), 0);

# Calculate leftCup and offset
def leftCup = Highest(high, 325);
def leftCupOffset = BarNumber() - pivotIndex;
def pivotPctOffLeftCup = (pivot - Highest(high, 325)) / Highest(high, 325) * 100;
def cupToHandleRatio = (leftCup - pivot) / (pivot - low);
def priorLow = Lowest(low, 325);
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def baseLow = Lowest(low, 325);
def cupDepthPct = (leftCup - baseLow) / leftCup * 100;
def handleDepthPct = (pivot - low) / pivot * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + low) / 2;

# Cup and Handle Conditions check
def cupAndHandleCondition = currentClose >= 1
    and currentClose >= 0.95 * SimpleMovingAvg(close, 200)
    and pivotPctOffLeftCup <= 5
    and pivotPctOffLeftCup >= -40
    and leftCupOffset >= 25
    and leftCupOffset <= 325
    and cupToHandleRatio >= 3
    and priorLow - Lowest(low, 25) >= 0.3 * priorLow
    and setupGainPct >= 30
    and baseLow == Lowest(low, 325)
    and cupDepthPct <= 60
    and handleDepthPct <= 30
    and midpointHandle >= midpointBase;




addchartbubble(0, low*0.99,
(currentClose >= 1) + "\n" +
(currentClose >= 0.95 * SimpleMovingAvg(close, 200)) + "\n" +
(pivotPctOffLeftCup <= 5) + "\n" +
(pivotPctOffLeftCup >= -40) + "\n\n" +
(leftCupOffset >= 25) + "\n" +
(leftCupOffset <= 325) + "\n" +
(cupToHandleRatio >= 3) + "\n" +
(priorLow - Lowest(low, 25) >= 0.3 * priorLow) + "\n\n" +
(setupGainPct >= 30) + "\n" +
(baseLow == Lowest(low, 325)) + "\n" +
(cupDepthPct <= 60) + "\n" +
(handleDepthPct <= 30) + "\n\n" +
(midpointHandle >= midpointBase) + "\n"
#+ cupAndHandleCondition + "\n"
, color.yellow, no);




def r01 = currentClose >= 1;
def r02 = (currentClose >= 0.95 * SimpleMovingAvg(close, 200));
def r03 = (pivotPctOffLeftCup <= 5);
def r04 = (pivotPctOffLeftCup >= -40);
def r05 = (leftCupOffset >= 25);
def r06 = (leftCupOffset <= 325);
def r07 = (cupToHandleRatio >= 3);
def r08 = (priorLow - Lowest(low, 25) >= 0.3 * priorLow);
def r09 = (setupGainPct >= 30);
def r10 = (baseLow == Lowest(low, 325));
def r11 = (cupDepthPct <= 60);
def r12 = (handleDepthPct <= 30);
def r13 = (midpointHandle >= midpointBase);

def z_cupAndHandleCondition = r01 and r02 and r03 and r04 and r05 and r06 and r07 and r08 and r10 and r11 and r12 and r13;
 



plot CupAndHandle = cupAndHandleCondition;
CupAndHandle.SetPaintingStrategy(PaintingStrategy.BOOLEAN_wedge_up);
CupAndHandle.SetDefaultColor(Color.cyan);
CupAndHandle.setlineweight(3);

addverticalline(CupAndHandle, "-");



addchartbubble(1, low*0.99,
#(currentClose >= 1) + "\n" +
#(currentClose >= 0.95 * SimpleMovingAvg(close, 200)) + "\n" +
#(pivotPctOffLeftCup <= 5) + "\n" +
#(pivotPctOffLeftCup >= -40) + "\n\n" +
#(leftCupOffset >= 25) + "\n" +
#(leftCupOffset <= 325) + "\n" +
(cupToHandleRatio >= 3) + "\n" +
(priorLow - Lowest(low, 25) >= 0.3 * priorLow) + "\n" +
#(setupGainPct >= 30) + "\n" +
#(baseLow == Lowest(low, 325)) + "\n" +
(cupDepthPct <= 60) + "\n"
# +
#(handleDepthPct <= 30) + "\n\n" +
#(midpointHandle >= midpointBase) + "\n" +
#cupAndHandleCondition + "\n"
, color.yellow, no);



addchartbubble(1, low*0.99,
#(cupToHandleRatio >= 3) + "\n" +
cupToHandleRatio + "\n" +

#(priorLow - Lowest(low, 25) >= 0.3 * priorLow) + "\n\n" +
priorLow + "\n" +
Lowest(low, 25) + "\n" +

#(cupDepthPct <= 60) + "\n"
cupDepthPct
, color.yellow, no);


# Plot Curve Connecting Data Points
plot ConnectingCurve_priorLow = if cupAndHandleCondition then priorLow else Double.NaN;
ConnectingCurve_priorLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_priorLow.SetDefaultColor(Color.CYAN);
ConnectingCurve_priorLow.SetLineWeight(3);

plot ConnectingCurve_LeftCup = if cupAndHandleCondition then leftCup else Double.NaN;
ConnectingCurve_LeftCup.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_LeftCup.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_baseLow = if cupAndHandleCondition then baseLow else Double.NaN;
ConnectingCurve_baseLow.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_baseLow.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_Pivot = if cupAndHandleCondition then pivot else Double.NaN;
ConnectingCurve_Pivot.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_Pivot.SetDefaultColor(Color.CYAN);

plot ConnectingCurve_CurrentClose = if cupAndHandleCondition then currentClose else Double.NaN;
ConnectingCurve_CurrentClose.SetPaintingStrategy(PaintingStrategy.LINE);
ConnectingCurve_CurrentClose.SetDefaultColor(Color.CYAN);

# Alerts
Alert(cupAndHandleCondition, "Cup and Handle Pattern Detected", Alert.BAR, Sound.Bell);

# DEBUG Check for conditions

AddLabel(yes, "Close = " + currentClose, Color.MAGENTA);
AddLabel(yes, "PivotPctOffLeftCup = " + pivotPctOffLeftCup, Color.MAGENTA);
AddLabel(yes, "LeftCup Offset = " + leftCupOffset, Color.MAGENTA);
AddLabel(yes, "Pivot = " + pivot, Color.MAGENTA);
AddLabel(yes, "CupToHandleRatio = " + cupToHandleRatio, Color.MAGENTA);
AddLabel(yes, "priorLow = " + priorLow, Color.MAGENTA);
AddLabel(yes, "setupGainPct = " + setupGainPct, Color.MAGENTA);
AddLabel(yes, "baseLow = " + baseLow, Color.MAGENTA);
AddLabel(yes, "cupDepthPct = " + cupDepthPct, Color.MAGENTA);
AddLabel(yes, "handleDepthPct = " + handleDepthPct, Color.MAGENTA);
AddLabel(yes, "midpointHandle = " + midpointHandle, Color.MAGENTA);
AddLabel(yes, "midpointBase = " + midpointBase, Color.MAGENTA);
AddLabel(yes, "cupAndHandleCondition = " + cupAndHandleCondition, Color.MAGENTA);
#
 
Last edited:
@halcyonguy - Your feedback is VERY much appreciated. This is my second indicator, and I barely spent 10 hours reading (not a coder by profession). I am looking at the other examples and referencing and learning so that I can also code and contribute instead of asking @samer800 for everything :)

This feedback/guidance on a better way to write is super helpful, especially showing in bubbles and then finetuning.

I am taking a few days off to travel, and I will work on this when I am back.

Thanks so much again.
 
@halcyonguy - Your feedback is VERY much appreciated. This is my second indicator, and I barely spent 10 hours reading (not a coder by profession). I am looking at the other examples and referencing and learning so that I can also code and contribute instead of asking @samer800 for everything :)

This feedback/guidance on a better way to write is super helpful, especially showing in bubbles and then finetuning.

I am taking a few days off to travel, and I will work on this when I am back.

Thanks so much again.
your welcome
i don't want to discourage you, but this is a very ambitious project for anyone, especially a beginner. the fact that there isn't a full working study like this on this site, should indicate how hard it will be.

think about what you want to see on the chart.
do you just want to find the last bar of the cup and handle pattern, and... draw a arrow or something?
then all your offsets and references will programmed from the last pattern bar, looking back.

if you want to draw an arc for the cup and a line for the handle, then you will have to start at the beginning of the pattern and look at future bars.

it will be hard to determine whether a cup of 10 bars wide should be considered, or a cup of 300 bars wide.
or something in between? several fold loops will probably have to be used, checking many possibilities.
 
@halcyonguy - Your feedback is VERY much appreciated. This is my second indicator, and I barely spent 10 hours reading (not a coder by profession). I am looking at the other examples and referencing and learning so that I can also code and contribute instead of asking @samer800 for everything :)

This feedback/guidance on a better way to write is super helpful, especially showing in bubbles and then finetuning.

I am taking a few days off to travel, and I will work on this when I am back.

Thanks so much again.
sorry I am busy at work these days. but you did very well. By the way, I'm not a coder at all and never claimed to be, I learned from others as well and trying to pay back little :)
 
@samer800 - That is inspiring :) -- Any help here with this indicator is also much appreciated.

@halcyonguy: Thanks again. You are not at all discouraging. I figured it was complex. I will spend some cycles learning and coding. For your question, I was thinking of working with Pivot back from the close on the right to identify the cup. Not focused on the handle. Basically, Pivot --> Base low --> Left of the Cup and prior low if possible.

Regards.
 
@samer800 - That is inspiring :) -- Any help here with this indicator is also much appreciated.

@halcyonguy: Thanks again. You are not at all discouraging. I figured it was complex. I will spend some cycles learning and coding. For your question, I was thinking of working with Pivot back from the close on the right to identify the cup. Not focused on the handle. Basically, Pivot --> Base low --> Left of the Cup and prior low if possible.

Regards.

working on a study, following those rules , listed on that site in post1. got a cold, so don't know how much i'll get done...
 
@samer800 - That is inspiring :) -- Any help here with this indicator is also much appreciated.

@halcyonguy: Thanks again. You are not at all discouraging. I figured it was complex. I will spend some cycles learning and coding. For your question, I was thinking of working with Pivot back from the close on the right to identify the cup. Not focused on the handle. Basically, Pivot --> Base low --> Left of the Cup and prior low if possible.

Regards.


here is a partial, sloppy code.
it finds the pivot, base, and left side of a cup and handle. ( on EBAY day chart anyway)
haven't tested it.
it looks for data on every bar, with the intent to use the data from the last bar.

i copied those rules, listed on the site mentioned in post1, and started adding code.


Code:
#cup_n_handle_03


# test with EBAY  day chart


#https://usethinkscript.com/threads/attempt-at-cup-and-handle-pattern.17536/#post-135874
#Attempt at Cup and Handle Pattern
#bulusufinances  12/24


# from current bar, look back for a cup-handle

# copy and rewrite rules from this site
# https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html
# replace days , with bars

# r01  Current Close ,  close >= 6 and close >= ( 0.95 of ma200)

# r02  Pivot  , Highest high , end of cup, beginning of the Handle.  within last 90 bars

# r03  Pivot price % of Left Cup ,  Difference between the Left Cup and the Pivot, expressed as a percentage of the Left Cup.   %  <= +5% and % >= -40%

# r04  Left Cup , Highest high , beginning of the correction.    >= 25 days and <=325 bars from the pivot

# r05  Cup length to Handle length Ratio , cup bars >= ( 3 x handle bars)

# r06 , Prior Low  , lowest low before the cup left,   price Rise from Prior Low to Left Cup >=30%
# r06b  Setup Gain %    The rise from the prior low to the left cup measured as a percentage of the prior low , >= 30%

# r07  Base Low    Lowest low within the Cup.

# r08  Cup Depth   price Difference between the Left Cup and Base Low, expressed as a percentage of the Left Cup.   <=60%

# r09  Handle Depth    Difference between the Pivot and the Handle Low, expressed as a percentage of the Pivot.    <= 30%

# r10  Midpoint of Base    Price which marks half the distance between the Left Cup and the Base Low.    None

# r11  Midpoint of Handle    Price which marks half the distance between the Pivot and the Handle Low.    >= Midpoint of Base

#The stock must also meet these technical criteria to improve the chances of a successful breakout:       
# r1b  Current Close    The price at which the stock closed today.    >= $6

# r12  Average Volume    The average daily volume over the last 50 days    >=30,000

# r13  Relative Strength (RS)Rank    The stock’s weighted price appreciation over the prior year, as ranked against all other stocks in our database.    >=80


#-----------------------
# copy the rules and add code


def na = double.nan;
def bn = barnumber();
def cls = close;
#def lastbar = (!isnan(close) and isnan(close[-1]));
def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
#def lastbar = if l
def big = 99999;


# choose_wick_body01
input candle_levels = {default "wick" , "body" };
def highx;
def lowx;
switch (candle_levels) {
case "wick":
  highx = high;
  lowx = low;
case "body":
  highx = max(open, close);
  lowx = min(open, close);
}


#--------------------------
#https://usethinkscript.com/threads/zigzag-high-low-with-supply-demand-zones-for-thinkorswim.172/#post-7048
#post10  robert
#  +------------------------------------------------------------+
#  |  Example: How to extend levels to the right of the chart   |
#  |                        Robert Payne                        |
#  |               https://funwiththinkscript.com               |
#  +------------------------------------------------------------+
# define peaks / valleys
#def na = double.nan;
#def bn = BarNumber();
input peak_length = 10;
#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def offset = Min(peak_length - 1, lastBar - bn);
def peak = highx > Highest(highx[1], peak_length - 1) and highx == GetValue(Highest(highx, peak_length), -offset);
def valley = lowx < Lowest(lowx[1], peak_length - 1) and lowx == GetValue(Lowest(lowx, peak_length), -offset);

input peak_valley_arrows = yes;
plot zhi = if peak_valley_arrows and peak then high*1.001 else na;
plot zlo = if peak_valley_arrows and valley then low*0.999 else na;
zlo.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zlo.SetDefaultColor(Color.red);
zlo.setlineweight(1);
zlo.hidebubble();
zhi.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
zhi.SetDefaultColor(Color.green);
zhi.setlineweight(1);
zhi.hidebubble();


#------------------------







#-------------------------------
# rules and code
#  find offsets to signals, then calc barnumbers


# r01  Current Close ,  close >= 6 and close >= ( 0.95 of ma200)
input min_price = 6.0;
input avg1_type = AverageType.Simple;
input avg1_length = 200;
def avg1 = MovingAverage(avg1_type , cls , avg1_length );
input avg_factor = 0.95;
def r01 = (cls >= min_price) and (cls >= (avg_factor * avg1));
input show_average_line = no;
plot zavg1 = if show_average_line then avg1 else na;


# r02  Pivot  , Highest high , end of cup, beginning of the Handle.  within last 90 bars
#   my added rule -  pivot should be higher than current price
# offset to pivot bar , handle_len
def pivot_len = 90;
# pivot_off
def handle_len = fold a1 = 0 to pivot_len
  with p1
  while !getvalue(peak,a1)
  do p1+1;

def pivot_bn = if handle_len == pivot_len then 0 else highestall(if isnan(close) then 0 else (bn - handle_len));
def pivot = getvalue(highx, (bn - pivot_bn));

input test_r2 = no;
addchartbubble(test_r2, low*0.998,
bn + " bn\n" +
handle_len + " pivoff\n" +
pivot_bn + " pivbn\n" +
pivot + " piv"
, color.white, no);


# move down and add conditions to this formula
def cancel = if (pivot_bn == 0 or 0) then 1 else 0;
addlabel(cancel, " cancel , no cup-handle found ", color.cyan);


# r03 


# r04  Left Cup , Highest high , beginning of the correction.    >= 25 days and <=325 bars from the pivot

def pivotleftoffmin = 25;
def pivotleftoffmax = 325;
def left_start = (handle_len + pivotleftoffmin);
#def leftlenmax = pivotleftoffmax - left_start;
def leftlenmax = (handle_len + pivotleftoffmax);


# find prev peak , left side of cup
def left_off = fold a2 = handle_len + 1 to (pivotleftoffmax + handle_len)
  with p2 = handle_len+1
  while !getvalue(peak,a2)
  do p2+1;

def left_bn = if left_off == leftlenmax then 0 else highestall(if isnan(close) then 0 else (bn - (handle_len + left_off)));
def left = getvalue(highx, (bn - left_bn));

def cup_bars = pivot_bn - left_bn;


input test_r4 = no;
addchartbubble(test_r4, low*0.99,
bn + " bn\n" +
left_off + " leftoff\n" +
left_bn + " leftbn\n" +
left + " left\n" +
cup_bars + " cup"
, color.white, no);



# r03  Pivot price % of Left Cup ,  Difference between the Left Cup and the Pivot, expressed as a percentage of the Left Cup.   %  <= +5% and % >= -40%

def leftpivpermin = -40;
def leftpivpermax = 5.0;
def leftpivot_per = round(100*(left-pivot)/left,1);
def isleftper = leftpivot_per > leftpivpermin and leftpivot_per < leftpivpermax;


input test_r3 = no;
addchartbubble(test_r3, low*0.99,
 bn + " bn\n" +
 left + " lt\n" +
 pivot + " piv\n" +
 leftpivot_per + " %\n" +
 isleftper + "\n"
, color.white, no);





# r05  Cup length to Handle length Ratio , cup bars >= ( 3 x handle bars)
def ratio_min = 3.0;
def cuphandleratio = cup_bars/handle_len;
def iscupratio = cuphandleratio >= ratio_min;

input test_r5 = no;
addchartbubble(test_r5, low*0.99,
 bn + " bn\n" +
"cup len ratio\n" +
 cuphandleratio + "\n" +
 iscupratio + " is"
, color.white, no);




# r06 , Prior Low  , lowest low before the cup left,   price Rise from Prior Low to Left Cup >=30%
# r06b  Setup Gain %    The rise from the prior low to the left cup measured as a percentage of the prior low , >= 30%




# r07  Base Low    Lowest low within the Cup.
# offset to base low, from pivot
#def base_off = GetMinValueOffset(lowx[handle_len], cup);
def base_min = fold a3 = handle_len to cup_bars + handle_len
with p3 = big
do min(p3,getvalue(lowx,a3));

def base_off = fold a4 = handle_len to cup_bars + handle_len
  with p4
  do if base_min == getvalue(lowx, a4) then a4 else p4;
 

def base_bn = highestall(if isnan(close) then 0 else (bn - (base_off+handle_len)));


input test_r7 = no;
addchartbubble(test_r7, low*0.99,
 bn + " bn\n" +
base_off + " Basoff\n" +
base_bn + " Bbn"
, color.white, no);



# r08  Cup Depth   price Difference between the Left Cup and Base Low, expressed as a percentage of the Left Cup.   <=60%

# r09  Handle Depth    Difference between the Pivot and the Handle Low, expressed as a percentage of the Pivot.    <= 30%

# r10  Midpoint of Base    Price which marks half the distance between the Left Cup and the Base Low.    None

# r11  Midpoint of Handle    Price which marks half the distance between the Pivot and the Handle Low.    >= Midpoint of Base

#The stock must also meet these technical criteria to improve the chances of a successful breakout:       
# r1b  Current Close    The price at which the stock closed today.    >= $6

# r12  Average Volume    The average daily volume over the last 50 days    >=30,000

# r13  Relative Strength (RS)Rank    The stock’s weighted price appreciation over the prior year, as ranked against all other stocks in our database.    >=80





input test_bn = no;
addchartbubble(test_bn, low*0.99,
 bn + " bn"
, color.white, no);


def bubs = (pivot_bn == bn or left_bn == bn or base_bn == bn);

input test1_data = yes;
addchartbubble(test1_data and bubs, low*0.99,
 bn + "  BN\n" +
 pivot_bn + "  PIVOT\n" +
 base_bn + "  BASE\n" +
 left_bn + "  LEFT\n" 
, color.cyan, no);

#

bubbles that list barnumbers of, pivot, base, left
sbOHJ5Z.jpg
 
WOW -- That's magic :)

Thank you @halcyonguy - This looks really good. I will test when I am back tomorrow.

Much appreciated
try my attempts. you may combine it with @halcyonguy code.

CSS:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9
# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html

input sensitivty = 10;    #Hint sensitivty: No of Conditions to considered. Max Value = 11
input showsetupLines = yes;
input pivotLookback = 90;
input cupLookback = 325;
input showMovAvgLine = yes;
input movAvgType = AverageType.SIMPLE;
input movAvgLength = 200;

def na = Double.NaN;
def last = isNaN(Close);
def sens = Min(11, Max(sensitivty, 1));
def n = barNumber();
def bar = if !last then n else bar[1];
def movAvg = MovingAverage(movAvgType, close, movAvgLength);
def PvtHH = Highest(high, pivotLookback);
def leftCupHH = Highest(high, cupLookback);
def priorLL = lowestAll(low);
def currentClose = close;
def pvtOfst     = GetMaxValueOffset(high, pivotLookback);
def leftCupOfst = GetMaxValueOffset(high, cupLookback);
def pivotOffset   = if (isNaN(pvtOfst) or pvtOfst==0) then 1 else pvtOfst;
def leftCupOffset = if (isNaN(leftCupOfst) or leftCupOfst==0) then 1 else leftCupOfst;
def leftCupLL = fold i = 1 to leftCupOffset with p = low do
                 if p <= GetValue(low, i) then p else GetValue(low, i);
def depth = fold j = 1 to pivotOffset with q=low do
                 if q <= GetValue(low, j)  then q else GetValue(low, j);
# Calculate leftCup and offset
#def leftCupOffset = Bar - pivotOffset;
def handleLength = pivotOffset;
def cupLength = leftCupOffset - pivotOffset;
def priorLow = priorLL;
def leftCup  = HighestAll(InertiaAll(leftCupHH, 2));
def baseLow  = HighestAll(InertiaAll(leftCupLL, 2));
def pivot    = HighestAll(InertiaAll(PvtHH, 2));
def handlelow = HighestAll(InertiaAll(depth, 2));

def handleDepthPct     = (pivot - handlelow) / handlelow * 100;
def cupToHandleRatio   = cupLength / (cupLength + handleLength) * 100;
def pivotPctOffLeftCup = (pivot - leftCup) / leftCup * 100;
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def cupDepthPct  = (leftCup - baseLow) / leftCup * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + handlelow) / 2;

def r01 = currentClose >= 1;
def r02 = (currentClose >= 0.95 * movAvg);
def r03 = (pivotPctOffLeftCup <= 5);
def r04 = (pivotPctOffLeftCup >= -40);
def r05 = (leftCupOffset >= 25);
def r06 = (leftCupOffset <= cupLookback);
def r07 = (cupToHandleRatio >= 3);
def r08 = (setupGainPct >= 3);
def r09 = (cupDepthPct <= 60);
def r10 = (handleDepthPct <= 30);
def r11 = (midpointHandle >= midpointBase);

def totCond = r01 + r02 + r03 + r04 + r05 + r06 + r07 + r08 + r09 + r10 + r11;


def active;
def sigCond = totCond>=sens and totCond[1] < sens and active[1];
if leftCupHH!= leftCupHH[1] and !active[1] {
    active = yes;
    } else if sigCond {
    active = no;
   } else {
    active = active[1];
}
def break;
def breakSig;
def cnt;
if sigCond {
    cnt   = 0;
    break =  yes;
    breakSig = high;
    } else {
    cnt   = if cnt[1] > cupLookback then 0 else cnt[1] + 1;
    break = if low[1] > breakSig[1] then no else yes;
    breakSig = if !break or cnt == 0 then na else breakSig[1];
}
AddChartBubble(!break and break[1], low, "break", color.CYAN, no);

plot breakLine = if breakSig then breakSig else na;
breakLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
breakLine.SetDefaultColor(Color.YELLOW);


plot movAvgLine = if showMovAvgLine then movAvg else na;
movAvgLine.SetDefaultColor(Color.RED);

plot CupAndHandle = if  active and !active[1] then low else na;#cupAndHandleCondition;
CupAndHandle.SetLineWeight(2);
CupAndHandle.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
CupAndHandle.SetDefaultColor(Color.YELLOW);


#-- END of CODE
 
From Bulkowski site.

Cup with Handle: Important Bull Market Results
  • Overall performance rank (1 is best): 6 out of 56
  • Break even failure rate: 5%
  • Average rise: 52%
  • Throwback rate: 62%
  • Percentage meeting price target: 62%
  • The above numbers are based on 912 perfect trades.
 
# Scan SemiCup from Mobius V02.10.02.2021
Caveat: Scan will time-out on attempts to scan the Universe of Stocks! There HAS to be some filters to narrow down the pool of stocks being scanned. The example below, has the standard filters on price, market cap, volume but you can use any filters that fit your strategy.
Shared Scanner Link: http://tos.mx/x1Dbpp2
FfwftTx.png

This scanner code MUST be cut&pasted into the scanner! It will timeout if saved as a study as referenced in the scanner.
Ruby:
# Scan SemiCup
# Mobius
# V02.10.02.2021 Note: Corrects script fuctions and getValue() functions

script VariableMax
    {
     input price = close;
     input min = 0;
     input max = 0;
     plot VMax = fold i = min to max
                 with m = Double.NEGATIVE_INFINITY
                 do Max(m, getValue(price, i));
    }
script VariableMin
    {
     input price = close;
     input min = 0;
     input max = 0;
     plot VMin = fold i = min to max
                 with m = Double.POSITIVE_INFINITY
                 do Min(m, getValue(price, i));
    }
script DX
    {
     input DXPlus = close;
     input DXMinus = close;
     input min = 0;
     input max = 0;
     def SumDXPlus = fold i = min to max
                     with p
                     do p + getValue(DXPlus, i);
     def SumDXMinus = fold j = min to max
                      with m
                      do m + getValue(DXMinus, j);
     plot DX = AbsValue(SumDXPlus - SumDXMinus) / (SumDXPlus + SumDXMinus + 0.000000001) * 100;
    }

input price = close;
input minLength = 20;
input maxLength = 252;
input factor = 2.0;

assert(minLength > 0, "'min length' must be positive: " + minLength);
assert(factor >= 1, "'factor' must be greater than or equal to 1: " + factor);

def rawOffset = fold i = minLength to maxLength
                with off = -1
                do if off == -1 and getValue(price, i) > price * factor
                   then i
                   else off;
def offset = if IsNaN(rawOffset)
             then -1
             else rawOffset;
def logPrice = log(price);
def B2Offset = if offset < 0
               then -1
               else round(offset * 0.6, 0);
def DXPlus = Max(logPrice - logPrice[1], 0);
def DXMinus = Max(logPrice[1] - logPrice, 0);
def DX1 = DX(DXPlus, DXMinus, B2Offset + 1, offset + 1);
def DX2 = DX(DXPlus, DXMinus, 0, B2Offset + 1);
def B3Offset = if offset < 0
               then -1
               else round(offset * 0.4, 0);
def highestB2toB3 = VariableMax(logPrice, B3Offset + 1, B2Offset + 1);
def highestB3toB5 = VariableMax(logPrice, 0, B3Offset + 1);
def hiLogPrice = if IsNaN(getValue(logPrice, offset))
                 then logPrice
                 else getValue(logPrice, offset);
def loLogPrice = VariableMin(logPrice, 0, offset + 1);
def L2 = loLogPrice * 0.6 + hiLogPrice * 0.4;
def L3 = loLogPrice * 0.4 + hiLogPrice * 0.6;

# NOTE: For a chart study the following line of code should be changed to a plot statement.
def SemiCup = offset > 0 and DX1 > 25 and DX2 < 25 and highestB2toB3 < L3 and highestB3toB5 < L2;

# find last cup
def curBar = barNumber();
def cupEnd = HighestAll(if SemiCup
                        then curBar
                        else Double.NaN);
def rawCupOffset = HighestAll(if cupEnd == curBar and SemiCup
                              then offset
                              else Double.NaN);
def cupOffset = if IsNaN(rawCupOffset)
                then 0
                else rawCupOffset;
def cupHiLogPrice = HighestAll(if curBar == cupEnd
                               then getValue(logPrice, cupOffset)
                               else Double.NaN);
def cupLowLogPrice = HighestAll(if curBar == cupEnd
                                then VariableMin(logPrice, 0, cupOffset + 1)
                                else Double.NaN);
def found = curBar >= cupEnd - cupOffset and curBar <= cupEnd;
def hi = exp(cupHiLogPrice);
def lo = exp(cupLowLogPrice);
def t = curBar - cupEnd;
def dev = (hi - lo) * Power(t / cupOffset, 10);
plot Curve = if found
             then Min(hi, dev + 0.98 * lo)
             else Double.NaN;
# End Code: Corrected SemiCup Formation
a1.png
 
Last edited:
try my attempts. you may combine it with @halcyonguy code.

CSS:
# Cup and Handle Indicator
# bulusufinances
# version - 0.9
# Data Points for checking the cup and handle conditions
# website: https://www.breakoutwatch.com/bootstrapAssets/html/cupandhandlepattern.html

input sensitivty = 10;    #Hint sensitivty: No of Conditions to considered. Max Value = 11
input showsetupLines = yes;
input pivotLookback = 90;
input cupLookback = 325;
input showMovAvgLine = yes;
input movAvgType = AverageType.SIMPLE;
input movAvgLength = 200;

def na = Double.NaN;
def last = isNaN(Close);
def sens = Min(11, Max(sensitivty, 1));
def n = barNumber();
def bar = if !last then n else bar[1];
def movAvg = MovingAverage(movAvgType, close, movAvgLength);
def PvtHH = Highest(high, pivotLookback);
def leftCupHH = Highest(high, cupLookback);
def priorLL = lowestAll(low);
def currentClose = close;
def pvtOfst     = GetMaxValueOffset(high, pivotLookback);
def leftCupOfst = GetMaxValueOffset(high, cupLookback);
def pivotOffset   = if (isNaN(pvtOfst) or pvtOfst==0) then 1 else pvtOfst;
def leftCupOffset = if (isNaN(leftCupOfst) or leftCupOfst==0) then 1 else leftCupOfst;
def leftCupLL = fold i = 1 to leftCupOffset with p = low do
                 if p <= GetValue(low, i) then p else GetValue(low, i);
def depth = fold j = 1 to pivotOffset with q=low do
                 if q <= GetValue(low, j)  then q else GetValue(low, j);
# Calculate leftCup and offset
#def leftCupOffset = Bar - pivotOffset;
def handleLength = pivotOffset;
def cupLength = leftCupOffset - pivotOffset;
def priorLow = priorLL;
def leftCup  = HighestAll(InertiaAll(leftCupHH, 2));
def baseLow  = HighestAll(InertiaAll(leftCupLL, 2));
def pivot    = HighestAll(InertiaAll(PvtHH, 2));
def handlelow = HighestAll(InertiaAll(depth, 2));

def handleDepthPct     = (pivot - handlelow) / handlelow * 100;
def cupToHandleRatio   = cupLength / (cupLength + handleLength) * 100;
def pivotPctOffLeftCup = (pivot - leftCup) / leftCup * 100;
def setupGainPct = (leftCup - priorLow) / priorLow * 100;
def cupDepthPct  = (leftCup - baseLow) / leftCup * 100;
def midpointBase = (leftCup + baseLow) / 2;
def midpointHandle = (pivot + handlelow) / 2;

def r01 = currentClose >= 1;
def r02 = (currentClose >= 0.95 * movAvg);
def r03 = (pivotPctOffLeftCup <= 5);
def r04 = (pivotPctOffLeftCup >= -40);
def r05 = (leftCupOffset >= 25);
def r06 = (leftCupOffset <= cupLookback);
def r07 = (cupToHandleRatio >= 3);
def r08 = (setupGainPct >= 3);
def r09 = (cupDepthPct <= 60);
def r10 = (handleDepthPct <= 30);
def r11 = (midpointHandle >= midpointBase);

def totCond = r01 + r02 + r03 + r04 + r05 + r06 + r07 + r08 + r09 + r10 + r11;


def active;
def sigCond = totCond>=sens and totCond[1] < sens and active[1];
if leftCupHH!= leftCupHH[1] and !active[1] {
    active = yes;
    } else if sigCond {
    active = no;
   } else {
    active = active[1];
}
def break;
def breakSig;
def cnt;
if sigCond {
    cnt   = 0;
    break =  yes;
    breakSig = high;
    } else {
    cnt   = if cnt[1] > cupLookback then 0 else cnt[1] + 1;
    break = if low[1] > breakSig[1] then no else yes;
    breakSig = if !break or cnt == 0 then na else breakSig[1];
}
AddChartBubble(!break and break[1], low, "break", color.CYAN, no);

plot breakLine = if breakSig then breakSig else na;
breakLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
breakLine.SetDefaultColor(Color.YELLOW);


plot movAvgLine = if showMovAvgLine then movAvg else na;
movAvgLine.SetDefaultColor(Color.RED);

plot CupAndHandle = if  active and !active[1] then low else na;#cupAndHandleCondition;
CupAndHandle.SetLineWeight(2);
CupAndHandle.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
CupAndHandle.SetDefaultColor(Color.YELLOW);


#-- END of CODE
Wonderful and ambitious attempt here Bulusu building a cup and handle scan. And thanks Samar and Halcyonguy . Just tried this code in my scanner. I get an "exactly one plot expected" error. I know this is a basic question. I am not a coder and I'm new to thinkscript. What do I need to fix? Will read any thread you recommend. Commenting out different plots did not resolve the error code.
 
Wonderful and ambitious attempt here Bulusu building a cup and handle scan. And thanks Samar and Halcyonguy . Just tried this code in my scanner. I get an "exactly one plot expected" error. I know this is a basic question. I am not a coder and I'm new to thinkscript. What do I need to fix? Will read any thread you recommend. Commenting out different plots did not resolve the error code.


It sounds like you attempted to cut&paste the whole code into the scanner.

Follow the directions in this scan tutorial to alleviate your error:
https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/
 

New Indicator: Buy the Dip

Check out our Buy the Dip indicator and see how it can help you find profitable swing trading ideas. Scanner, watchlist columns, and add-ons are included.

Download the indicator

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
169 Online
Create Post

Similar threads

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.
Back
Top