-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathswing_failure_detection.pinescript
More file actions
371 lines (325 loc) · 19.2 KB
/
swing_failure_detection.pinescript
File metadata and controls
371 lines (325 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// © jyang98il
// @version=4
maxBarsBack = 4999 // Maximum: 4999.
strategy("SFPHiLoBars", "SFPHiLoBars", true, calc_on_every_tick = true, max_bars_back = maxBarsBack, max_lines_count = 500, max_labels_count = 500)
// ———————————————————— Constants
// {
CS0 = "Lime/Red", CS1 = "Aqua/Pink", CS2 = "Coral/Violet"
TF0 = "None", TF1 = "Auto-Steps (15min, 60min, 4H, 1D, 3D, 1W, 1M, 12M)", TF2 = "Multiple Of Current TF", TF3 = "Fixed TF"
TX0 = "Same as Color Theme", TX1 = "Neutral"
MS0 = "None", MS1 = "Running value", MS2 = "Last value", MS3 = "Both"
MM0 = "Mean", MM1 = "Median"
TB0 = "Varying", TB1 = "Always high"
MD0 = "Both", MD1 = "Longs Only", MD2 = "Shorts Only"
// }
// ———————————————————— Inputs
// {
_2 = input(true, "═══════════ Display ════════════")
i_qtyPivots = input(3, "Quantity of saved pivots", minval = 1, maxval = 249)
i_numHours = input(12, "# of bars to restrict the Swing Failure Pattern ")
i_showAll = input(false, "Show all Pivot points?")
i_highlightLast = input(true, "Highlight last pivots")
i_showPrices = input(true, "Show Prices")
i_textColor = input(TX0, " Text Color", options = [TX0, TX1])
i_textBrightness = input(TB0, " Text Brightness", options = [TB0, TB1])
i_textSize = input(3, " Text Size", minval = 1, maxval = 5)
i_htfShow = input(true, "Show HTF Used")
i_offsetLabels = input(3, " Text Offset")
_4 = input(true, "═════════ HTF Selection ══════════")
i_htfType = input(TF3, "Higher Timeframe Selection", options = [TF0, TF1, TF2, TF3])
i_htfType2 = input(3., " 2. Multiple of Current TF", minval = 1)
i_htfType3 = input("240", " 3. Fixed TF", type = input.resolution)
i_htfRepaints = input(false, "Repainting HTF")
_8 = input(true, "═══════════ Options ════════════")
i_srcH = input(high, "Hi Pivots Source")
i_srcL = input(low, "Lo Pivots Source")
i_legLeft = input(5, "Left Pivot Leg (bars)", minval = 1)
i_legRight = input(5, "Right Pivot Leg (bars)", minval = 1)
i_RangePct = input(0.10, "Range to allow the box to be drawn")
// HTF is being used.
var htfOn = i_htfType != TF0
// Price text size.
var labelSize = i_textSize == 1 ? size.tiny : i_textSize == 2 ? size.small : i_textSize == 3 ? size.normal : i_textSize == 4 ? size.large : size.huge
// }
// ———————————————————— Constants
i_lineThicknessH = 1
i_lineBrightnessH = 4
i_lineThicknessL = 1
i_lineBrightnessL = 4
i_colorScheme = CS2
arr_max_idx = 2*i_qtyPivots - 1
// ———————————————————— Time Functions
// {
// ————— Generate colors for pivot lines and text using user-selected color scheme and brightness levels.
f_cGreen(_b) => _b == 8 ? #00FF00ff : _b == 7 ? #00FF00d0 : _b == 6 ? #00FF00b0 : _b == 5 ? #00FF0090 : _b == 4 ? #00FF0070 : _b == 3 ? #00FF0050 : _b == 2 ? #00FF0020 : _b == 1 ? #00FF0010 : na
f_cAqua(_b) => _b == 8 ? #00C0FFff : _b == 7 ? #00C0FFd0 : _b == 6 ? #00C0FFb0 : _b == 5 ? #00C0FF90 : _b == 4 ? #00C0FF70 : _b == 3 ? #00C0FF50 : _b == 2 ? #00C0FF20 : _b == 1 ? #00C0FF10 : na
f_cOrange(_b) => _b == 8 ? #FF8080ff : _b == 7 ? #FF8080d0 : _b == 6 ? #FF8080b0 : _b == 5 ? #FF808090 : _b == 4 ? #FF808070 : _b == 3 ? #FF808050 : _b == 2 ? #FF808020 : _b == 1 ? #FF808018 : na
f_cRed(_b) => _b == 8 ? #FF0000ff : _b == 7 ? #FF0000d0 : _b == 6 ? #FF0000b0 : _b == 5 ? #FF000090 : _b == 4 ? #FF000070 : _b == 3 ? #FF000050 : _b == 2 ? #FF000020 : _b == 1 ? #FF000010 : na
f_cPink(_b) => _b == 8 ? #FF0080ff : _b == 7 ? #FF0080d0 : _b == 6 ? #FF0080b0 : _b == 5 ? #FF008090 : _b == 4 ? #FF008070 : _b == 3 ? #FF008050 : _b == 2 ? #FF008020 : _b == 1 ? #FF008010 : na
f_cViolet(_b) => _b == 8 ? #AA00FFff : _b == 7 ? #AA00FFd0 : _b == 6 ? #AA00FFb0 : _b == 5 ? #AA00FF90 : _b == 4 ? #AA00FF70 : _b == 3 ? #AA00FF50 : _b == 2 ? #AA00FF38 : _b == 1 ? #AA00FF20 : na
f_colorH(_b) => i_colorScheme == CS0 ? f_cGreen(_b) : i_colorScheme == CS1 ? f_cAqua(_b) : f_cOrange(_b)
f_colorL(_b) => i_colorScheme == CS0 ? f_cRed(_b) : i_colorScheme == CS1 ? f_cPink(_b) : f_cViolet(_b)
var colorPH = f_colorH(i_lineBrightnessH)
var colorPL = f_colorL(i_lineBrightnessL)
var colorTextPH = i_textBrightness == TB0 ? i_textColor == TX0 ? colorPH : color.gray : i_textColor == TX0 ? f_colorH(5) : color.new(color.gray, 0)
var colorTextPL = i_textBrightness == TB0 ? i_textColor == TX0 ? colorPL : color.gray : i_textColor == TX0 ? f_colorL(5) : color.new(color.gray, 0)
// ————— Round prices to tick.
f_roundToTick( _price) => round(_price / syminfo.mintick) * syminfo.mintick
// ————— Produces a string format usable with `tostring()` to restrict precision to ticks.
// • Note that `tostring()` will also round the value.
f_tickFormat() =>
_s = tostring(syminfo.mintick)
_s := str.replace_all(_s, "25", "00")
_s := str.replace_all(_s, "5", "0")
_s := str.replace_all(_s, "1", "0")
// ————— Queues a new element in an array and de-queues its first element.
f_qDq(_array, _val) =>
array.push(_array, _val)
array.shift(_array)
// ————— Lookback to find chart bar where pivot occured.
f_offsetToP(_src, _pivotPrice, _maxBack) =>
int _offset = na
float _delta = 10e10
if not na(_pivotPrice)
// There is a pivot price to check; loop back in limited number of bars for closest level matching pivot.
for _i = 1 to _maxBack
_thisDelta = abs(_src[_i] - _pivotPrice)
if _thisDelta < _delta
// Closer price found; save its offset.
_delta := _thisDelta
_offset := _i
_offset
// —————————— PineCoders MTF Selection Framework functions
// ————— Converts current "timeframe.multiplier" plus the TF into minutes of type float.
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 10080. :
timeframe.ismonthly ? 43800. : na)
// ————— Returns resolution of _resolution period in minutes.
f_tfResInMinutes(_resolution) =>
// _resolution: resolution of any TF (in "timeframe.period" string format).
security(syminfo.tickerid, _resolution, f_resInMinutes())
// ————— Given current resolution, returns next step of HTF.
f_resNextStep(_res) =>
// _res: current TF in fractional minutes.
_res <= 1 ? "15" :
_res <= 5 ? "60" :
_res <= 30 ? "240" :
_res <= 60 ? "1D" :
_res <= 360 ? "3D" :
_res <= 1440 ? "1W" :
_res <= 10080 ? "1M" : "12M"
// ————— Returns a multiple of current resolution as a string in "timeframe.period" format usable with "security()".
f_multipleOfRes(_res, _mult) =>
// _res: current resolution in minutes, in the fractional format supplied by f_resInMinutes() companion function.
// _mult: Multiple of current TF to be calculated.
// Convert current float TF in minutes to target string TF in "timeframe.period" format.
_targetResInMin = _res * max(_mult, 1)
_targetResInMin <= 0.083 ? "5S" :
_targetResInMin <= 0.251 ? "15S" :
_targetResInMin <= 0.501 ? "30S" :
_targetResInMin <= 1440 ? tostring(round(_targetResInMin)) :
_targetResInMin <= 43800 ? tostring(round(min(_targetResInMin / 1440, 365))) + "D" :
tostring(round(min(_targetResInMin / 43800, 12))) + "M"
// ————— Print a label at end of chart.
f_htfLabel(_txt, _y, _color, _offsetLabels) =>
_t = int(time + (f_resInMinutes() * _offsetLabels * 60000))
var _lbl = label.new(_t, _y, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large)
if barstate.islast
label.set_xy(_lbl, _t, _y)
label.set_text(_lbl, _txt)
label.set_textcolor(_lbl, _color)
// }
// ———————————————————— Pivot Functions
// Function returns true when a cross is detected between the close and one of the pivots in the last n displayed.
f_pivotCross(_direction, _pivots) =>
// _direction: direction of the cross to detect ("over" or "under").
// _pivots : array of pivot prices to be tested against.
_return = false
_arr_max_idx = array.size(_pivots)
for _i = _arr_max_idx - 1 to 0
_pivotPrice = array.get(_pivots, _i)
if _direction == "over" and close[1] < _pivotPrice and close > _pivotPrice
_return := true
break
else if _direction == "under" and close[1] > _pivotPrice and close < _pivotPrice
_return := true
break
_return
f_is_falling() =>
// hl2 <= hl2[2]
// avg(hl2, hl2[1]) <= avg(hl2[2], hl2[3])
// true
avg(hlc3, hlc3[1]) <= avg(hlc3[2], hlc3[3])
f_is_rising() =>
// hl2 >= hl2[2]
// avg(hl2, hl2[1]) >= avg(hl2[2], hl2[3])
// true
avg(hlc3, hlc3[1]) >= avg(hlc3[2], hlc3[3])
// Function returns true when a cross is detected between the close and one of the pivots in the last n displayed.
f_pivotCrossBoth(_pivots) =>
// _direction: direction of the cross to detect ("over" or "under").
// _pivots : array of pivot prices to be tested against.
_return = false
_arr_max_idx = array.size(_pivots)
for _i = _arr_max_idx - 1 to 0
_pivotPrice = array.get(_pivots, _i)
if (close[1] < _pivotPrice and close > _pivotPrice) or (close[1] > _pivotPrice and close < _pivotPrice)
_return := true
break
_return
// if array.size(_sorted_pivots) > 0 and _barstate
// _arr_min_idx = 0
// _lowestPiv = array.get(_sorted_pivots, _arr_min_idx)
// _sfp_found = _low < _lowestPiv and _close > _lowestPiv
// _sfp_pivot = _sfp_found ? _lowestPiv : na
f_detectSFPLow(_sorted_pivots, _low, _close, _barstate, _bars_in_range) =>
_sfp_found = false
float _sfp_pivot = na
if array.size(_sorted_pivots) > 0 and _barstate and _bars_in_range > i_numHours
_arr_min_idx = 0
_lowestPiv = array.get(_sorted_pivots, _arr_min_idx)
_sfp_found := (_low < _lowestPiv and _close > _lowestPiv) and f_is_falling()
_sfp_pivot := _sfp_found ? _lowestPiv : na
[_sfp_found, _sfp_pivot]
// if array.size(_sorted_pivots) > 0 and _barstate
// _highestPiv = array.get(_sorted_pivots, _arr_max_idx)
// _sfp_found = _high > _highestPiv and _close < _highestPiv
// _sfp_pivot = _sfp_found ? _highestPiv : na
// need to check against the highest pivot in the sorted range.
f_detectSFPHigh(_sorted_pivots, _high, _close, _barstate, _bars_in_range) =>
_arr_max_idx = array.size(_sorted_pivots) - 1
_sfp_found = false
float _sfp_pivot = na
if array.size(_sorted_pivots) > 0 and _barstate and _bars_in_range > i_numHours
_highestPiv = array.get(_sorted_pivots, _arr_max_idx)
_sfp_found := (_high > _highestPiv and _close < _highestPiv) and f_is_rising()
_sfp_pivot := _sfp_found ? _highestPiv : na
[_sfp_found, _sfp_pivot]
// ———————————————————— Calcs
// {
// Arrays holding pivot line id's, label id's and prices.
i_qtyPivots := int(i_qtyPivots)
var pHiLines = array.new_line(i_qtyPivots)
var pLoLines = array.new_line(i_qtyPivots)
var pHiLabels = array.new_label(i_qtyPivots)
var pLoLabels = array.new_label(i_qtyPivots)
var pHiPrices = array.new_float(i_qtyPivots)
var pLoPrices = array.new_float(i_qtyPivots)
var pHiSorted = array.new_float()
var pLoSorted = array.new_float()
// ————— HTF calcs
// Get current resolution in float minutes.
var resInMinutes = f_resInMinutes()
// Get HTF from user-defined mode.
var htf = i_htfType == TF0 ? timeframe.period : i_htfType == TF1 ? f_resNextStep(resInMinutes) : i_htfType == TF2 ? f_multipleOfRes(resInMinutes, i_htfType2) : i_htfType3
// Vertical position of label.
labelY = sma(high + 3 * tr, 10)[1]
// If current res is not lower than HTF, print warning at right of chart.
if htfOn and resInMinutes >= f_tfResInMinutes(htf)
f_htfLabel("Chart\nresolution\nmust be < " + htf, labelY, color.silver, i_offsetLabels)
else
// Show calculated HTF when needed.
if htfOn and i_htfShow
f_htfLabel(htf, labelY, color.silver, i_offsetLabels)
// ————— Number of chart bars back contained in one HTF bar.
chartBarsInHtf = int(f_tfResInMinutes(htf) / resInMinutes)
// ————— Starting point offset where we can begin searching for a pivot.
chartBarsOffset = int(((i_legRight) * chartBarsInHtf) + (i_htfRepaints ? 0 : 1))
//
// ————— Pivot calcs
//
pH = pivothigh(i_srcH, i_legLeft, i_legRight)
pL = pivotlow( i_srcL, i_legLeft, i_legRight)
// get HTF pivots
htfPH = not htfOn ? pH : i_htfRepaints ? security(syminfo.tickerid, htf, pH) : security(syminfo.tickerid, htf, pH[1], lookahead = barmerge.lookahead_on)
htfPL = not htfOn ? pL : i_htfRepaints ? security(syminfo.tickerid, htf, pL) : security(syminfo.tickerid, htf, pL[1], lookahead = barmerge.lookahead_on)
newPH = na(htfPH[1]) and not(na(htfPH))
newPL = na(htfPL[1]) and not(na(htfPL))
// In case a pivot is found, find the offset to the bar matching its level [these functions need to be called on each bar]. Only send pivot value when one is found, so loop isn't executed on every bar.
offsetToPH = f_offsetToP(i_srcH, newPH ? htfPH : na, min(maxBarsBack, max(30, chartBarsOffset + chartBarsInHtf + 1)))
offsetToPL = f_offsetToP(i_srcL, newPL ? htfPL : na, min(maxBarsBack, max(30, chartBarsOffset + chartBarsInHtf + 1)))
// Pivot values and line/label ids (each pivot uses a line and, if user-selected, a label for the price).
line linePH = na
line linePL = na
// —————————— Main block where we decide first if we can run the rest of the script.
if chartBarsOffset > maxBarsBack
// Dilation of HTF contains too many bars. Would cause referencing errors; can't run logic.
f_htfLabel("Can't run indicator.\nGap between chart res\nand HTF is too large.\n" + tostring(chartBarsOffset, "(#)"), labelY, f_cRed(8), i_offsetLabels)
float(na)
else
// ————— If a new pivot is found, draw a new line and label at the offset found.
if newPH
// Draw new pivot line.
linePH := i_showAll ? line.new(bar_index - offsetToPH, htfPH, bar_index, htfPH, xloc.bar_index, extend.right, colorPH, line.style_solid, i_lineThicknessH) : na
// Queue new pivot line and delete de-queued one.
line.delete(f_qDq(pHiLines, linePH))
// Queue new pivot's price.
f_qDq(pHiPrices, htfPH)
// Display price if needed.
if i_showPrices
// Draw new label.
labelPH = label.new(bar_index - offsetToPH, htfPH, " " + tostring(f_roundToTick(htfPH), f_tickFormat()), xloc.bar_index, yloc.price, #00000000, label.style_none, colorTextPH, labelSize)
// Queue new price label and delete de-queued one.
label.delete(f_qDq(pHiLabels, labelPH))
if newPL
linePL := i_showAll ? line.new(bar_index - offsetToPL, htfPL, bar_index, htfPL, xloc.bar_index, extend.right, colorPL, line.style_solid, i_lineThicknessL) : na
line.delete(f_qDq(pLoLines, linePL))
f_qDq(pLoPrices, htfPL)
if i_showPrices
labelPL = label.new(bar_index - offsetToPL, htfPL, " " + tostring(f_roundToTick(htfPL), f_tickFormat()), xloc.bar_index, yloc.price, #00000000, label.style_none, colorTextPL, labelSize)
label.delete(f_qDq(pLoLabels, labelPL))
// ————— Make last hi and lo pivot lines thicker, if required.
if barstate.islast and i_highlightLast and i_showAll
line.set_width(array.get(pHiLines, i_qtyPivots - 1), i_lineThicknessH * 4)
line.set_width(array.get(pLoLines, i_qtyPivots - 1), i_lineThicknessL * 4)
float(na)
// Sort both the LoPrices and the HiPrices
var float highestHiPiv = na
var float lowestLoPiv = na
if newPH
array.clear(pHiSorted)
array.concat(pHiSorted, pHiPrices)
array.sort(pHiSorted)
// Get the highest pivot which is the last sorted val
highestHiPiv := array.get(pHiSorted, i_qtyPivots - 1)
if newPL
array.clear(pLoSorted)
array.concat(pLoSorted, pLoPrices)
array.sort(pLoSorted)
// Get the lowest pivot which is the first idx
lowestLoPiv := array.get(pLoSorted, 0)
price_above_hiPiv = close > highestHiPiv
price_below_loPiv = close < lowestLoPiv
bars_since_hiPiv = barssince(price_above_hiPiv)
bars_since_loPiv = barssince(price_below_loPiv)
// have the sorted pivots
[sfp_low_found, sfp_low_pivot] = f_detectSFPLow(pLoSorted, low, close, barstate.isconfirmed, bars_since_loPiv)
[sfp_high_found, sfp_high_pivot] = f_detectSFPHigh(pHiSorted, high, close, barstate.isconfirmed, bars_since_hiPiv)
// if we found the SFP, then we need to determine the next bar is the right color..
if sfp_low_found[1] and barstate.isconfirmed and sfp_low_pivot[1] > 0
// build a label if it's green
is_green = close > open
// label.new(bar_index - offsetToPH, htfPH, " " + tostring(f_roundToTick(htfPH), f_tickFormat()), xloc.bar_index, yloc.price, #00000000, label.style_none, colorTextPH, labelSize)
sfp_low_label = is_green ? label.new(bar_index - 1, sfp_low_pivot[1]*.99, "SFPL", xloc.bar_index, yloc.price, color.orange, style=label.style_label_up, size=size.small) : na
if is_green
alert_msg = "Swing Failure to Upside detected on " + syminfo.tickerid + "at price: " + tostring(f_roundToTick(sfp_low_pivot[1]), f_tickFormat())
alert(alert_msg)
// clear the sfp_low_found
sfp_low_found := false
plot(sfp_low_found ? sfp_low_pivot : na, title = "Low Pivot Found", color=color.orange, transp=100)
if sfp_high_found[1] and barstate.isconfirmed and sfp_high_pivot[1] > 0
is_red = close < open
sfp_high_label = is_red ? label.new(bar_index - 1, sfp_high_pivot[1]*1.01, "SFPH", xloc.bar_index, yloc.price, color.purple, style=label.style_label_down, size=size.small) : na
if is_red
alert_msg = "Swing Failure to Downside detected on " + syminfo.tickerid + "at price: " + tostring(f_roundToTick(sfp_high_pivot[1]), f_tickFormat())
alert(alert_msg)
sfp_high_found := false
plot(sfp_high_found ? sfp_high_pivot : na, title = "High Pivot Found", color = color.purple, transp=100)
lowestPivLo = array.size(pLoSorted) > 0 ? array.get(pLoSorted, 0) : na
highestPivHi = array.size(pHiSorted) > 0 ? array.get(pHiSorted, array.size(pHiSorted)-1) : na
plot(lowestPivLo, title = "Lowest Piv Lo", color=color.purple, transp=100)
plot(highestPivHi, title = "Highest Piv Hi", color=color.orange, transp=100)