PROTECTED SOURCE SCRIPT

mohvip

85
//version=5
indicator(" Fmfm250 ", overlay = true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)

// User inputs
prd = input.int(defval=30, title=' Period for Pivot Points', minval=1, maxval=50)
max_num_of_pivots = input.int(defval=6, title=' Maximum Number of Pivots', minval=5, maxval=10)
max_lines = input.int(defval=1, title=' Maximum number of trend lines', minval=1, maxval=10)
show_lines = input.bool(defval=true, title=' Show trend lines')
show_pivots = input.bool(defval=false, title=' Show Pivot Points')
sup_line_color = input(defval = color.lime, title = "Colors", inline = "tcol")
res_line_color = input(defval = color.red, title = "", inline = "tcol")

float ph = ta.pivothigh(high, prd, prd)
float pl = ta.pivotlow(low, prd, prd)

plotshape(ph and show_pivots, style=shape.triangledown, location=location.abovebar, offset=-prd, size=size.tiny)
plotshape(pl and show_pivots, style=shape.triangleup, location=location.belowbar, offset=-prd, size=size.tiny)

// Creating array of pivots
var pivots_high = array.new_float(0)
var pivots_low = array.new_float(0)

var high_ind = array.new_int(0)
var low_ind = array.new_int(0)

if ph
array.push(pivots_high, ph)
array.push(high_ind, bar_index - prd)
if array.size(pivots_high) > max_num_of_pivots // limit the array size
array.shift(pivots_high)
array.shift(high_ind)

if pl
array.push(pivots_low, pl)
array.push(low_ind, bar_index - prd)
if array.size(pivots_low) > max_num_of_pivots // limit the array size
array.shift(pivots_low)
array.shift(low_ind)

// Create arrays to store slopes and lines
var res_lines = array.new_line()
var res_slopes = array.new_float()

len_lines = array.size(res_lines)

if (len_lines >= 1)
for ind = 0 to len_lines - 1
to_delete = array.pop(res_lines)
array.pop(res_slopes)
line.delete(to_delete)


count_slope(ph1, ph2, pos1, pos2) => (ph2 - ph1) / (pos2 - pos1)


if array.size(pivots_high) == max_num_of_pivots
index_of_biggest_slope = 0
for ind1 = 0 to max_num_of_pivots - 2
for ind2 = ind1 + 1 to max_num_of_pivots - 1
p1 = array.get(pivots_high, ind1)
p2 = array.get(pivots_high, ind2)
pos1 = array.get(high_ind, ind1)
pos2 = array.get(high_ind, ind2)
k = count_slope(p1, p2, pos1, pos2)
b = p1 - k * pos1

ok = true

if ind2 - ind1 >= 1 and ok
for ind3 = ind1 + 1 to ind2 - 1
p3 = array.get(pivots_high, ind3)
pos3 = array.get(high_ind, ind3)
if p3 > k * pos3 + b
ok := false
break

pos3 = 0
p_val = p2 + k
if ok
for ind = pos2 + 1 to bar_index
if close[bar_index - ind] > p_val
ok := false
break
pos3 := ind + 1
p_val += k


if ok
if array.size(res_slopes) < max_lines
line = line.new(pos1, p1, pos3, p_val, color=res_line_color)//, extend=extend.right)
array.push(res_lines, line)
array.push(res_slopes, k)
else
max_slope = array.max(res_slopes)
max_slope_ind = array.indexof(res_slopes, max_slope)
if max_lines == 1
max_slope_ind := 0
if k < max_slope
line_to_delete = array.get(res_lines, max_slope_ind)
line.delete(line_to_delete)
new_line = line.new(pos1, p1, pos3, p_val, color=res_line_color)//, extend=extend.right)
array.insert(res_lines, max_slope_ind, new_line)
array.insert(res_slopes, max_slope_ind, k)
array.remove(res_lines, max_slope_ind + 1)
array.remove(res_slopes, max_slope_ind + 1)

if not show_lines
len_l = array.size(res_lines)
if (len_l >= 1)
for ind = 0 to len_l - 1
to_delete = array.pop(res_lines)
array.pop(res_slopes)
line.delete(to_delete)



var sup_lines = array.new_line()
var sup_slopes = array.new_float()

len_lines1 = array.size(sup_lines)

if (len_lines1 >= 1)
for ind = 0 to len_lines1 - 1
to_delete = array.pop(sup_lines)
array.pop(sup_slopes)
line.delete(to_delete)

if array.size(pivots_low) == max_num_of_pivots
for ind1 = 0 to max_num_of_pivots - 2
for ind2 = ind1 + 1 to max_num_of_pivots - 1
p1 = array.get(pivots_low, ind1)
p2 = array.get(pivots_low, ind2)
pos1 = array.get(low_ind, ind1)
pos2 = array.get(low_ind, ind2)
k = count_slope(p1, p2, pos1, pos2)
b = p1 - k * pos1

ok = true

// check if pivot points in the middle of two points is lower
if ind2 - ind1 >= 1 and ok
for ind3 = ind1 + 1 to ind2 - 1
p3 = array.get(pivots_low, ind3)
pos3 = array.get(low_ind, ind3)
if p3 < k * pos3 + b
ok := false
break

pos3 = 0
p_val = p2 + k
if ok
for ind = pos2 + 1 to bar_index
if close[bar_index - ind] < p_val
ok := false
break
pos3 := ind + 1
p_val += k

if ok
if array.size(sup_slopes) < max_lines
line = line.new(pos1, p1, pos3, p_val, color=sup_line_color)//, extend=extend.right)
array.push(sup_lines, line)
array.push(sup_slopes, k)
else
max_slope = array.min(sup_slopes)
max_slope_ind = array.indexof(sup_slopes, max_slope)
if max_lines == 1
max_slope_ind := 0
if k > max_slope
line_to_delete = array.get(sup_lines, max_slope_ind)
line.delete(line_to_delete)
new_line = line.new(pos1, p1, pos3, p_val, color=sup_line_color)//, extend=extend.right)
array.insert(sup_lines, max_slope_ind, new_line)
array.insert(sup_slopes, max_slope_ind, k)
array.remove(sup_lines, max_slope_ind + 1)
array.remove(sup_slopes, max_slope_ind + 1)


if not show_lines
len_l = array.size(sup_lines)
if (len_l >= 1)
for ind = 0 to len_l - 1
to_delete = array.pop(sup_lines)
array.pop(sup_slopes)
line.delete(to_delete)


plotLiq = input.bool(defval=true, title='Liquidity Highs/Lows', group='Enable/Disable Section---------------------------------------------', inline = '01')

