// -- equity curve head and shoulders detection ----
once useHSPatterStop = 1
if useHSPatterStop then
// Variabls ------------------------
D = positionPerf // data = ie usually current trade performance
hsMinWidth = 4 // minimum shoulder-head width in bars
rightShoulderMinDepth = 0.5 // minimum % of left shoulder that right shoulder must retrace to for a valid setup
//-----------------------------------
maxD = max(maxD, D)
findL = (not hsLeft) and (not hsHead) and (d >= maxD) and (d > hsLeft)
restL = d > hsLeft and (barIndex < hsLeftIndex+round(hsMinWidth/2) or d > hsLeft*2)
findH = hsLeft and (not hsRight) and d > hsLeft //and d > hsHead
findH = findH and d > hsHead and barIndex > hsLeftIndex+hsMinWidth
findR = (not hsRight) and hsHead and hsLeft and (d >= hsLeft)
findR = findR and ( barIndex-hsHeadIndex >= hsMinWidth )
findR = findR and lowest[barIndex-hsHeadIndex](d) <= hsLeft-(hsLeft-lowest[barIndex-hsLeftIndex](d))*rightShoulderMinDepth
hsDone = hsRight and d <= hsLeft - lowest[barIndex-hsLeftIndex](d)
graph hsDone
if findL or restL then // We found possible left shoulder
hsLeft = d
hsLeftIndex = barIndex
hsHead = 0
hsRight = 0
elsif findH and not findR then // We found possible head
hsHead = d
hsHeadIndex = barIndex
elsif findR then // We found possible right shoulder
hsRight = d
elsif hsDone then // Pattern completed below left shoulder low
// INSERT YOUR H&S CONDITION HANDLER HERE
canExitMyTrade = 1 // for example
endif
if hsDone or (not onMarket) then // reset to clear HS pattern
hsLeft = 0
hsHead = 0
hsRight = 0
endif
endif