0% found this document useful (0 votes)
10 views6 pages

Order Block Detector for Trading

Uploaded by

icaro87mm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Order Block Detector for Trading

Uploaded by

icaro87mm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

var ob_box = array.

new_box(0)
var ob_lvl = array.new_line(0)

if [Link]
for i = 0 to ext_last-1
[Link](ob_box, [Link](na,na,na,na, xloc = xloc.bar_time, extend
= [Link], bgcolor = bg_css, border_color = [Link](border_css, 70)))
[Link](ob_lvl, [Link](na,na,na,na, xloc = xloc.bar_time,
extend = [Link], color = lvl_css, style = get_line_style(line_style), width =
line_width))

if [Link]
if [Link](ob_top) > 0
for i = 0 to [Link](ext_last-1, [Link](ob_top)-1)
get_box = [Link](ob_box, i)
get_lvl = [Link](ob_lvl, i)
box.set_lefttop(get_box, [Link](ob_left, i), [Link](ob_top,
i))
box.set_rightbottom(get_box, [Link](ob_left, i),
[Link](ob_btm, i))
line.set_xy1(get_lvl, [Link](ob_left, i), [Link](ob_avg, i))
line.set_xy2(get_lvl, [Link](ob_left, i)+1, [Link](ob_avg,
i))

// Order Block Detector Logic


var os = 0
var target_bull = 0.
var target_bear = 0.

n = bar_index
upper = [Link](length)
lower = [Link](length)

if mitigation == 'Close'
target_bull := [Link](close, length)
target_bear := [Link](close, length)
else
target_bull := lower
target_bear := upper

os := high[length] > upper ? 0 : low[length] < lower ? 1 : os[1]

phv = [Link](volume, length, length)

[bull_top, bull_btm, bull_avg, bull_left, bull_ob] = get_coordinates(phv and os ==


1, hl2[length], low[length], low[length])
[bear_top, bear_btm, bear_avg, bear_left, bear_ob] = get_coordinates(phv and os ==
0, high[length], hl2[length], high[length])

mitigated_bull = remove_mitigated(bull_top, bull_btm, bull_left, bull_avg,


target_bull, true)
mitigated_bear = remove_mitigated(bear_top, bear_btm, bear_left, bear_avg,
target_bear, false)

set_order_blocks(bull_top, bull_btm, bull_left, bull_avg, bull_ext_last,


bg_bull_css, bull_css, bull_avg_css)
set_order_blocks(bear_top, bear_btm, bear_left, bear_avg, bear_ext_last,
bg_bear_css, bear_css, bear_avg_css)
plot(bull_ob, 'Bull OB', bull_css, 2, plot.style_linebr, offset = -length)
plot(bear_ob, 'Bear OB', bear_css, 2, plot.style_linebr, offset = -length)

// EMA Calculations and Plotting


ema9 = [Link](src_ema, len1)
ema20 = [Link](src_ema, len2)