/////////////////////////////////////////////////////////////////////////Liquidity Equal Highs
pvtTopColor = input.color(defval=color.new(color.green,85), title='Top Color', group='Liquidity-------------------------------------------------', inline='1')
pvtBtmColor = input.color(defval=color.new(color.red,85), title='Bottom Color', group='Liquidity-------------------------------------------------',inline = '1')
pvtStyle = line.style_solid
pvtMax = input.int(defval=30, title='Maximum Liquidity Displayed', minval=1, maxval=500, group='Liquidity-------------------------------------------------', tooltip='Minimum = 1, Maximum = 500')
delline = input.bool(defval=true, title='Delete After X Bars Through Line', group='Liquidity-------------------------------------------------')
mitdel = input.int(defval=15, title='Mitigated+Line Delete (X Bars)', minval=1, maxval=100, group='Liquidity-------------------------------------------------', tooltip='Line will remain on chart until this many bars after first broken through. Minimum = 1, Maximum = 500')
linebrk = input.bool(defval=true, title='Color After Close Through Line', group='Liquidity-------------------------------------------------')
mitdelcol = input.color(defval=(color.new(#34eb40,0)), title='Mitigated Color', group='Liquidity-------------------------------------------------', tooltip = 'Once broken, line will change to this colour until deleted. Line deletion is controlled by (Mitigated+Line Delete) input control')
//del_pc = input.bool(defval=false, title='', group='Liquidity-------------------------------------------------', inline="m")
//mitdel_pc = input.int(defval=300, title='Only show lines within x% of current price', minval=1, maxval=500, step=50, group='Liquidity-------------------------------------------------', inline="m")
//
brkstyle = line.style_dashed
var line[] _lowLiqLines = array.new_line()
var line[] _highLiqLines = array.new_line()

//Functions
isPvtHigh(_index, __high) =>
__high[_index+2] < __high[_index+1] and __high[_index+1] > __high[_index]

// | <-- pivot high
// ||| <-- candles
// 210 <-- candle index

isPvtLow(_index, __low) =>
__low[_index+2] > __low[_index+1] and __low[_index+1] < __low[_index]

// ||| <-- candles
// | <-- pivot low
// 210 <-- candle index

//Function to Calculte Line Length
_controlLine(_lines, __high, __low) =>
if array.size(_lines) > 0
for i = array.size(_lines) - 1 to 0 by 1
_line = array.get(_lines, i)
_lineLow = line.get_y1(_line)
_lineHigh = line.get_y2(_line)
_lineRight = line.get_x2(_line)
if na or (bar_index == _lineRight and not((__high > _lineLow and __low < _lineLow) or (__high > _lineHigh and __low < _lineHigh)))
line.set_x2(_line, bar_index + 1)
//deletes line if not within X% of current last price
//pch = (mitdel_pc/100) + 1
//pcl = 1 - (mitdel_pc/100)
//cprice = close
//highpc = (cprice * pch)
//lowpc = (cprice * pcl)
//if del_pc
//if _lineLow < close + mitdel_pc //) and > (close*0.98)) //if Y2 < close*1.05
//line.set_color(_line, color.new(color.white,50))
//line.delete(_line)
///deletes line if more than X bars pass through
if _lineRight > bar_index[mitdel] and _lineRight < bar_index[0] and linebrk
line.set_color(_line,mitdelcol)
line.set_style(_line, brkstyle)
if _lineRight < bar_index[mitdel] and delline
line.delete(_line)

//Pivot Low Line Plotting
if isPvtLow(0, low) and plotLiq
_lowPVT = line.new(x1=bar_index - 1, y1=low[1], x2=bar_index, y2=low[1], extend=extend.none, color=pvtBtmColor, style=pvtStyle)
if array.size(_lowLiqLines) >= pvtMax
line.delete(array.shift(_lowLiqLines))
array.push(_lowLiqLines, _lowPVT)

//Pivot High Line Plotting
if isPvtHigh(0, high) and plotLiq
_highPVT = line.new(x1=bar_index - 1, y1=high[1], x2=bar_index, y2=high[1], extend=extend.none, color=pvtTopColor, style=pvtStyle)
if array.size(_highLiqLines) >= pvtMax
line.delete(array.shift(_highLiqLines))
array.push(_highLiqLines, _highPVT)

if plotLiq
_controlLine(_lowLiqLines, high, low)
_controlLine(_highLiqLines, high, low)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//version=5

// indicator("ابو فيصل 12", overlay=true, max_labels_count=500,explicit_plot_zorder = 1000,max_lines_count = 500,max_boxes_count = 500,precision = 10)

// Control Colors
sky = color.new(color.rgb(0, 219, 255), 60)
PunkCyan = #2157f3
PunkPink = #ff1100
PunkBuy = color.new(color.rgb(0, 255, 100), 50)
PunkSell = color.new(color.rgb(255, 17, 0), 50)


// Get user settings
showBuySell = input(true, "Smart Signals", group="Smart Signals", tooltip="Confirm that the price will move strongly in the direction that the trend points")
sensitivity = 1.3
float percentStop = na
offsetSignal = 5
smooth1 = 35
smooth2 = 45
lineColor = sky
labelColor = sky
showEmas = false
srcEma1 = close
lenEma1 = 55
srcEma2 = close
lenEma2 = 200
//showSwing = input(false, "Show SFP Signals", group="SFP SIGNALS")
//prdSwing = input.int(10, "SFP Period", 2, group="SFP SIGNALS")
colorPos = input(color.new(PunkBuy, 50), "Buy Signal Color")
colorNeg = input(color.new(PunkSell, 50), "Sell Signal Color")
showDashboard = input(true, "Show Dashboard", group="TREND DASHBOARD")
locationDashboard = input.string("Top Right", "Table Location", ["Top Right", "Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center", "Top Left", "Middle Left", "Bottom Left"], group="TREND DASHBOARD")
tableTextColor = input(color.white, "Table Text Color", group="TREND DASHBOARD")
tableBgColor = input(#48419f, "Table Background Color", group="TREND DASHBOARD")
sizeDashboard = input.string("Small", "Table Size", ["Large", "Normal", "Small", "Tiny"], group="TREND DASHBOARD")

// Functions
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
securityNoRep(sym, res, src) => request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on)
swingPoints(prd) =>
pivHi = ta.pivothigh(prd, prd)
pivLo = ta.pivotlow (prd, prd)
last_pivHi = ta.valuewhen(pivHi, pivHi, 1)
last_pivLo = ta.valuewhen(pivLo, pivLo, 1)
hh = pivHi and pivHi > last_pivHi ? pivHi : na
lh = pivHi and pivHi < last_pivHi ? pivHi : na
hl = pivLo and pivLo > last_pivLo ? pivLo : na
ll = pivLo and pivLo < last_pivLo ? pivLo : na
[hh, lh, hl, ll]
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
f_kc(src, len, sensitivity) =>
basis = ta.sma(src, len)
span = ta.atr(len)
[basis + span * sensitivity, basis - span * sensitivity]
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
[wt1, wt2]
f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0]
f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0]
f_fractalize (src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src[2] >= topLimit ? src[2] : na
fractalBot = f_fractalize(src) < 0 and src[2] <= botLimit ? src[2] : na
highPrev = ta.valuewhen(fractalTop, src[2], 0)[2]
highPrice = ta.valuewhen(fractalTop, high[2], 0)[2]
lowPrev = ta.valuewhen(fractalBot, src[2], 0)[2]
lowPrice = ta.valuewhen(fractalBot, low[2], 0)[2]
bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev
bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev
[bearSignal, bullSignal]
// Get components
source = close
smrng1 = smoothrng(source, 27, 1.5)
smrng2 = smoothrng(source, 55, sensitivity)
smrng = (smrng1 + smrng2) / 2
filt = rngfilt(source, smrng)
up = 0.0, up := filt > filt[1] ? nz(up[1]) + 1 : filt < filt[1] ? 0 : nz(up[1])
dn = 0.0, dn := filt < filt[1] ? nz(dn[1]) + 1 : filt > filt[1] ? 0 : nz(dn[1])
bullCond = bool(na), bullCond := source > filt and source > source[1] and up > 0 or source > filt and source < source[1] and up > 0
bearCond = bool(na), bearCond := source < filt and source < source[1] and dn > 0 or source < filt and source > source[1] and dn > 0
lastCond = 0, lastCond := bullCond ? 1 : bearCond ? -1 : lastCond[1]
bull = bullCond and lastCond[1] == -1
bear = bearCond and lastCond[1] == 1
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
rsi = ta.rsi(close, 21)
rsiOb = rsi > 70 and rsi > ta.ema(rsi, 10)
rsiOs = rsi < 30 and rsi < ta.ema(rsi, 10)
dHigh = securityNoRep(syminfo.tickerid, "D", high [1])
dLow = securityNoRep(syminfo.tickerid, "D", low [1])
dClose = securityNoRep(syminfo.tickerid, "D", close[1])
ema1 = ta.ema(srcEma1, lenEma1)
ema2 = ta.ema(srcEma2, lenEma2)
ema = ta.ema(close, 144)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)



var dashboard_loc = locationDashboard == "Top Center" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Right" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.tiny : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 2, 15, tableBgColor, #000000, 2, tableBgColor, 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column, row, txt, 0, 0, signal ? #000000 : tableTextColor, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
if barstate.islast and showDashboard

dashboard_cell(0, 1 , "المتوقع")
dashboard_cell(0, 2 ," الحالي")
dashboard_cell(0, 3 , "فوليوم")

dashboard_cell(1, 1 , trigger ? "كول" : "بوت", true), dashboard_cell_bg(1, 1, trigger ? color.rgb(89, 255, 12) : color.rgb(255, 7, 7))
dashboard_cell(1, 2 , emaBull ?"كول":"بوت", true), dashboard_cell_bg(1, 2, emaBull ? color.rgb(107, 255, 8) : color.rgb(248, 11, 3))
dashboard_cell(1, 3 , str.tostring(volume))


// Constants
color CLEAR = color.rgb(0,0,0,100)


eq_threshold = input.float(0.3, '', minval = 0, maxval = 0.5, step = 0.1, group = 'Market Structure',inline = 'equilibrium_zone')
showSwing = input.bool(false, 'Swing Points', group="Market Structure",inline="3")
swingSize_swing = input.int(10, "Swing Point Period",inline="4", group="Market Structure")
label_sizes_s =input.string("Medium", options=["Small", "Medium","Large"], title="Label Size",inline="4", group="Market Structure")
label_size_buysell_s = label_sizes_s == "Small" ? size.tiny : label_sizes_s == "Medium" ? size.small : label_sizes_s == "Large" ? size.normal : label_sizes_s == "Medium2" ? size.normal : label_sizes_s == "Large2" ? size.large : size.huge
label_size_buysell = label_sizes_s == "Small" ? size.tiny : label_sizes_s == "Medium" ? size.small : label_sizes_s == "Large" ? size.normal : label_sizes_s == "Medium2" ? size.normal : label_sizes_s == "Large2" ? size.large : size.huge
swingColor = input.color(#787b86 , '', group="Market Structure",inline="3")

swingSize = 3
length_eqh = 3

//----------------------------------------}
//Key Levels
//----------------------------------------{
var Show_4H_Levels = input.bool(defval=false, title='4H', group='Key Levels', inline='4H')
Color_4H_Levels = input.color(title='', defval=color.orange, group='Key Levels', inline='4H')
Style_4H_Levels = input.string('Dotted', ' Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="4H")
Text_4H_Levels = input.bool(defval=false, title='Shorten', group='Key Levels', inline='4H')

labelsize = input.string(defval='Medium', title='Text Size', options=['Small', 'Medium', 'Large'],group = "Key Levels", inline='H')

var pihtext = Text_4H_Levels ? '-4H-' :'مقاومة 4'
displayStyle = 'Standard'
distanceright = 25
radistance = 250
linesize = 'Small'
linestyle = 'Solid'
var untested_monday = false

bosConfType = 'Candle High'//input.string('Candle Close', 'BOS Confirmation', ['Candle Close', 'Wicks'], tooltip='Choose whether candle close/wick above previous swing point counts as a BOS.')
MSS = true//input.bool(false, 'Show MSS', tooltip='Renames the first counter t_MS BOS to MSS' )
// showSwing = false//input.bool(true, 'Show Swing Points', tooltip='Show or hide HH, LH, HL, LL')

// Functions
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
pivot_high_found = ta.pivothigh(high, swingSize_swing, swingSize_swing)
pivot_low_found = ta.pivotlow(low, swingSize_swing, swingSize_swing)

var float prevHigh_s = na,var float prevLow_s = na,var int prevHighIndex_s = na,var int prevLowIndex_s = na
bool higher_highs = false, bool lower_highs = false, bool higher_lows = false, bool lower_lows = false

var int prevSwing_s = 0

if not na(pivot_high_found)
if pivot_high_found >= prevHigh_s
higher_highs := true
prevSwing_s := 2
else
lower_highs := true
prevSwing_s := 1
prevHigh_s := pivot_high_found
prevHighIndex_s := bar_index - swingSize_swing

if not na(pivot_low_found)
if pivot_low_found >= prevLow_s
higher_lows := true
prevSwing_s := -1
else
lower_lows := true
prevSwing_s := -2
prevLow_s := pivot_low_found
prevLowIndex_s := bar_index - swingSize_swing

// ———————————————————— Global data {
//Using current bar data for HTF highs and lows instead of security to prevent future leaking
var htfH = open
var htfL = open

if close > htfH
htfH:= close
if close < htfL
htfL := close

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------- Key Levels
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var monday_time = time
var monday_high = high
var monday_low = low

[weekly_time, weekly_open] = request.security(syminfo.tickerid, 'W', [time, open], lookahead=barmerge.lookahead_on)
[weeklyh_time, weeklyh_open] = request.security(syminfo.tickerid, 'W', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[weeklyl_time, weeklyl_open] = request.security(syminfo.tickerid, 'W', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[monthly_time, monthly_open] = request.security(syminfo.tickerid, 'M', [time, open], lookahead=barmerge.lookahead_on)
[monthlyh_time, monthlyh_open] = request.security(syminfo.tickerid, 'M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[monthlyl_time, monthlyl_open] = request.security(syminfo.tickerid, 'M', [time[1], low[1]], lookahead=barmerge.lookahead_on)

[intrah_time, intrah_open] = request.security(syminfo.tickerid, '240', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time, intral_open] = request.security(syminfo.tickerid, '240', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[quarterly_time, quarterly_open] = request.security(syminfo.tickerid, '3M', [time, open], lookahead=barmerge.lookahead_on)
[quarterlyh_time, quarterlyh_open] = request.security(syminfo.tickerid, '3M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[quarterlyl_time, quarterlyl_open] = request.security(syminfo.tickerid, '3M', [time[1], low[1]], lookahead=barmerge.lookahead_on)

[yearlyh_time, yearlyh_open] = request.security(syminfo.tickerid, '12M', [time, high], lookahead=barmerge.lookahead_on)
[yearlyl_time, yearlyl_open] = request.security(syminfo.tickerid, '12M', [time, low], lookahead=barmerge.lookahead_on)
if weekly_time != weekly_time[1]
untested_monday := false
untested_monday

untested_monday := true

monday_low
linewidthint = 1
if linesize == 'Small'
linewidthint := 1
linewidthint
if linesize == 'Medium'
linewidthint := 2
linewidthint
if linesize == 'Large'
linewidthint := 3
linewidthint
var linewidth_def = linewidthint
fontsize = size.small
if labelsize == 'Small'
fontsize := size.small
fontsize
if labelsize == 'Medium'
fontsize := size.normal
fontsize
if labelsize == 'Large'
fontsize := size.large
fontsize
linestyles = line.style_solid
if linestyle == 'Dashed'
linestyles := line.style_dashed
linestyles
if linestyle == 'Dotted'
linestyles := line.style_dotted
linestyles
var DEFAULT_LABEL_SIZE = fontsize
var DEFAULT_LABEL_STYLE = label.style_none
var Rigth_Def = distanceright
var arr_price = array.new_float(0)
var arr_label = array.new_label(0)
Combine_Levels(arr_price, arr_label, currentprice, currentlabel, currentcolor) =>
if array.includes(arr_price, currentprice)
whichindex = array.indexof(arr_price, currentprice)
labelhold = array.get(arr_label, whichindex)
whichtext = label.get_text(labelhold)
label.set_text(labelhold, label.get_text(currentlabel) + ' / ' + whichtext)
label.set_text(currentlabel, '')
label.set_textcolor(labelhold, currentcolor)
else
array.push(arr_price, currentprice)
array.push(arr_label, currentlabel)
extend_to_current(bars) =>
timenow + (time - time[1]) * bars
if barstate.islast
arr_price := array.new_float(0)
arr_label := array.new_label(0)
if Show_4H_Levels
limit_4H_right = extend_to_current(Rigth_Def)
intrah_limit_right = extend_to_current(Rigth_Def)
intral_limit_right = extend_to_current(Rigth_Def)

var intrah_line = line.new(x1=intrah_time, x2=intrah_limit_right, y1=intrah_open, y2=intrah_open, color=Color_4H_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_4H_Levels))
var intrah_label = label.new(x=intrah_limit_right, y=intrah_open, text=pihtext, style=DEFAULT_LABEL_STYLE, textcolor=Color_4H_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
var intral_line = line.new(x1=intral_time, x2=intral_limit_right, y1=intral_open, y2=intral_open, color=Color_4H_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_4H_Levels))

line.set_xy1(intrah_line,intrah_time,intrah_open)
line.set_xy2(intrah_line,intrah_limit_right,intrah_open)
label.set_xy(intrah_label,intrah_limit_right,intrah_open)
label.set_text(intrah_label, pihtext)
line.set_x1(intral_line, intral_time)
line.set_x2(intral_line, intral_limit_right)
line.set_y1(intral_line, intral_open)
line.set_y2(intral_line, intral_open)

Combine_Levels(arr_price, arr_label, intrah_open, intrah_label, Color_4H_Levels)



daily_limit_right = extend_to_current(Rigth_Def)
dailyh_limit_right = extend_to_current(Rigth_Def)
dailyl_limit_right = extend_to_current(Rigth_Def)


type Candle
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
box body
line wick_up
line wick_down


type Imbalance
box b
int idx

type CandleSettings
bool show
string htf
int max_display

type Settings
int max_sets
color bull_body
color bull_border
color bull_wick
color bear_body
color bear_border
color bear_wick
int offset
int buffer
int htf_buffer
int width
bool trace_show
color trace_o_color
string trace_o_style
int trace_o_size
color trace_c_color
string trace_c_style
int trace_c_size
color trace_h_color
string trace_h_style
int trace_h_size
color trace_l_color
string trace_l_style
int trace_l_size
string trace_anchor
bool label_show
color label_color
string label_size
bool htf_label_show
color htf_label_color
string htf_label_size
bool htf_timer_show
color htf_timer_color
string htf_timer_size

type CandleSet
Candle[] candles
Imbalance[] imbalances
CandleSettings settings
label tfName
label tfTimer

type Helper
string name = "Helper"

Settings settings = Settings.new()

var CandleSettings SettingsHTF1 = CandleSettings.new()
var CandleSettings SettingsHTF2 = CandleSettings.new()
var CandleSettings SettingsHTF3 = CandleSettings.new()



var Candle[] candles_1 = array.new<Candle>(0)
var Candle[] candles_2 = array.new<Candle>(0)
var Candle[] candles_3 = array.new<Candle>(0)


var CandleSet htf1 = CandleSet.new()
htf1.settings := SettingsHTF1
htf1.candles := candles_1


var CandleSet htf2 = CandleSet.new()
htf2.settings := SettingsHTF2
htf2.candles := candles_2


var CandleSet htf3 = CandleSet.new()
htf3.settings := SettingsHTF3
htf3.candles := candles_3



//+------------------------------------------------------------------------------------------------------------+//
//+--- Settings ---+//
//+------------------------------------------------------------------------------------------------------------+//

htf1.settings.show := input.bool(true, "HTF 1      ", inline="htf1")
htf_1 = input.timeframe("15", "", inline="htf1")
htf1.settings.htf := htf_1
htf1.settings.max_display := input.int(4, "", inline="htf1")

htf2.settings.show := input.bool(true, "HTF 2      ", inline="htf2")
htf_2 = input.timeframe("60", "", inline="htf2")
htf2.settings.htf := htf_2
htf2.settings.max_display := input.int(4, "", inline="htf2")

htf3.settings.show := input.bool(true, "HTF 3      ", inline="htf3")
htf_3 = input.timeframe("1D", "", inline="htf3")
htf3.settings.htf := htf_3
htf3.settings.max_display := input.int(4, "", inline="htf3")


settings.max_sets := input.int(6, "Limit to next HTFs only", minval=1, maxval=6)

settings.bull_body := input.color(color.new(#0efd16, 3), "Body  ", inline="body")
settings.bear_body := input.color(color.new(#ec0808, 0), "", inline="body")
settings.bull_border := input.color(color.rgb(159, 159, 169), "Borders", inline="borders")
settings.bear_border := input.color(color.new(#e5e9ea, 0), "", inline="borders")
settings.bull_wick := input.color(color.new(#e9eeee, 10), "Wick  ", inline="wick")
settings.bear_wick := input.color(#f7f9f9, "", inline="wick")

settings.offset := input.int(25, "padding from current candles", minval = 1)
settings.buffer := input.int(1, "space between candles", minval = 1, maxval = 4)
settings.htf_buffer := input.int(10, "space between Higher Timeframes", minval = 1, maxval = 10)
settings.width := input.int(1, "Candle Width", minval = 1, maxval = 4)*2

settings.htf_label_show := input.bool(true, "HTF Label           ", inline="HTFlabel")
settings.htf_label_color := input.color(color.new(color.black, 10), "", inline='HTFlabel')
settings.htf_label_size := input.string(size.large, "", [size.tiny, size.small, size.normal, size.large, size.huge], inline="HTFlabel")

//+------------------------------------------------------------------------------------------------------------+//
//+--- Variables ---+//
//+------------------------------------------------------------------------------------------------------------+//

Helper helper = Helper.new()

color color_transparent = #ffffff00

//+------------------------------------------------------------------------------------------------------------+//
//+--- Internal Functions ---+//
//+------------------------------------------------------------------------------------------------------------+//

method LineStyle(Helper helper, string style) =>
helper.name := style
out = switch style
'----' => line.style_dashed
'····' => line.style_dotted
=> line.style_solid


method ValidTimeframe(Helper helper, string HTF) =>
helper.name := HTF
if timeframe.in_seconds(HTF) >= timeframe.in_seconds("D") and timeframe.in_seconds(HTF) > timeframe.in_seconds()
true
else
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(HTF)
n3 = n1 % n2
(n1 < n2 and math.round(n2/n1) == n2/n1)

method HTFName(Helper helper, string HTF) =>
helper.name := "HTFName"
formatted = HTF

seconds = timeframe.in_seconds(HTF)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted

method HTFEnabled(Helper helper) =>
helper.name := "HTFEnabled"
int enabled =0
enabled += htf1.settings.show ? 1 : 0
enabled += htf2.settings.show ? 1 : 0
enabled += htf3.settings.show ? 1 : 0

int last = math.min(enabled, settings.max_sets)

last

method CandleSetHigh(Helper helper, Candle[] candles, float h) =>
helper.name := "CandlesSetHigh"
float _h = h
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
Candle c = array.get(candles, i)
if c.h > _h
_h := c.h
_h

method CandlesHigh(Helper helper, Candle[] candles) =>
helper.name := "CandlesHigh"
h = 0.0
int cnt = 0
int last = helper.HTFEnabled()

if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
h := helper.CandleSetHigh(htf1.candles, h)
cnt += 1
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt < last
h := helper.CandleSetHigh(htf2.candles, h)
cnt +=1
if htf3.settings.show and helper.ValidTimeframe(htf3.settings.htf) and cnt < last
h := helper.CandleSetHigh(htf3.candles, h)
cnt += 1


if array.size(candles) > 0
for i = 0 to array.size(candles)-1
Candle c = array.get(candles, i)
if c.h > h
h := c.h
h

method Reorder(CandleSet candleSet, int offset) =>
size = candleSet.candles.size()

if size > 0
for i = size-1 to 0
Candle candle = candleSet.candles.get(i)
t_buffer = offset + ((settings.width+settings.buffer)*(size-i-1))
box.set_left(candle.body, bar_index + t_buffer)
box.set_right(candle.body, bar_index + settings.width + t_buffer)
line.set_x1(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x1(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
candleSet

top = helper.CandlesHigh(candleSet.candles)
left = bar_index + offset + ((settings.width+settings.buffer)*(size-1))/2

if settings.htf_label_show
var label l = candleSet.tfName

string lbl = helper.HTFName(candleSet.settings.htf)
if settings.htf_timer_show
lbl += "\n"

if not na(l)
label.set_xy(l, left, top)
else
l := label.new(left, top, lbl, color=color_transparent, textcolor = settings.htf_label_color, style=label.style_label_down, size = settings.htf_label_size)

if settings.htf_timer_show
var label t = candleSet.tfTimer

if not na(t)
label.set_xy(t, left, top)


candleSet

method FindImbalance(CandleSet candleSet) =>
if barstate.isrealtime or barstate.islast
if candleSet.imbalances.size() > 0
for i = candleSet.imbalances.size()-1 to 0
Imbalance del = candleSet.imbalances.get(i)
box.delete(del.b)
candleSet.imbalances.pop()

if candleSet.candles.size() > 3
for i = 1 to candleSet.candles.size() -3
candle1 = candleSet.candles.get(i)
candle2 = candleSet.candles.get(i+2)
candle3 = candleSet.candles.get(i+1)
method Monitor(CandleSet candleSet) =>
HTFBarTime = time(candleSet.settings.htf)
isNewHTFCandle = ta.change(HTFBarTime)

if isNewHTFCandle
Candle candle = Candle.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.o_idx := bar_index
candle.c_idx := bar_index
candle.h_idx := bar_index
candle.l_idx := bar_index

bull = candle.c > candle.o

candle.body := box.new(bar_index, math.max(candle.o, candle.c), bar_index+2, math.min(candle.o, candle.c), bull ? settings.bull_border : settings.bear_border, 1, bgcolor = bull ? settings.bull_body : settings.bear_body)
candle.wick_up := line.new(bar_index+1, candle.h, bar_index, math.max(candle.o, candle.c), color=bull ? settings.bull_wick : settings.bear_wick)
candle.wick_down := line.new(bar_index+1, math.min(candle.o, candle.c), bar_index, candle.l, color=bull ? settings.bull_wick : settings.bear_wick)

candleSet.candles.unshift(candle)

if candleSet.candles.size() > candleSet.settings.max_display
Candle delCandle = array.pop(candleSet.candles)
box.delete(delCandle.body)
line.delete(delCandle.wick_up)
line.delete(delCandle.wick_down)

candleSet

method Update(CandleSet candleSet, int offset, bool showTrace) =>
if candleSet.candles.size() > 0
Candle candle = candleSet.candles.first()
candle.h_idx := high > candle.h ? bar_index : candle.h_idx
candle.h := high > candle.h ? high : candle.h
candle.l_idx := low < candle.l ? bar_index : candle.l_idx
candle.l := low < candle.l ? low : candle.l
candle.c := close
candle.c_idx := bar_index

bull = candle.c > candle.o

box.set_top(candle.body, candle.o)
box.set_bottom(candle.body, candle.c)
box.set_bgcolor(candle.body, bull ? settings.bull_body : settings.bear_body)
box.set_border_color(candle.body, bull ? settings.bull_border : settings.bear_border)
line.set_color(candle.wick_up, bull ? settings.bull_wick : settings.bear_wick)
line.set_color(candle.wick_down, bull ? settings.bull_wick : settings.bear_wick)
line.set_y1(candle.wick_up, candle.h)
line.set_y2(candle.wick_up, math.max(candle.o, candle.c))
line.set_y1(candle.wick_down, candle.l)
line.set_y2(candle.wick_down, math.min(candle.o, candle.c))

if barstate.isrealtime or barstate.islast
candleSet.Reorder(offset)

candleSet

int cnt = 0
int last = helper.HTFEnabled()

int offset = settings.offset
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
bool showTrace = false
if settings.trace_anchor == "First Timeframe"
showTrace := true
if settings.trace_anchor == "Last Timeframe" and settings.max_sets == 1
showTrace := true
htf1.Monitor().Update(offset, showTrace)
cnt +=1
offset += cnt > 0 ? (htf1.candles.size() * settings.width) + (htf1.candles.size() > 0 ? htf1.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt < last
bool showTrace = false
if settings.trace_anchor == "First Timeframe" and cnt == 0
showTrace := true
if settings.trace_anchor == "Last Timeframe" and cnt == last-1
showTrace := true
htf2.Monitor().Update(offset, showTrace)
cnt+=1
offset += cnt > 0 ? (htf2.candles.size() * settings.width) + (htf2.candles.size() > 0 ? htf2.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
if htf3.settings.show and helper.ValidTimeframe(htf3.settings.htf) and cnt < last
bool showTrace = false
if settings.trace_anchor == "First Timeframe" and cnt == 0
showTrace := true
if settings.trace_anchor == "Last Timeframe" and cnt == last-1
showTrace := true
htf3.Monitor().Update(offset, showTrace)
cnt+=1
offset += cnt > 0 ? (htf3.candles.size() * settings.width) + (htf3.candles.size() > 0 ? htf3.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0





// =======================
// إعدادات مناطق العرض والطلب
// =======================
zigzagLen = input.int(9, 'ZigZag Length', group = 'Order Block Settings')
numberObShow = input.int(1, 'عدد مناطق العرض والطلب المعروضة', group = 'Order Block Settings', minval = 1, maxval = 10)
bearishOrderblockColor = input.color(color.new(#dc1515, 18), title = 'لون منطقة العرض', group = 'Order Block Settings')
bullishOrderblockColor = input.color(color.new(#58bd0f, 10), title = 'لون منطقة الطلب', group = 'Order Block Settings')

// إعدادات نسبة القوة
showStrengthLabels = input.bool(true, 'عرض نسبة القوة', group = 'Strength Settings')
strengthThreshold = input.int(60, 'حد التنبيه', group = 'Strength Settings', minval = 50, maxval = 90)
enableAlert = input.bool(true, 'تفعيل التنبيهات', group = 'Strength Settings')

// أنواع البيانات
type orderblock
float value
int barStart
int barEnd
box block
bool broken
label supplyLabel
label demandLabel

// المصفوفات
var array<orderblock> bullishOrderblock = array.new<orderblock>()
var array<orderblock> bearishOrderblock = array.new<orderblock>()
var array<int> highValIndex = array.new<int>()
var array<int> lowValIndex = array.new<int>()
var array<float> highVal = array.new_float()
var array<float> lowVal = array.new_float()

// المتغيرات
var bool drawUp = false
var bool drawDown = false
var string lastState = na
var bool to_up = false
var bool to_down = false
var int trend = 1
atr = ta.atr(14)

// حساب الاتجاه
to_up := high[zigzagLen] >= ta.highest(high, zigzagLen)
to_down := low[zigzagLen] <= ta.lowest(low, zigzagLen)
trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend

// تحديد تغيير الاتجاه للأعلى
if ta.change(trend) != 0 and trend == 1
array.push(highValIndex, time[zigzagLen])
array.push(highVal, high[zigzagLen])
if array.size(lowVal) > 1
drawUp := false

// تحديد تغيير الاتجاه للأسفل
if ta.change(trend) != 0 and trend == -1
array.push(lowValIndex, time[zigzagLen])
array.push(lowVal, low[zigzagLen])
if array.size(highVal) > 1
drawDown := false

// دالة حساب نسبة القوة (من إجمالي 100)
calculateStrengthRatio() =>
float supplyStrength = 0.0
float demandStrength = 0.0

// حساب قوة العرض
int supplyTouches = 0
for i = 1 to 20
if i < bar_index
if close < open
supplyTouches += 1

// حساب قوة الطلب
int demandTouches = 0
for i = 1 to 20
if i < bar_index
if close > open
demandTouches += 1

// حساب النسب من إجمالي الحجم
float avgVolume = ta.sma(volume, 20)
float volumeRatio = volume / avgVolume

// حساب قوة الاتجاه
float rsiValue = ta.rsi(close, 14)

if rsiValue > 50
demandStrength := rsiValue
supplyStrength := 100 - rsiValue
else
supplyStrength := 100 - rsiValue
demandStrength := rsiValue

[supplyStrength, demandStrength]

// إنشاء منطقة عرض (Bearish Order Block)
if array.size(lowVal) > 1 and drawDown == false
if close < array.get(lowVal, array.size(lowVal) - 1)
drawDown := true
lastState := 'down'

orderblock newOrderblock = orderblock.new()
float max = 0
int bar = na
for i = (time - array.get(lowValIndex, array.size(lowValIndex) - 1) - (time - time[1])) / (time - time[1]) to 0 by 1
if high > max
max := high
bar := time

newOrderblock.barStart := bar
newOrderblock.barEnd := time
newOrderblock.broken := false
newOrderblock.value := max

// جعل الخط نحيف بدلاً من صندوق
newOrderblock.block := box.new(
left = newOrderblock.barStart,
top = newOrderblock.value,
right = newOrderblock.barEnd,
bottom = newOrderblock.value - atr * 0.20,
xloc = xloc.bar_time,
bgcolor = bearishOrderblockColor,
border_width = 1,
border_color = color.new(#cd1212, 0))

// حساب النسب
[supplyStr, demandStr] = calculateStrengthRatio()

newOrderblock.supplyLabel := na
newOrderblock.demandLabel := na

if showStrengthLabels
// قوة العرض فوق الخط
newOrderblock.supplyLabel := label.new(
x = time,
y = newOrderblock.value + atr * 0.5,
text = "عرض: "+ str.tostring(supplyStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = supplyStr >= strengthThreshold ? color.new(color.red, 0) : color.new(color.orange, 0),
textcolor = color.white,
style = label.style_label_down,
size = size.normal)

// قوة الطلب تحت الخط
newOrderblock.demandLabel := label.new(
x = time,
y = newOrderblock.value - atr * 0.5,
text = " طلب" + str.tostring(demandStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = color.new(color.gray, 30),
textcolor = color.white,
style = label.style_label_up,
size = size.small)

// تنبيه عند تجاوز الحد
if enableAlert and supplyStr >= strengthThreshold
alert("تنبيه: قوة العرض " + str.tostring(supplyStr, "#") + "% - تجاوزت " + str.tostring(strengthThreshold) + "%", alert.freq_once_per_bar)

array.push(bearishOrderblock, newOrderblock)
if array.size(bearishOrderblock) > 20
oldBlock = array.shift(bearishOrderblock)
if not na(oldBlock.supplyLabel)
label.delete(oldBlock.supplyLabel)
if not na(oldBlock.demandLabel)
label.delete(oldBlock.demandLabel)

// إنشاء منطقة طلب (Bullish Order Block)
if array.size(highVal) > 1 and drawUp == false
if close > array.get(highVal, array.size(highVal) - 1)
drawUp := true
lastState := 'up'

orderblock newOrderblock = orderblock.new()
float min = 999999999
int bar = na
for i = (time - array.get(highValIndex, array.size(highValIndex) - 1) - (time - time[1])) / (time - time[1]) to 0 by 1
if low < min
min := low
bar := time

newOrderblock.barStart := bar
newOrderblock.barEnd := time
newOrderblock.broken := false
newOrderblock.value := min

// جعل الخط نحيف بدلاً من صندوق
newOrderblock.block := box.new(
left = newOrderblock.barStart,
top = newOrderblock.value + atr *0.30,
right = newOrderblock.barEnd,
bottom = newOrderblock.value,
xloc = xloc.bar_time,
bgcolor = bullishOrderblockColor,
border_width = 1,
border_color = color.new(#52ae10, 0))

// حساب النسب
[supplyStr, demandStr] = calculateStrengthRatio()

newOrderblock.supplyLabel := na
newOrderblock.demandLabel := na

if showStrengthLabels
// قوة الطلب تحت الخط
newOrderblock.demandLabel := label.new(
x = time,
y = newOrderblock.value - atr * 0.5,
text = "طلب: " + str.tostring(demandStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = demandStr >= strengthThreshold ? color.new(color.green, 0) : color.new(color.blue, 0),
textcolor = color.white,
style = label.style_label_up,
size = size.normal)

// تنبيه عند تجاوز الحد
if enableAlert and demandStr >= strengthThreshold
alert("تنبيه: قوة الطلب " + str.tostring(demandStr, "#") + "% - تجاوزت " + str.tostring(strengthThreshold) + "%", alert.freq_once_per_bar)

array.push(bullishOrderblock, newOrderblock)
if array.size(bullishOrderblock) > 20
oldBlock = array.shift(bullishOrderblock)
if not na(oldBlock.supplyLabel)
label.delete(oldBlock.supplyLabel)
if not na(oldBlock.demandLabel)
label.delete(oldBlock.demandLabel)

// متغيرات العداد
var int activeBullishCount = 0
var int activeBearishCount = 0

// تحديث مناطق الطلب
if array.size(bullishOrderblock) > 0
orderblock testOrderblock = na
int counter = 0
activeBullishCount := 0
for i = array.size(bullishOrderblock) - 1 to 0 by 1
testOrderblock := array.get(bullishOrderblock, i)
if counter < numberObShow
testOrderblock.block.set_right(time)

// تحديث النسب المتحركة
[supplyStr, demandStr] = calculateStrengthRatio()

if showStrengthLabels
if not na(testOrderblock.demandLabel)
label.set_x(testOrderblock.demandLabel, time)
label.set_text(testOrderblock.demandLabel, "طلب: " + str.tostring(demandStr, "#") + "%")
label.set_color(testOrderblock.demandLabel, demandStr >= strengthThreshold ? color.new(color.green, 0) : color.new(color.blue, 0))

if not na(testOrderblock.supplyLabel)
label.set_x(testOrderblock.supplyLabel, time)
label.set_text(testOrderblock.supplyLabel, "عرض: " + str.tostring(supplyStr, "#") + "%")

if close < testOrderblock.value
testOrderblock.block.delete()
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
array.remove(bullishOrderblock, i)
else
activeBullishCount += 1
counter := counter + 1
else
testOrderblock.block.set_right(testOrderblock.barStart)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)

// تحديث مناطق العرض
if array.size(bearishOrderblock) > 0
orderblock testOrderblock = na
int counter = 0
activeBearishCount := 0
for i = array.size(bearishOrderblock) - 1 to 0 by 1
testOrderblock := array.get(bearishOrderblock, i)
if counter < numberObShow
testOrderblock.block.set_right(time)

// تحديث النسب المتحركة
[supplyStr, demandStr] = calculateStrengthRatio()

if showStrengthLabels
if not na(testOrderblock.supplyLabel)
label.set_x(testOrderblock.supplyLabel, time)
label.set_text(testOrderblock.supplyLabel," عرض " + str.tostring(supplyStr, "#") + "%")
label.set_color(testOrderblock.supplyLabel, supplyStr >= strengthThreshold ? color.new(color.red, 0) : color.new(color.orange, 0))

if not na(testOrderblock.demandLabel)
label.set_x(testOrderblock.demandLabel, time)
label.set_text(testOrderblock.demandLabel,"طلب " + str.tostring(demandStr, "#") + "%")

if close > testOrderblock.value
testOrderblock.block.delete()
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
array.remove(bearishOrderblock, i)
else
activeBearishCount += 1
counter := counter + 1
else
testOrderblock.block.set_right(testOrderblock.barStart)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)




// ========== إعدادات FVG ==========
showFVG = input.bool(defval = true, title = "Show Fair Value Gaps", group = "FVG")
contract = input.bool(defval = false, title = "Contract Violated FVG", group = "FVG")
closeOnly = input.bool(defval = false, title = "Show Closest Up/Down FVG Only", group = "FVG")
fvgcol = input.color(defval = #f2da07, title = "FVG Color", group = "FVG")
fvgtra = input.int(defval = 80, minval = 0, maxval = 100, title = "FVG Transparency", group = "FVG")

// ========== دالة FVG ==========
fvg(direction) =>
var fvgMat = matrix.new<float>(5)
var fvgDrawings = array.new<box>()

fvgMat.add_col(0, array.from(math.sign(close - open), close, high, low, time))

if fvgMat.columns() > 3
fvgMat.remove_col(fvgMat.columns() - 1)

if fvgMat.row(0).sum() == direction
getDir = math.sign(direction)

[y, y1] = switch getDir
-1 => [fvgMat.get(3, 2), fvgMat.get(2, 0)]
=> [fvgMat.get(3, 0), fvgMat.get(2, 2)]

col = switch closeOnly
true => #00000000
=> color.new(fvgcol, fvgtra)

fvgDrawings.push(
box.new(int(fvgMat.get(4, 1)), y, last_bar_time, y1, xloc = xloc.bar_time,
border_color = col, bgcolor = col)
)

fvgDrawings

// ========== تنفيذ FVG ==========
if showFVG
fvgDn = fvg(-3)
fvgUp = fvg(3)

// معالجة FVG الهابط
if fvgDn.size() > 0
for i = fvgDn.size() - 1 to 0
getfvg = fvgDn.get(i)

if high >= getfvg.get_top()
getfvg.delete()
fvgDn.remove(i)
else if contract
if high > getfvg.get_bottom()
getfvg.set_bottom(high)

// معالجة FVG الصاعد
if fvgUp.size() > 0
for i = fvgUp.size() - 1 to 0
getfvg = fvgUp.get(i)

if low <= getfvg.get_bottom()
getfvg.delete()
fvgUp.remove(i)
else if contract
if low < getfvg.get_top()
getfvg.set_top(low)

// إظهار أقرب FVG فقط
if closeOnly and barstate.islast
minDist = matrix.new<float>(1, 2, 20e20)

if fvgDn.size() > 0
for i = fvgDn.size() - 1 to 0
getBottom = fvgDn.get(i).get_bottom()
minDist.set(0, 1, math.min(minDist.get(0, 1), math.abs(close - getBottom)))

if math.abs(close - getBottom) == minDist.get(0, 1)
minDist.set(0, 0, i)

fvgDn.get(i).set_right(fvgDn.get(i).get_left())

fvgDn.get(int(minDist.get(0, 0))).set_bgcolor(color.new(fvgcol, fvgtra))
fvgDn.get(int(minDist.get(0, 0))).set_border_color(color.new(fvgcol, fvgtra))
fvgDn.get(int(minDist.get(0, 0))).set_right(last_bar_time)

minDist.set(0, 0, 0)
minDist.set(0, 1, 20e20)

if fvgUp.size() > 0
for i = fvgUp.size() - 1 to 0
getTop = fvgUp.get(i).get_top()
minDist.set(0, 1, math.min(minDist.get(0, 1), math.abs(close - getTop)))

if math.abs(close - getTop) == minDist.get(0, 1)
minDist.set(0, 0, i)

fvgUp.get(i).set_right(fvgUp.get(i).get_left())

fvgUp.get(int(minDist.get(0, 0))).set_bgcolor(color.new(fvgcol, fvgtra))
fvgUp.get(int(minDist.get(0, 0))).set_border_color(color.new(fvgcol, fvgtra))
fvgUp.get(int(minDist.get(0, 0))).set_right(last_bar_time)






//==============================
// إعدادات العرض والألوان
//==============================
Show_Middle_Line_4H = input.bool(true, "عرض خط المنتصف 4H")
Show_Middle_Line_D = input.bool(true, "عرض خط المنتصف Daily")

Color_Middle_Below_4H = input.color(color.red, "لون المنتصف (تحت السعر) 4H")
Color_Middle_Above_4H = input.color(color.green, "لون المنتصف (فوق السعر) 4H")

Color_Middle_Below_D = input.color(color.new(color.red, 0), "لون المنتصف (تحت السعر) Daily")
Color_Middle_Above_D = input.color(color.new(color.green, 0), "لون المنتصف (فوق السعر) Daily")

//==============================
// دالة امتداد الخط إلى اليمين
//==============================
extendToCurrentBar(int offset_bars) =>
timenow + (time - time[1]) * offset_bars

//==============================
// حساب خط المنتصف 4H
//==============================
[intrah_time_4h, intrah_value_4h] = request.security(syminfo.tickerid, "240", [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time_4h, intral_value_4h] = request.security(syminfo.tickerid, "240", [time[1], low[1]], lookahead=barmerge.lookahead_on)
float middle_price_4h = (intrah_value_4h + intral_value_4h) / 2

//==============================
// حساب خط المنتصف Daily
//==============================
[intrah_time_d, intrah_value_d] = request.security(syminfo.tickerid, "D", [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time_d, intral_value_d] = request.security(syminfo.tickerid, "D", [time[1], low[1]], lookahead=barmerge.lookahead_on)
float middle_price_d = (intrah_value_d + intral_value_d) / 2

//==============================
// رسم خط المنتصف 4H
//==============================
if barstate.islast and Show_Middle_Line_4H
int distance_right = 25
color middle_color_4h = close < middle_price_4h ? Color_Middle_Below_4H : Color_Middle_Above_4H
string middle_text_4h = close < middle_price_4h ? "سلبي 🔴 (4H)" : "إيجابي 🟢 (4H)"

var line middle_line_4h = line.new(na, na, na, na, xloc=xloc.bar_time, width=2, style=line.style_solid)
var label middle_label_4h = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none)

line.set_xy1(middle_line_4h, intrah_time_4h, middle_price_4h)
line.set_xy2(middle_line_4h, extendToCurrentBar(distance_right), middle_price_4h)
line.set_color(middle_line_4h, middle_color_4h)

label.set_xy(middle_label_4h, extendToCurrentBar(distance_right), middle_price_4h)
label.set_text(middle_label_4h, str.tostring(middle_price_4h, format.mintick) + " " + middle_text_4h)
label.set_textcolor(middle_label_4h, middle_color_4h)

//==============================
// رسم خط المنتصف Daily
//==============================
if barstate.islast and Show_Middle_Line_D
int distance_right = 25
color middle_color_d = close < middle_price_d ? Color_Middle_Below_D : Color_Middle_Above_D
string middle_text_d = close < middle_price_d ? "سلبي 🔴 (يومي)" : "إيجابي 🟢 (يومي)"

var line middle_line_d = line.new(na, na, na, na, xloc=xloc.bar_time, width=2, style=line.style_dotted)
var label middle_label_d = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none)

line.set_xy1(middle_line_d, intrah_time_d, middle_price_d)
line.set_xy2(middle_line_d, extendToCurrentBar(distance_right), middle_price_d)
line.set_color(middle_line_d, middle_color_d)

label.set_xy(middle_label_d, extendToCurrentBar(distance_right), middle_price_d)
label.set_text(middle_label_d, str.tostring(middle_price_d, format.mintick) + " " + middle_text_d)
label.set_textcolor(middle_label_d, middle_color_d)












// ========== الإعدادات ==========
length = input.int(14, "فترة", minval=1)
threshold = input.int(55, "حد القوة", minval=0, maxval=100)

// اختيار موقع الجدول
tablePositionInput = input.string("Top Right", "موضع الجدول", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right"])

// ========== حساب قوة الطلب والعرض ==========
buyingPressure = close > open ? close - open : 0
sellingPressure = close < open ? open - close : 0

sumBuyingPressure = math.sum(buyingPressure, length)
sumSellingPressure = math.sum(sellingPressure, length)
totalPressure = sumBuyingPressure + sumSellingPressure

demandStrength = totalPressure > 0 ? (sumBuyingPressure / totalPressure) * 100 : 0
supplyStrength = totalPressure > 0 ? (sumSellingPressure / totalPressure) * 100 : 0

// ========== مؤشرات مساعدة ==========

volumeMA = ta.sma(volume, length)
volumeStrength = volume > volumeMA
ema_fast = ta.ema(close, 8)
ema_slow = ta.ema(close, 21)

// ========== شروط الإشارات ==========
callCondition = demandStrength >= threshold and rsi < 70 and close > open and volumeStrength
putCondition = supplyStrength >= threshold and rsi > 30 and close < open and volumeStrength

// ========== إنشاء جدول حسب الموقع ==========
var table infoTableTopLeft = table.new(position.top_left, 2, 5, border_width=1, frame_color=color.gray, frame_width=1)
var table infoTableTopRight = table.new(position.top_right, 2, 5, border_width=1, frame_color=color.gray, frame_width=1)
var table infoTableBottomLeft = table.new(position.bottom_left, 2, 5, border_width=1, frame_color=color.gray, frame_width=1)
var table infoTableBottomRight = table.new(position.bottom_right, 2, 5, border_width=1, frame_color=color.gray, frame_width=1)

var table infoTable = tablePositionInput == "Top Left" ? infoTableTopLeft :
tablePositionInput == "Top Right" ? infoTableTopRight :
tablePositionInput == "Bottom Left" ? infoTableBottomLeft :
infoTableBottomRight

// ========== تعبئة الجدول ==========
if barstate.islast
table.cell(infoTable, 0, 0, "مؤشر", bgcolor=color.new(color.blue, 80), text_color=color.white)
table.cell(infoTable, 1, 0, "قيمة", bgcolor=color.new(color.blue, 80), text_color=color.white)

demandColor = demandStrength >= threshold ? color.new(#5ced61, 52) : color.new(color.gray, 90)
supplyColor = supplyStrength >= threshold ? color.new(#ff4b4b, 62) : color.new(color.gray, 90)
signalColor = callCondition ? color.new(color.green, 70) : (putCondition ? color.new(color.red, 70) : color.new(color.gray, 90))
currentSignal = callCondition ? "CALL" : (putCondition ? "PUT" : "-")

table.cell(infoTable, 0, 1, "طلب", bgcolor=demandColor, text_color=color.white)
table.cell(infoTable, 1, 1, str.tostring(math.round(demandStrength, 0)) + "%", bgcolor=demandColor, text_color=color.white)

table.cell(infoTable, 0, 2, "عرض", bgcolor=supplyColor, text_color=color.white)
table.cell(infoTable, 1, 2, str.tostring(math.round(supplyStrength, 0)) + "%", bgcolor=supplyColor, text_color=color.white)

table.cell(infoTable, 0, 3, "RSI", bgcolor=color.new(#5c646a, 90), text_color=color.white)
table.cell(infoTable, 1, 3, str.tostring(math.round(rsi, 0)), bgcolor=color.new(#8c8995, 95), text_color=color.white)

table.cell(infoTable, 0, 4, "إشاره", bgcolor=signalColor, text_color=color.white)
table.cell(infoTable, 1, 4, currentSignal, bgcolor=signalColor, text_color=color.white)




















// الإعدادات
atrPeriod = input.int(10, "ATR Period")
factor = input.float(3.0, "Supertrend Factor")
rsiLength = input.int(14, "RSI Length")
tablePos = input.string("top_right", "Table Position", options=["top_left","top_right","bottom_left","bottom_right"])

// حساب Supertrend
atrVal = ta.atr(atrPeriod)
hl2Value = (ta.highest(high, atrPeriod) + ta.lowest(low, atrPeriod)) / 2
upperBand = hl2Value + factor * atrVal
lowerBand = hl2Value - factor * atrVal

var float supertrendLine = na
var int trendDirection = 1
previousST = nz(supertrendLine[1], close)
previousDir = nz(trendDirection[1], 1)

if na(atrVal)
supertrendLine := close
trendDirection := 1
else
if previousDir == 1
supertrendLine := close < previousST ? upperBand : math.max(lowerBand, previousST)
else
supertrendLine := close > previousST ? lowerBand : math.min(upperBand, previousST)
trendDirection := close > supertrendLine ? 1 : -1

isBullish = trendDirection == 1
buySignal = trendDirection == 1 and previousDir == -1
sellSignal = trendDirection == -1 and previousDir == 1

// حساب VWAP
vwapLine = ta.vwap(close)
vwapBullish = close > vwapLine

// حساب RSI
rsiValue = ta.rsi(close, rsiLength)
// تحديد رمز Flow بناءً على RSI
rsiFlowSymbol = rsiValue > 55 ? "🟢" : rsiValue < 40 ? "🔴" : "⚪"

// حساب قوة الطلب والعرض
demandPressure = close > open ? (close - open) * volume : 0.0
supplyPressure = close < open ? (open - close) * volume : 0.0
avgDemand = ta.sma(demandPressure, 14)
avgSupply = ta.sma(supplyPressure, 14)

demandPercent = totalPressure > 0 ? (avgDemand / totalPressure) * 100 : 50.0
supplyPercent = totalPressure > 0 ? (avgSupply / totalPressure) * 100 : 50.0
demandSymbol = demandPercent > 55 ? "🟢" : "⚪"
supplySymbol = supplyPercent > 55 ? "🔴" : "⚪"

// حساب الاتجاهات متعددة الأطر الزمنية
getTrendSymbol() =>
emaValue = ta.ema(close, 50)
emaValue > emaValue[1] ? "🟢" : "🔴"

trend3min = request.security(syminfo.tickerid, "3", getTrendSymbol())
trend5min = request.security(syminfo.tickerid, "5", getTrendSymbol())
trend15min = request.security(syminfo.tickerid, "15", getTrendSymbol())
trend1hour = request.security(syminfo.tickerid, "60", getTrendSymbol())

// الإشارة النهائية




// تحديد موقع الجدول
tablePosition = tablePos == "top_right" ? position.top_right : tablePos == "top_left" ? position.top_left : tablePos == "bottom_right" ? position.bottom_right : position.bottom_left

// إنشاء الجدول
var mainTable = table.new(tablePosition, 2, 12, border_width=1)

// تحديث الجدول
if barstate.islast
textSize = size.tiny

// الإشارة النهائية
table.cell(mainTable, 0, 0, "إشارة", text_color=color.white, bgcolor=color.blue, text_size=textSize)


// Supertrend
stText = buySignal ? "✅" : sellSignal ? "❌" : isBullish ? "🟢" : "🔴"
stColor = buySignal ? color.green : sellSignal ? color.red : isBullish ? color.new(color.green, 60) : color.new(color.red, 60)
table.cell(mainTable, 0, 1, "ST", text_color=color.white, bgcolor=color.new(color.blue, 60), text_size=textSize)
table.cell(mainTable, 1, 1, stText, text_color=color.white, bgcolor=stColor, text_size=textSize)




// RSI - تحديد اللون بناءً على القيمة
rsiGreenCondition = rsiValue > 55
rsiRedCondition = rsiValue < 40
rsiBgColor = rsiGreenCondition ? color.new(color.green, 60) : rsiRedCondition ? color.new(color.red, 60) : color.new(color.gray, 60)

table.cell(mainTable, 0, 5, "RSI", text_color=color.white, bgcolor=color.new(color.blue, 60), text_size=textSize)
table.cell(mainTable, 1, 5, str.tostring(rsiValue, "#.0") + " " + rsiFlowSymbol, text_color=color.white, bgcolor=rsiBgColor, text_size=textSize)

// الطلب (Demand)
demandBgColor = demandPercent > 55 ? color.new(color.green, 60) : color.new(color.gray, 60)
table.cell(mainTable, 0, 6, "طلب", text_color=color.white, bgcolor=color.new(color.blue, 60), text_size=textSize)
table.cell(mainTable, 1, 6, str.tostring(demandPercent, "#") + "% " + demandSymbol, text_color=color.white, bgcolor=demandBgColor, text_size=textSize)

// العرض (Supply)
supplyBgColor = supplyPercent > 55 ? color.new(color.red, 60) : color.new(color.gray, 60)
table.cell(mainTable, 0, 7, "عرض", text_color=color.white, bgcolor=color.new(color.blue, 60), text_size=textSize)
table.cell(mainTable, 1, 7, str.tostring(supplyPercent, "#") + "% " + supplySymbol, text_color=color.white, bgcolor=supplyBgColor, text_size=textSize)

// الأطر الزمنية
table.cell(mainTable, 0, 8, "3m", text_color=color.white, bgcolor=color.new(color.gray, 70), text_size=textSize)
table.cell(mainTable, 1, 8, trend3min, text

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.