plot(ema9, title="9 EMA", linewidth=2, color=#0000FF)


plot(ema20, title="20 EMA", linewidth=2, color=#11DCBF)

// UNTESTED

temp0 = [Link](title='••••••••••••••••••• Fractals ••••••••••••••••••••••',


defval=false)
showFractals = [Link](title='Show Fractal Points ?', defval=false)
filterFractal = [Link](title='Filter 3/5 bar fractal', defval='3',
options=['3', '5'])

temp1 = [Link](title='••••••••••••••••••• Orderblocks •••••••••••••••••••',


defval=false)
findObType = [Link](title='Find OB after fractal break of close/HL',
defval='Close', options=['Close', 'HL'])
filterFvgs = [Link](title='Filter only OB that follow with FVG ?', defval=true)
fvgDistance = [Link](3, title='Max bars between the OB and FVG', minval=1,
maxval=6)
lineHeight = [Link](title='Line Height', defval='Body', options=['Body',
'Wick'])
delLines = [Link](title='Delete lines after fill ?', defval=true)

temp3 = [Link](title='•••••••••••••••••••• Styles ••••••••••••••••••••••••',


defval=false)
lines_style = [Link](title='Lines style', defval='Solid', options=['Solid',
'Dashed', 'Dotted'])
line_length = [Link](5, 'Length of lines', minval=1, maxval=100)
lineStyle = lines_style == 'Solid' ? line.style_solid : lines_style == 'Dashed' ?
line.style_dashed : line.style_dotted
linesWidth = [Link](2, 'Lines Width ?', minval=1, maxval=4)
bear_line_color = [Link]([Link], 'Bear OB Line color')
bull_line_color = [Link]([Link], 'Bull OB Line color')

// -------------------- FUNCTIONS --------------------


bullishImb(i=0) => close[i+1] > high[i+2] and low[i] > high[i+2]
bearishImb(i=0) => close[i+1] < low[i+2] and high[i] < low[i+2]

// Fractals
isRegularFractal(mode) =>
ret = mode == 'Buy' ? high[0] < high[1] and (high[2] < high[1] or high[2] ==
high[1] and high[3] < high[2]) : mode == 'Sell' ? low[0] > low[1] and (low[2] >
low[1] or low[2] == low[1] and low[3] > low[2]) : false
ret

isBWFractal(mode) =>
ret = mode == 'Buy' ? high[0] < high[2] and high[1] < high[2] and high[3] <
high[2] and high[4] < high[2] : mode == 'Sell' ? low[0] > low[2] and low[1] >
low[2] and low[3] > low[2] and low[4] > low[2] : false
ret
isFractalHigh() =>
filterFractal == '3' ? isRegularFractal('Buy') : isBWFractal('Buy')

isFractalLow() =>
filterFractal == '3' ? isRegularFractal('Sell') : isBWFractal('Sell')

resolutionInMinutes() =>
resInMinutes = [Link] * ([Link] ? 1. / 60 :
[Link] ? 1. : [Link] ? 60. * 24 : [Link] ? 60.
* 24 * 7 : [Link] ? 60. * 24 * 30.4375 : na)
resInMinutes

f_timeFrom(_from, length, _units, i) =>


var int _timeFrom = na
_unit = str.replace_all(_units, 's', '')
_timeFrom := int(time[i] + resolutionInMinutes() * 60 * 1000 * length)
_timeFrom

// -------------------- FUNCTIONS --------------------

// -------------------- Fractals --------------------


var float fractal_high_val = na
var float fractal_low_val = na

var fractal_highs = array.new_float(0) // array of high fractal values


var fractal_high_times = array.new_int(0) // array of high fractal times
var fractal_lows = array.new_float(0) // array of low fractal values
var fractal_low_times = array.new_int(0) // array or low fractal times

// Check if fractal and add it to array


if isFractalHigh()
if filterFractal == '3'
[Link](fractal_highs, high[1])
[Link](fractal_high_times, time[1])
fractal_high_val := high[1]
else
[Link](fractal_highs, high[2])
[Link](fractal_high_times, time[2])
fractal_high_val := high[2]

if isFractalLow()
if filterFractal == '3'
[Link](fractal_lows, low[1])
[Link](fractal_low_times, time[1])
fractal_low_val := low[1]
else
[Link](fractal_lows, low[2])
[Link](fractal_low_times, time[2])
fractal_low_val := low[2]
// -------------------- Fractals --------------------

var bars_back = 500

// -------------------- Orderblocks --------------------


var line1 = array.new_line()
var line2 = array.new_line()
var line3 = array.new_line()
var line4 = array.new_line()

var label1 = array.new_label()


var label2 = array.new_label()

// Bearish loop
if [Link](fractal_lows) > 0
for i = [Link](fractal_lows) - 1 to 0
if (findObType == 'Close' ? close : low) < [Link](fractal_lows, i)
idx = 0
max = low //current low
gapIndex = 0

for k = 0 to bars_back
bearishGap = (close[k+1] < low[k+2]) and (high[k] < low[k+2])

//stop loop if reached time limit


if time[k] < [Link](fractal_low_times, i)
break

//Get all bullish candles in range


if close[k] > open[k] and high[k] > max
idx := k
max := high[k]

if bearishGap and high[k] > max


gapIndex := k+2

_filterFvg = filterFvgs ? gapIndex > 0 and idx - gapIndex >= 0 and idx
- gapIndex <= fvgDistance : true
// Line on OB
if idx != 0 and _filterFvg
// [Link](bar_index, high, [Link](idx) + "\n" +
[Link](gapIndex))
TimeTo = f_timeFrom('bar', line_length, 'chart', idx)
loc = lineHeight == 'Body' ? open[idx] : low[idx]

[Link](line1, [Link](x1=time[idx], y1=high[idx], x2=TimeTo,


y2=high[idx], xloc=xloc.bar_time, style=lineStyle, color=bear_line_color,
width=linesWidth))
[Link](line2, [Link](x1=time[idx], y1=loc, x2=TimeTo, y2=loc,
xloc=xloc.bar_time, style=lineStyle, color=bear_line_color, width=linesWidth))

[Link](fractal_lows, i)
[Link](fractal_low_times, i)

// Bullish loop
if [Link](fractal_highs) > 0
for i = [Link](fractal_highs) - 1 to 0
if (findObType == 'Close' ? close : high) > [Link](fractal_highs, i)
idx = 0
min = low
gapIndex = 0

for k = 0 to bars_back
bullishGap = (close[k+1] > high[k+2]) and (low[k] > high[k+2])

// Stop the loop once it reaches the last fractal high


if time[k] < [Link](fractal_high_times, i)
break

// if bearish candle
if close[k] < open[k] and low[k] < min
idx := k
min := low[k]

if bullishGap
gapIndex := k+2

_filterFvg = filterFvgs ? gapIndex > 0 and idx - gapIndex >= 0 and idx
- gapIndex <= fvgDistance : true
// Line on OB
if idx != 0 and _filterFvg
// [Link](bar_index, high, [Link](idx) + "\n" +
[Link](gapIndex))
TimeTo = f_timeFrom('bar', line_length, 'chart', idx)
loc = lineHeight == 'Body' ? open[idx] : high[idx]

[Link](line3, [Link](x1=time[idx], y1=low[idx], x2=TimeTo,


y2=low[idx], xloc=xloc.bar_time, style=lineStyle, color=bull_line_color,
width=linesWidth))
[Link](line4, [Link](x1=time[idx], y1=loc, x2=TimeTo, y2=loc,
xloc=xloc.bar_time, style=lineStyle, color=bull_line_color, width=linesWidth))

[Link](fractal_highs, i)
[Link](fractal_high_times, i)

// -------------------- Orderblocks --------------------

// Delete Lines/Labels
if [Link](line1) > 0
var int i = [Link](line1) - 1
while i >= 0
if high >= line.get_y1([Link](line1, i)) and high >=
line.get_y1([Link](line2, i))
if delLines
[Link]([Link](line1, i))
[Link]([Link](line2, i))
//[Link]([Link](label1, i))
[Link](line1, i)
[Link](line2, i)
//[Link](label1,i)
i -= 1

if [Link](line3) > 0
var int j = [Link](line3) - 1
while j >= 0
if low <= line.get_y1([Link](line3, j)) and low <=
line.get_y1([Link](line4, j))
if delLines
[Link]([Link](line3, j))
[Link]([Link](line4, j))
//[Link]([Link](label2, j))
[Link](line3, j)
[Link](line4, j)
//[Link](label2,j)
j -= 1

//Plot fractal points


plotshape(showFractals and isFractalHigh(), title='Fractal High',
style=[Link], location=[Link], color=[Link]([Link],
0), offset=filterFractal == '3' ? -1 : -2, size=[Link])
plotshape(showFractals and isFractalLow(), title='Fractal Low',
style=[Link], location=[Link], color=[Link]([Link], 0),
offset=filterFractal == '3' ? -1 : -2, size=[Link])
// Order Block Detector Functions
get_line_style(style) =>
switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted

get_coordinates(condition, top, btm, ob_val) =>


var ob_top = array.new_float(0)
var ob_btm = array.new_float(0)
var ob_avg = array.new_float(0)
var ob_left = array.new_int(0)

float ob = na

if condition
avg = [Link](top, btm)
[Link](ob_top, top)
[Link](ob_btm, btm)
[Link](ob_avg, avg)
[Link](ob_left, time[length])
ob := ob_val

[ob_top, ob_btm, ob_avg, ob_left, ob]

remove_mitigated(ob_top, ob_btm, ob_left, ob_avg, target, bull) =>


mitigated = false
target_array = bull ? ob_btm : ob_top

for element in target_array


idx = [Link](target_array, element)
if (bull ? target < element : target > element)
mitigated := true
[Link](ob_top, idx)
[Link](ob_btm, idx)
[Link](ob_avg, idx)
[Link](ob_left, idx)

mitigated

Common questions

Powered by AI

The script identifies potential trading opportunities by using fractals, which are specific price patterns that indicate potential reversals. It defines fractals based on whether the filter is set to '3' or '5', determining regular or BW fractals . Fractals help in identifying potential order block areas by checking if the current price action surpasses fractal highs or lows, and accordingly, it sets order blocks. Bullish and bearish loops further use these fractals to detect gaps in price action, helping to draw projected lines on the chart that can act as future resistance or support levels .

Bearish gaps are identified when the closing price of a bar is less than the low of a bar two periods earlier, and the high of a bar is less than the low two periods ago . Conversely, bullish gaps occur when the closing price is greater than the high from two periods ago, and the low is greater than the high from two periods ago . These gaps are crucial for setting up targets for potential order blocks, indicating a departure in price direction and highlighting areas that traders may watch for reversals or trend continuations .

The script calculates chart time in minutes using the 'resolutionInMinutes' function, which considers the timeframe's multiplier and adjusts based on whether it is set to seconds, minutes, daily, weekly, or monthly . This accurate conversion ensures timing precision when locating fractals and plotting lines, which is crucial for order block identification. Precise time calculations prevent plotting errors, thus enhancing the reliability of order block setups and minimizing potential miscalculations that could lead to incorrect trading decisions .

The 'remove_mitigated' function refines the order block strategy by filtering out order blocks that have already been mitigated, i.e., instances where the price has surpassed target levels, marking those order blocks as fulfilled . Its implementation ensures that only active order blocks, which may influence future price movement, are retained. This prevents false signals generated from old or irrelevant blocks, optimizing the strategy by maintaining the focus on current market dynamics and thus enhancing decision-making accuracy .

Different line styles are used in the script—such as solid, dashed, or dotted lines—to visually distinguish between various types of data like order block borders or potential support and resistance levels . Customizing line appearances helps users quickly interpret order block data by providing clear visual indicators that reduce cognitive load when analyzing complex chart patterns. This customization empowers users to adapt charts according to personal strategies or preferences, thereby facilitating quicker decision-making and improving user-friendliness .

The 'fvgDistance' sets a maximum bar count allowing the script to determine the spatial relationship between identified order blocks and subsequent fair value gaps . This parameter ensures that the blocks and gaps are closely correlated, preventing the association of potentially irrelevant price action with the identified blocks. By enforcing a realistic maximum bar distance, the strategy is refined to consider only proximate gaps that can logically follow order blocks, thus aiding in more accurate setup identifications and filtering out noise .

The 'mitigation' condition determines whether the target levels for bullish and bearish scenarios are calculated using the 'Close' price or the highest/lowest price within a specified lookback period. If 'mitigation' is set to 'Close', the target for bulls becomes the lowest close within the period, and for bears, the highest close . This condition affects the strategy by targeting areas likely to see price reversals, thereby influencing the removal of mitigated order blocks and refining where potential buying or selling pressure might occur .

The relevance of filtering order blocks followed by fair value gaps (FVGs) lies in reinforcing valid price action signals with areas of imbalance, where price discrepancies offer high-probability trading opportunities. By ensuring order blocks are followed by FVGs, the script refines block identification, eliminating less reliable setups and focusing on those with confirmed momentum shifts . This filtering process affects trading accuracy by improving the strength and reliability of trades initiated by these order blocks, leading to more consistent outcomes .

Pivot highs and lows are critical for constructing order blocks as they mark significant local price extremes. The script uses 'ta.pivothigh' and a similar method for lows to identify these points, which then serve as references for the top and bottom of potential order blocks . This incorporation of pivot points into the trading logic offers strategic advantages by anchoring order blocks to significant price points, thereby increasing the likelihood of capturing pivotal market turning points and enhancing trade accuracy .

The script calculates two EMAs, a 9-period EMA and a 20-period EMA, using a source input for moving averages . These exponential moving averages help smooth out price data, thus identifying the trend direction more accurately and assisting in validating the strength of any order block detections. The crossover of these EMAs can provide additional signals of potential entry or exit points, enhancing the predictive capability by confirming order block signals within the broader trend context .

You might also like