PROTECTED SOURCE SCRIPT

vip

94
//version=5
indicator(" fmfm1 ", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500)

// ==============================
// | الإعدادات الأساسية
// ==============================
atrPeriod = input.int(10, "ATR Period", minval=1, group="Supertrend")
factor = input.float(3.0, "Supertrend Multiplier", minval=0.1, step=0.1, group="Supertrend")
rsiLength = input.int(14, "RSI Length", minval=2, group="RSI")
macdFast = input.int(12, "MACD Fast Length", minval=1, group="MACD")
macdSlow = input.int(26, "MACD Slow Length", minval=1, group="MACD")
macdSig = input.int(9, "MACD Signal Length", minval=1, group="MACD")
emaLen1 = input.int(20, "EMA 20 Length", group="EMA")
emaLen2 = input.int(50, "EMA 50 Length", group="EMA")
tablePos = input.string("top_right", "Table Position",
options=["top_left","top_right","bottom_left","bottom_right"], group="Display")

// إعدادات الصناديق
showBoxes = input.bool(true, "إظهار صناديق الإشارات", group="صناديق الإشارات")
boxTransparency = input.int(70, "شفافية الصندوق", minval=0, maxval=100, group="صناديق الإشارات")
boxHeight = input.float(0.15, "ارتفاع الصندوق %", minval=0.05, maxval=1.0, step=0.05, group="صناديق الإشارات")

// فلتر الشركات
enableFilter = input.bool(false, "تفعيل فلتر الشركات", group="فلتر الشركات")
symbol1 = input.string("", "الشركة 1", group="فلتر الشركات")
symbol2 = input.string("", "الشركة 2", group="فلتر الشركات")
symbol3 = input.string("", "الشركة 3", group="فلتر الشركات")
symbol4 = input.string("", "الشركة 4", group="فلتر الشركات")
symbol5 = input.string("", "الشركة 5", group="فلتر الشركات")
symbol6 = input.string("", "الشركة 6", group="فلتر الشركات")

// التنبيهات
enableAlerts = input.bool(true, "تفعيل التنبيهات", group="التنبيهات")
alertOnCall = input.bool(true, "تنبيه عند CALL", group="التنبيهات")
alertOnPut = input.bool(true, "تنبيه عند PUT", group="التنبيهات")

// إعدادات مناطق العرض والطلب
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)
enableStrengthAlert = input.bool(true, 'تفعيل تنبيهات القوة', group = 'Strength Settings')

// ==============================
// | حسابات Supertrend و المؤشرات
// ==============================
atrValue = ta.atr(atrPeriod)
hl2Value = (high + low) / 2
upperBand = hl2Value - factor * atrValue
lowerBand = hl2Value + factor * atrValue
var float trendLine = na
trendLine := close > nz(trendLine[1], hl2Value) ? math.max(upperBand, nz(trendLine[1], upperBand)) : math.min(lowerBand, nz(trendLine[1], lowerBand))
bull = close > trendLine
bear = close < trendLine
buySignal = ta.crossover(close, trendLine)
sellSignal = ta.crossunder(close, trendLine)

ema20 = ta.ema(close, emaLen1)
ema50 = ta.ema(close, emaLen2)
emaBull = ema20 > ema50
emaBear = ema20 < ema50

rsi = ta.rsi(close, rsiLength)
rsiBull = rsi > 50
rsiBear = rsi < 50

macd = ta.ema(close, macdFast) - ta.ema(close, macdSlow)
signal = ta.ema(macd, macdSig)
macdBull = macd > signal
macdBear = macd < signal

vwapValue = ta.vwap(close)
vwapBull = close > vwapValue
vwapBear = close < vwapValue

// الإشارات النهائية
allBull = (bull and rsiBull and macdBull and emaBull and vwapBull)
allBear = (bear and rsiBear and macdBear and emaBear and vwapBear)
finalSignal = allBull ? "CALL " : allBear ? "PUT " :" NEUTRAL"
finalBg = allBull ? color.new(color.green, 0) : allBear ? color.new(color.red, 0) : color.new(color.orange, 0)

// حفظ الحالة السابقة للإشارات
var bool wasCall = false
var bool wasPut = false

// اكتشاف إشارة CALL جديدة
newCallSignal = allBull and not wasCall
// اكتشاف إشارة PUT جديدة
newPutSignal = allBear and not wasPut

// تحديث الحالة
wasCall := allBull
wasPut := allBear

// ==============================
// | Labels للإشارات الجديدة - تم تعطيلها
// ==============================
// تم إزالة Labels CALL/PUT من فوق وتحت الشموع

// ==============================
// | التنبيهات
// ==============================
if enableAlerts
if alertOnCall and newCallSignal
alert("🔔 إشارة CALL على " + syminfo.ticker + " | السعر: " + str.tostring(close, format.mintick), alert.freq_once_per_bar)

if alertOnPut and newPutSignal
alert("🔔 إشارة PUT على " + syminfo.ticker + " | السعر: " + str.tostring(close, format.mintick), alert.freq_once_per_bar)

// ==============================
// | لوحة المعلومات
// ==============================
var table dash = table.new(position=tablePos, columns=2, rows=9, border_width=1)

if barstate.islast
table.cell(dash, 0, 0, "Ind", text_color=color.white, bgcolor=color.blue, text_size=size.tiny)
table.cell(dash, 1, 0, "Sig", text_color=color.white, bgcolor=color.blue, text_size=size.tiny)

table.cell(dash, 0, 1, "Sup", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 1, buySignal ? "BUY" : sellSignal ? "SELL" : bull ? "UP" : "DN",
text_color=color.white,
bgcolor= buySignal ? color.new(color.green, 0) : sellSignal ? color.new(color.red, 0) : bull ? color.new(color.green, 0) : color.new(color.red, 0),
text_size=size.tiny)

table.cell(dash, 0, 2, "EMA", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 2, emaBull ? "UP" : "DN", text_color=color.white,
bgcolor=emaBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)

table.cell(dash, 0, 3, "RSI", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 3, rsiBull ? "UP" : "DN", text_color=color.white,
bgcolor=rsiBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)

table.cell(dash, 0, 4, "MACD", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 4, macdBull ? "UP" : "DN", text_color=color.white,
bgcolor=macdBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)

table.cell(dash, 0, 5, "VWAP", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 5, vwapBull ? "UP" : "DN", text_color=color.white,
bgcolor=vwapBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)

table.cell(dash, 0, 6, "دخول", text_color=color.yellow, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 6, finalSignal, text_color=color.white, bgcolor=finalBg, text_size=size.tiny)

table.cell(dash, 0, 7, "Price", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 7, str.tostring(close, format.mintick), text_color=color.white, bgcolor=color.gray, text_size=size.tiny)


// ==============================
// | رسم المؤشرات
// ==============================
plot(trendLine, "Supertrend", color=bull ? color.green : color.red, linewidth=2)
plot(ema20, "EMA 20", color=color.blue, linewidth=1)

// ==============================
// | مناطق العرض والطلب
// ==============================

// أنواع البيانات
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 trendZZ = 1
atrOB = ta.atr(14)

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

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

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

// دالة حساب نسبة القوة
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 - atrOB * 0.30,
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 + atrOB * 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.tiny)

newOrderblock.demandLabel := label.new(
x = time,
y = newOrderblock.value - atrOB * 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.tiny)

if enableStrengthAlert 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 + atrOB * 0.12,
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 - atrOB * 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.tiny)

if enableStrengthAlert 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)







// ================= SETTINGS =================
paint_bars = input.bool(false, "Paint bars?", group="Bars Settings")
catch_flat = input.bool(false, "Try to catch flat?", group="Bars Settings")
uptrend_colour = input.color(color.rgb(13,247,20), "Uptrend colour", group="Bars Settings")
downtrend_colour = input.color(color.rgb(250,10,10), "Downtrend colour", group="Bars Settings")
neutraltrend_colour = input.color(color.rgb(245,252,252), "Neutral colour", group="Bars Settings")

// ================= TABLE SETTINGS =================
show_header = input(false, "Show header?", group="Table Settings")
show_ema_value = input(false, "Show EMA value?", group="Table Settings")
dashboard_position = input.string("Middle right", "Position", options=["Top right", "Bottom right", "Top left", "Bottom left", "Top center", "Bottom center", "Middle right"], group="Table Settings")
text_color = input.color(color.white, "Text colour", group="Table Settings")
table_color = input.color(color.rgb(240,249,250), "Border colour", group="Table Settings")

uptrend_indicator = input.string("🟢", "Uptrend indicator", group="Table Settings")
downtrend_indicator = input.string("🔴", "Downtrend indicator", group="Table Settings")
neutraltrend_indicator = input.string("🟡", "Neutral indicator", group="Table Settings")

header_bg_color = input.color(color.rgb(18,18,18,75), "Header background", group="Table Settings")
uptrend_bg_color = input.color(color.new(color.green,90), "Up BG", group="Table Settings")
downtrend_bg_color = input.color(color.new(color.red,90), "Down BG", group="Table Settings")
neutraltrend_bg_color = input.color(color.new(color.yellow,90), "Neutral BG", group="Table Settings")

// ================= EMA SETTINGS =================
trend_identification_approach = input.string("Direction of a single EMA", "Trend approach", options=["Direction of a single EMA", "Comparison of the two EMAs"], group="EMA Settings")
ema1_length = input.int(50, "EMA length", minval=1, maxval=800, group="EMA Settings")
ema2_length = input.int(200, "Additional EMA length", minval=20, maxval=800, group="EMA Settings")

// ================= TIMEFRAMES =================
show_3m = input(true, "Show 3m", group="Timeframe Settings")
show_5m = input(true, "Show 5m", group="Timeframe Settings")
show_15m = input(true, "Show 15m", group="Timeframe Settings")
show_1h = input(true, "Show 1h", group="Timeframe Settings")
show_4h = input(true, "Show 4h", group="Timeframe Settings")

// ================= TABLE CREATION =================
var table_position = switch dashboard_position
"Top left" => position.top_left
"Top right" => position.top_right
"Bottom left" => position.bottom_left
"Bottom right" => position.bottom_right
"Top center" => position.top_center
"Bottom center" => position.bottom_center
"Middle right" => position.middle_right
=> position.middle_right

// جدول صغير جدًا جدًا
var t = table.new(position=table_position, columns=3, rows=20, frame_color=table_color, frame_width=0, border_color=table_color, border_width=0)

// ================= FUNCTIONS =================
calc_smma(src, len) =>
var float smma = na
smma := na(smma) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len
smma

calc_zlema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema1 + (ema1 - ema2)

check_impulse() =>
hi = calc_smma(high, 34)
lo = calc_smma(low, 34)
mi = calc_zlema(hlc3, 34)
md = (mi > hi ? mi - hi : mi < lo ? mi - lo : 0)
sb = ta.sma(md, 9)
sh = md - sb
sh != 0

get_trend_status() =>
impulse = catch_flat ? check_impulse() : true
ema1_current = ta.ema(close, ema1_length)
ema1_prev = ema1_current[1]
ema2_current = ta.ema(close, ema2_length)
ema2_prev = ema2_current[1]
if trend_identification_approach == "Direction of a single EMA"
bg = not impulse ? neutraltrend_bg_color : ema1_current > ema1_prev ? uptrend_bg_color : ema1_current < ema1_prev ? downtrend_bg_color : neutraltrend_bg_color
ind = not impulse ? neutraltrend_indicator : ema1_current > ema1_prev ? uptrend_indicator : ema1_current < ema1_prev ? downtrend_indicator : neutraltrend_indicator
[ema1_current, bg, ind]
else
bg = not impulse ? neutraltrend_bg_color : ema1_current > ema2_current ? uptrend_bg_color : ema1_current < ema2_current ? downtrend_bg_color : neutraltrend_bg_color
ind = not impulse ? neutraltrend_indicator : ema1_current > ema2_current ? uptrend_indicator : ema1_current < ema2_current ? downtrend_indicator : neutraltrend_indicator
[ema1_current, bg, ind]

// ================= TREND REQUESTS =================
[ema_3m, bg_3m, ind_3m] = request.security(syminfo.tickerid, "3", get_trend_status())
[ema_5m, bg_5m, ind_5m] = request.security(syminfo.tickerid, "5", get_trend_status())
[ema_15m, bg_15m, ind_15m] = request.security(syminfo.tickerid, "15", get_trend_status())
[ema_1h, bg_1h, ind_1h] = request.security(syminfo.tickerid, "60", get_trend_status())
[ema_4h, bg_4h, ind_4h] = request.security(syminfo.tickerid, "240", get_trend_status())

// ================= SMALL TABLE =================
if barstate.islast
tiny = size.tiny
if show_header
table.cell(t, 0, 0, "TF", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)
table.cell(t, 1, 0, "Trend", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)
if show_ema_value
table.cell(t, 2, 0, "EMA", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)

if show_3m
table.cell(t, 0, 1, "3m", text_color=text_color, text_size=tiny, bgcolor=bg_3m)
table.cell(t, 1, 1, ind_3m, text_color=text_color, text_size=tiny, bgcolor=bg_3m)
if show_5m
table.cell(t, 0, 2, "5m", text_color=text_color, text_size=tiny, bgcolor=bg_5m)
table.cell(t, 1, 2, ind_5m, text_color=text_color, text_size=tiny, bgcolor=bg_5m)
if show_15m
table.cell(t, 0, 3, "15m", text_color=text_color, text_size=tiny, bgcolor=bg_15m)
table.cell(t, 1, 3, ind_15m, text_color=text_color, text_size=tiny, bgcolor=bg_15m)
if show_1h
table.cell(t, 0, 4, "1h", text_color=text_color, text_size=tiny, bgcolor=bg_1h)
table.cell(t, 1, 4, ind_1h, text_color=text_color, text_size=tiny, bgcolor=bg_1h)
if show_4h
table.cell(t, 0, 5, "4h", text_color=text_color, text_size=tiny, bgcolor=bg_4h)
table.cell(t, 1, 5, ind_4h, text_color=text_color, text_size=tiny, bgcolor=bg_4h)

















// --- إعدادات الإدخال ---
string GRP_SETTINGS = "الإعدادات"
var bool showTable = input.bool(true, "إظهار جدول التحليل", group=GRP_SETTINGS)
var int lookbackPeriod = input.int(5, "فترة التحليل (أشرطة)", minval=5, maxval=100, group=GRP_SETTINGS)
var int maxBarsDisplay = input.int(5, "أقصى عدد أشرطة مرئية", minval=5, maxval=20, group=GRP_SETTINGS)
var color buyColor = input.color(color.new(#00C853, 0), "لون الشراء", group=GRP_SETTINGS)
var color sellColor = input.color(color.new(#FF1744, 0), "لون البيع", group=GRP_SETTINGS)
var string tablePosition = input.string("Top-Right", "موضع الجدول", options=["Top-Right", "Top-Left", "Bottom-Right", "Bottom-Left"], group=GRP_SETTINGS)

// --- متغيرات الحالة ---
var float[] volumes = array.new_float(0)
var float[] buyVolumes = array.new_float(0)
var float[] sellVolumes = array.new_float(0)
var float[] netFlows = array.new_float(0)
var float[] priceChanges = array.new_float(0)
var float[] highs = array.new_float(0)
var float[] lows = array.new_float(0)
var float[] opens = array.new_float(0)
var float[] closes = array.new_float(0)
var table trendTable = na

// --- دالة بناء الشريط البصري ---
f_buildBar(int filled, int total) =>
string result = ""
for i = 1 to total
result += i <= filled ? "█" : "░"
result

// --- جمع البيانات ---
if barstate.isconfirmed
float h = high
float l = low
float o = open
float c = close
float v = volume
float prevClose = nz(close[1], c)
float priceChange = c - prevClose
float priceRange = math.max(h - l, syminfo.mintick)
float buyV = v * (c - l) / priceRange
float sellV = v * (h - c) / priceRange
float netFlow = buyV - sellV

if array.size(volumes) >= lookbackPeriod
array.shift(volumes)
array.shift(buyVolumes)
array.shift(sellVolumes)
array.shift(netFlows)
array.shift(priceChanges)
array.shift(highs)
array.shift(lows)
array.shift(opens)
array.shift(closes)
array.push(volumes, v)
array.push(buyVolumes, buyV)
array.push(sellVolumes, sellV)
array.push(netFlows, netFlow)
array.push(priceChanges, priceChange)
array.push(highs, h)
array.push(lows, l)
array.push(opens, o)
array.push(closes, c)

// --- منطق الجدول ---
if showTable and array.size(volumes) >= lookbackPeriod
// === 1. الاتجاه ===
float totalVol = array.sum(volumes)
float totalBuyVol = array.sum(buyVolumes)
float totalSellVol = array.sum(sellVolumes)
float buyPerc = totalVol > 0 ? (totalBuyVol / totalVol) * 100 : 0
float sellPerc = totalVol > 0 ? (totalSellVol / totalVol) * 100 : 0
float diffPerc = buyPerc - sellPerc
string diffText = str.tostring(math.abs(diffPerc), "#.##") + "%"
int filledBars = int(math.round((math.abs(diffPerc) / 100) * maxBarsDisplay))
string visualBar = f_buildBar(filledBars, maxBarsDisplay)
color barColor = totalBuyVol > totalSellVol ? buyColor : sellColor

// === 2. الديناميكية ===
float meanFlow = array.avg(netFlows)
float stdFlow = array.stdev(netFlows)
float skew = 0.0
if stdFlow > 1e-10
for i = 0 to array.size(netFlows) - 1
float z = (array.get(netFlows, i) - meanFlow) / stdFlow
skew += math.pow(z, 3)
skew /= array.size(netFlows)
float skew_norm = math.max(-1, math.min(1, skew / 2))

float pBuy = totalBuyVol / totalVol
float pSell = totalSellVol / totalVol
pBuy := math.max(pBuy, 1e-10)
pSell := math.max(pSell, 1e-10)
float entropy = -(pBuy * math.log(pBuy) + pSell * math.log(pSell))
float normEntropy = entropy / math.log(2)
float entropy_score = 1 - normEntropy

float sumX = array.sum(priceChanges)
float sumY = array.sum(netFlows)
float sumXY = 0.0, sumX2 = 0.0, sumY2 = 0.0
int n = array.size(priceChanges)
for i = 0 to n - 1
float x = array.get(priceChanges, i)
float y = array.get(netFlows, i)
sumXY += x * y
sumX2 += x * x
sumY2 += y * y
float numerator = n * sumXY - sumX * sumY
float denominator = math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY))
float corr = denominator != 0 ? numerator / denominator : 0.0

float signal = math.abs(totalBuyVol - totalSellVol)
float noise = totalVol - signal
float snr = signal / (noise + 1e-10)
float snr_norm = math.min(1, snr / 3)

float dynamicScore = (skew_norm + entropy_score + corr + snr_norm) / 4
float finalPerc = (dynamicScore + 1) * 50
int filledDynamicBars = int(math.round(finalPerc / 100 * maxBarsDisplay))
string dynamicBar = f_buildBar(filledDynamicBars, maxBarsDisplay)
color dynamicColor = finalPerc > 50 ? buyColor : sellColor

// === 3. السلوك ===
float controlSum = 0.0
float reactionSum = 0.0
float closeDomSum = 0.0
int upBars = 0
int totalBars = array.size(closes)

for i = 0 to totalBars - 1
float h_i = array.get(highs, i)
float l_i = array.get(lows, i)
float o_i = array.get(opens, i)
float c_i = array.get(closes, i)
float v_i = array.get(volumes, i)
float range_i = math.max(h_i - l_i, syminfo.mintick)

controlSum += (c_i - l_i) / range_i
reactionSum += v_i / range_i
closeDomSum += math.abs(c_i - o_i) / range_i
if c_i > o_i
upBars += 1

float controlScore = controlSum / float(totalBars)
float volumeBiasScore = float(upBars) / float(totalBars)
float reactionAvg = reactionSum / float(totalBars)
float reactionScore = reactionAvg / math.max(ta.highest(reactionAvg, math.max(lookbackPeriod * 2, 10)), 1e-10)
reactionScore := math.min(1.0, reactionScore)
float closeDominanceScore = closeDomSum / float(totalBars)

float behaviorScore = (controlScore + volumeBiasScore + reactionScore + closeDominanceScore) / 4.0
float behaviorPerc = math.min(100.0, math.max(0.0, behaviorScore * 100.0))
int filledBehaviorBars = int(math.round(behaviorPerc / 100.0 * maxBarsDisplay))
string behaviorBar = f_buildBar(filledBehaviorBars, maxBarsDisplay)
color behaviorColor = behaviorPerc > 50 ? buyColor : sellColor

// === إنشاء الجدول (2 عمود، 4 صفوف) ===
if na(trendTable)
if tablePosition == "Top-Right"
trendTable := table.new(position.top_right, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else if tablePosition == "Top-Left"
trendTable := table.new(position.top_left, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else if tablePosition == "Bottom-Right"
trendTable := table.new(position.bottom_right, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else
trendTable := table.new(position.bottom_left, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)

// === الصف 1: الاتجاه ===
table.cell(trendTable, 0, 1, "الاتجاه", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 1, diffText + " | " + visualBar, text_color=barColor, bgcolor=color.new(barColor, 80))

// === الصف 2: الديناميكية ===
table.cell(trendTable, 0, 2, "الديناميكية", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 2, str.tostring(finalPerc, "#.##") + "% | " + dynamicBar, text_color=dynamicColor, bgcolor=color.new(dynamicColor, 80))

// === الصف 3: السلوك ===
table.cell(trendTable, 0, 3, "السلوك", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 3, str.tostring(behaviorPerc, "#.##") + "% | " + behaviorBar, text_color=behaviorColor, bgcolor=color.new(behaviorColor, 80))







FPeriod = input(35, title='Fibo Period')
plotF1618 = input(title='Plot 1.618 Level?', defval=true)
Fhigh = ta.highest(FPeriod)
Flow = ta.lowest(FPeriod)
FH = ta.highestbars(high, FPeriod)
FL = ta.lowestbars(low, FPeriod)
downfibo = FH < FL

// تصغير حجم الإشارات مع الحفاظ على النص
plotshape(Flow, style=shape.labelup, location=location.absolute, size=size.tiny,
color=color.new(#000000, 40), textcolor=color.new(#c7c9d0, 0), show_last=1, text="🟢", offset=FL)
plotshape(Fhigh, style=shape.labeldown, location=location.absolute, size=size.tiny,
color=color.new(#000000, 30), textcolor=color.new(#e3e5e8, 0), show_last=1, text="🔴", offset=FH)






// === Inputs ===
trendLineLength = input.int(10, 'Trend Line Detection Sensitivity', minval=10)
upTlColor = input.color(color.new(color.teal, 15), title='Trend Line Colors', inline='tl')
downTlColor = input.color(color.new(color.red, 15), title=' ', inline='tl')
showTrendLines = input.bool(true, 'Show Trend Lines')

// === Helper Functions ===
extendTrendline(lineId, startIndex, startValue, endIndex, endValue) =>
slope = (endValue - startValue) / (endIndex - startIndex)
newEndIndex = bar_index
newEndValue = startValue + slope * (newEndIndex - startIndex)
line.set_x2(lineId, newEndIndex)
line.set_y2(lineId, newEndValue)

getSlope(startIndex, startValue, endIndex, endValue) =>
(endValue - startValue) / (endIndex - startIndex)

// === Trendlines Calculation ===
var line newBearishTrendline = na
var line newBullishTrendline = na

if showTrendLines
phTrend = ta.pivothigh(high, trendLineLength, trendLineLength)
plTrend = ta.pivotlow(low, trendLineLength, trendLineLength)

bullishTrendLineStart = ta.valuewhen(not na(plTrend), bar_index[trendLineLength], 1)
bullishTrendLineEnd = ta.valuewhen(not na(plTrend), bar_index[trendLineLength], 0)
bearishTrendLineStart = ta.valuewhen(not na(phTrend), bar_index[trendLineLength], 1)
bearishTrendLineEnd = ta.valuewhen(not na(phTrend), bar_index[trendLineLength], 0)

bullishTrendLineStartVal = ta.valuewhen(not na(plTrend), low[trendLineLength], 1)
bullishTrendLineEndVal = ta.valuewhen(not na(plTrend), low[trendLineLength], 0)
bearishTrendLineStartVal = ta.valuewhen(not na(phTrend), high[trendLineLength], 1)
bearishTrendLineEndVal = ta.valuewhen(not na(phTrend), high[trendLineLength], 0)

line.delete(newBearishTrendline)
line.delete(newBullishTrendline)

slopeBearish = getSlope(bearishTrendLineStart, bearishTrendLineStartVal, bearishTrendLineEnd, bearishTrendLineEndVal)
slopeBullish = getSlope(bullishTrendLineStart, bullishTrendLineStartVal, bullishTrendLineEnd, bullishTrendLineEndVal)

if slopeBearish < 0
newBearishTrendline := line.new(x1=bearishTrendLineStart, y1=bearishTrendLineStartVal, x2=bar_index, y2=bearishTrendLineEndVal, xloc=xloc.bar_index, color=downTlColor, width=2)

if slopeBullish > 0
newBullishTrendline := line.new(x1=bullishTrendLineStart, y1=bullishTrendLineStartVal, x2=bar_index, y2=bullishTrendLineEndVal, xloc=xloc.bar_index, color=upTlColor, width=2)

if not na(newBearishTrendline)
extendTrendline(newBearishTrendline, bearishTrendLineStart, bearishTrendLineStartVal, bearishTrendLineEnd, bearishTrendLineEndVal)

if not na(newBullishTrendline)
extendTrendline(newBullishTrendline, bullishTrendLineStart, bullishTrendLineStartVal, bullishTrendLineEnd, bullishTrendLineEndVal)












// ========== إعدادات 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 = 30, 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)








//----------------------------------------
// Key Levels - 4H Only
//----------------------------------------
Show_4H_Levels = input.bool(defval=true, title='عرض مستويات 4H', group='Key Levels')
Color_Resistance = input.color(title='لون المقاومة', defval=color.green, group='Key Levels', inline='colors')
Color_Support = input.color(title='لون الدعم', defval=color.red, group='Key Levels', inline='colors')
Style_4H_Levels = input.string('Dotted', 'نمط الخطوط', ['Solid', 'Dashed', 'Dotted'], group="Key Levels")
Text_4H_Levels = input.bool(defval=false, title='نص مختصر', group='Key Levels')
labelsize = input.string(defval='Medium', title='حجم النص', options=['Small', 'Medium', 'Large'], group = "Key Levels")

// تعديل مستويات الدعم والمقاومة
Resistance_Offset = input.float(defval=0.0, title='تعديل المقاومة (نقاط)', step=0.01, group='تعديل المستويات', tooltip='رفع (+) أو خفض (-) مستوى المقاومة بالنقاط')
Support_Offset = input.float(defval=0.0, title='تعديل الدعم (نقاط)', step=0.01, group='تعديل المستويات', tooltip='رفع (+) أو خفض (-) مستوى الدعم بالنقاط')

// إعدادات خط المنتصف
Show_Middle_Line = input.bool(defval=true, title='عرض خط المنتصف', group='"0"')
Color_Middle = input.color(title='لون خط المنتصف', defval=color.blue, group='Key Levels')

//----------------------------------------
// Targets Settings
//----------------------------------------
Show_Targets = input.bool(defval=true, title='إظهار الأهداف', group='إعدادات الأهداف')

// أهداف صاعدة (بعد اختراق المقاومة)
Target1_Up_Distance = input.float(defval=0.5, title='المسافة للهدف الأول %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target1_Up = input.color(title='لون الهدف الأول', defval=color.new(color.lime, 40), group='أهداف الاختراق (صعود)')

Target2_Up_Distance = input.float(defval=1.0, title='المسافة للهدف الثاني %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target2_Up = input.color(title='لون الهدف الثاني', defval=color.new(color.lime, 20), group='أهداف الاختراق (صعود)')

Target3_Up_Distance = input.float(defval=1.5, title='المسافة للهدف الثالث %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target3_Up = input.color(title='لون الهدف الثالث', defval=color.lime, group='أهداف الاختراق (صعود)')

// أهداف هابطة (بعد كسر الدعم)
Target1_Down_Distance = input.float(defval=0.5, title='المسافة للهدف الأول %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target1_Down = input.color(title='لون الهدف الأول', defval=color.new(color.fuchsia, 40), group='أهداف الكسر (هبوط)')

Target2_Down_Distance = input.float(defval=1.0, title='المسافة للهدف الثاني %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target2_Down = input.color(title='لون الهدف الثاني', defval=color.new(color.fuchsia, 20), group='أهداف الكسر (هبوط)')

Target3_Down_Distance = input.float(defval=1.5, title='المسافة للهدف الثالث %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target3_Down = input.color(title='لون الهدف الثالث', defval=color.fuchsia, group='أهداف الكسر (هبوط)')

Style_Targets = input.string('Dashed', 'نمط خطوط الأهداف', ['Solid', 'Dashed', 'Dotted'], group="إعدادات الأهداف")

//----------------------------------------
// Signal Settings
//----------------------------------------
Show_Signals = input.bool(defval=true, title='إظهار إشارات البيع والشراء', group='إعدادات الإشارات')
Signal_Size = input.string(defval='Normal', title='حجم الإشارة', options=['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group='إعدادات الإشارات')
Color_Buy_Signal = input.color(title='لون إشارة الشراء', defval=color.new(color.lime, 0), group='إعدادات الإشارات')
Color_Sell_Signal = input.color(title='لون إشارة البيع', defval=color.new(color.red, 0), group='إعدادات الإشارات')

//----------------------------------------
// FVG Settings
//----------------------------------------
Show_FVG = input.bool(defval=true, title='إظهار FVG', group='إعدادات FVG')
FVG_Lookback = input.int(defval=10, title='عدد الشموع للبحث عن FVG', minval=3, maxval=50, group='إعدادات FVG')
Color_Bullish_FVG = input.color(title='لون FVG الصاعد', defval=color.new(color.lime, 80), group='إعدادات FVG')
Color_Bearish_FVG = input.color(title='لون FVG الهابط', defval=color.new(color.red, 80), group='إعدادات FVG')
FVG_Border_Color = input.color(title='لون إطار FVG', defval=color.new(color.gray, 50), group='إعدادات FVG')

//========================================
// HELPER FUNCTIONS
//========================================

// Format price display
formatPrice(float price) =>
str.tostring(price, format.mintick)

// Get signal size
getSignalSize(string size_str) =>
switch size_str
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
=> size.normal

// Get line style
getLineStyle(string x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
=> line.style_solid

// Get font size
getFontSize(string size_str) =>
switch size_str
'Small' => size.small
'Medium' => size.normal
'Large' => size.large
=> size.normal

// Detect Bullish FVG
detectBullishFVG(int lookback) =>
float fvg_top = na
float fvg_bottom = na
int fvg_left = na

if bar_index >= 3
int max_bars = math.min(lookback, bar_index - 2)
for i = 1 to max_bars
if bar_index >= i + 1
if low[i-1] > high[i+1]
fvg_top := low[i-1]
fvg_bottom := high[i+1]
fvg_left := bar_index - i
break
[fvg_top, fvg_bottom, fvg_left]

// Detect Bearish FVG
detectBearishFVG(int lookback) =>
float fvg_top = na
float fvg_bottom = na
int fvg_left = na

if bar_index >= 3
int max_bars = math.min(lookback, bar_index - 2)
for i = 1 to max_bars
if bar_index >= i + 1
if high[i-1] < low[i+1]
fvg_top := low[i+1]
fvg_bottom := high[i-1]
fvg_left := bar_index - i
break
[fvg_top, fvg_bottom, fvg_left]

// Extend line to current bar
extendToCurrentBar(int offset_bars) =>
timenow + (time - time[1]) * offset_bars

//========================================
// MAIN CALCULATIONS
//========================================

// Get 4H levels
[intrah_time, intrah_value] = request.security(syminfo.tickerid, '240', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time, intral_value] = request.security(syminfo.tickerid, '240', [time[1], low[1]], lookahead=barmerge.lookahead_on)

// Apply offsets to levels
float adjusted_resistance = intrah_value + Resistance_Offset
float adjusted_support = intral_value + Support_Offset

// Text labels
string resistance_text = Text_4H_Levels ? 'كول' : 'مقاومة'
string support_text = Text_4H_Levels ? 'بوت' : 'دعم'

// Style settings
int line_width = 1
string font_size = getFontSize(labelsize)
string line_style = getLineStyle(Style_4H_Levels)
string target_style = getLineStyle(Style_Targets)
int distance_right = 25

//========================================
// BREAKOUT DETECTION & TRACKING
//========================================

var bool resistance_broken = false
var bool support_broken = false
var float last_resistance = na
var float last_support = na
var int buy_signal_bar = na
var int sell_signal_bar = na
var float buy_signal_price = na
var float sell_signal_price = na

// Detect resistance breakout
if close > adjusted_resistance and not resistance_broken
resistance_broken := true
support_broken := false
last_resistance := adjusted_resistance
buy_signal_bar := bar_index
buy_signal_price := adjusted_resistance

// Detect support breakdown
if close < adjusted_support and not support_broken
support_broken := true
resistance_broken := false
last_support := adjusted_support
sell_signal_bar := bar_index
sell_signal_price := adjusted_support

// Cancel breakout if price returns
if close < adjusted_resistance and resistance_broken
resistance_broken := false
buy_signal_bar := na
buy_signal_price := na

if close > adjusted_support and support_broken
support_broken := false
sell_signal_bar := na
sell_signal_price := na

// Reset on new level formation
if adjusted_resistance != last_resistance
resistance_broken := false
last_resistance := adjusted_resistance
buy_signal_bar := na
buy_signal_price := na

if adjusted_support != last_support
support_broken := false
last_support := adjusted_support
sell_signal_bar := na
sell_signal_price := na

//========================================
// DRAWING - SUPPORT & RESISTANCE LEVELS
//========================================

if barstate.islast and Show_4H_Levels
int right_extension = extendToCurrentBar(distance_right)

// Draw Resistance Line
var line resistance_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Resistance, width=line_width, style=line_style)
line.set_xy1(resistance_line, intrah_time, adjusted_resistance)
line.set_xy2(resistance_line, right_extension, adjusted_resistance)
line.set_color(resistance_line, Color_Resistance)

var label resistance_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Resistance, size=font_size)
label.set_xy(resistance_label, right_extension, adjusted_resistance)
label.set_text(resistance_label, formatPrice(adjusted_resistance) + " " + resistance_text)
label.set_textcolor(resistance_label, Color_Resistance)

// Draw Support Line
var line support_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Support, width=line_width, style=line_style)
line.set_xy1(support_line, intral_time, adjusted_support)
line.set_xy2(support_line, right_extension, adjusted_support)
line.set_color(support_line, Color_Support)

var label support_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Support, size=font_size)
label.set_xy(support_label, right_extension, adjusted_support)
label.set_text(support_label, formatPrice(adjusted_support) + " " + support_text)
label.set_textcolor(support_label, Color_Support)

// Draw Middle Line
if Show_Middle_Line
float middle_price = (adjusted_resistance + adjusted_support) / 2

var line middle_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Middle, width=line_width, style=line_style)
line.set_xy1(middle_line, intrah_time, middle_price)
line.set_xy2(middle_line, right_extension, middle_price)
line.set_color(middle_line, Color_Middle)

var label middle_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Middle, size=font_size)
label.set_xy(middle_label, right_extension, middle_price)
label.set_text(middle_label, formatPrice(middle_price) +"0")
label.set_textcolor(middle_label, Color_Middle)

//========================================
// DRAWING - BULLISH TARGETS & SIGNALS
//========================================

if barstate.islast and Show_Targets and resistance_broken
int right_extension = extendToCurrentBar(distance_right)

// Buy Signal
if Show_Signals and not na(buy_signal_bar)
var label buy_label = label.new(na, na, text="شراء\nBUY", style=label.style_label_up, color=Color_Buy_Signal, textcolor=color.white, size=getSignalSize(Signal_Size))
label.set_xy(buy_label, buy_signal_bar, buy_signal_price)
label.set_color(buy_label, Color_Buy_Signal)
label.set_size(buy_label, getSignalSize(Signal_Size))

// Bullish FVG Box
if Show_FVG
[bull_top, bull_bottom, bull_left] = detectBullishFVG(FVG_Lookback)
if not na(bull_top) and not na(bull_bottom) and not na(bull_left)
var box bull_box = box.new(na, na, na, na, xloc=xloc.bar_index, bgcolor=Color_Bullish_FVG, border_color=FVG_Border_Color, border_width=1)
box.set_lefttop(bull_box, bull_left, bull_top)
box.set_rightbottom(bull_box, bar_index, bull_bottom)
box.set_bgcolor(bull_box, Color_Bullish_FVG)
box.set_border_color(bull_box, FVG_Border_Color)

// Calculate Target Prices
float target1_price = adjusted_resistance * (1 + Target1_Up_Distance / 100)
float target2_price = adjusted_resistance * (1 + Target2_Up_Distance / 100)
float target3_price = adjusted_resistance * (1 + Target3_Up_Distance / 100)

// Target 1
var line t1_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target1_Up, width=2, style=target_style)
line.set_xy1(t1_line, intrah_time, target1_price)
line.set_xy2(t1_line, right_extension, target1_price)
line.set_color(t1_line, Color_Target1_Up)

var label t1_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target1_Up, size=size.small)
label.set_xy(t1_label, right_extension, target1_price)
label.set_text(t1_label, formatPrice(target1_price) + " ⬆ T1")
label.set_textcolor(t1_label, Color_Target1_Up)

// Target 2
var line t2_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target2_Up, width=2, style=target_style)
line.set_xy1(t2_line, intrah_time, target2_price)
line.set_xy2(t2_line, right_extension, target2_price)
line.set_color(t2_line, Color_Target2_Up)

var label t2_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target2_Up, size=size.small)
label.set_xy(t2_label, right_extension, target2_price)
label.set_text(t2_label, formatPrice(target2_price) + " ⬆ T2")
label.set_textcolor(t2_label, Color_Target2_Up)

// Target 3
var line t3_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target3_Up, width=2, style=target_style)
line.set_xy1(t3_line, intrah_time, target3_price)
line.set_xy2(t3_line, right_extension, target3_price)
line.set_color(t3_line, Color_Target3_Up)

var label t3_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target3_Up, size=size.small)
label.set_xy(t3_label, right_extension, target3_price)
label.set_text(t3_label, formatPrice(target3_price) + " ⬆ T3")
label.set_textcolor(t3_label, Color_Target3_Up)

//========================================
// DRAWING - BEARISH TARGETS & SIGNALS
//========================================

if barstate.islast and Show_Targets and support_broken
int right_extension = extendToCurrentBar(distance_right)

// Sell Signal
if Show_Signals and not na(sell_signal_bar)
var label sell_label = label.new(na, na, text="بيع\nSELL", style=label.style_label_down, color=Color_Sell_Signal, textcolor=color.white, size=getSignalSize(Signal_Size))
label.set_xy(sell_label, sell_signal_bar, sell_signal_price)
label.set_color(sell_label, Color_Sell_Signal)
label.set_size(sell_label, getSignalSize(Signal_Size))

// Bearish FVG Box
if Show_FVG
[bear_top, bear_bottom, bear_left] = detectBearishFVG(FVG_Lookback)
if not na(bear_top) and not na(bear_bottom) and not na(bear_left)
var box bear_box = box.new(na, na, na, na, xloc=xloc.bar_index, bgcolor=Color_Bearish_FVG, border_color=FVG_Border_Color, border_width=1)
box.set_lefttop(bear_box, bear_left, bear_top)
box.set_rightbottom(bear_box, bar_index, bear_bottom)
box.set_bgcolor(bear_box, Color_Bearish_FVG)
box.set_border_color(bear_box, FVG_Border_Color)

// Calculate Target Prices
float target1_price = adjusted_support * (1 - Target1_Down_Distance / 100)
float target2_price = adjusted_support * (1 - Target2_Down_Distance / 100)
float target3_price = adjusted_support * (1 - Target3_Down_Distance / 100)

// Target 1
var line t1_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target1_Down, width=2, style=target_style)
line.set_xy1(t1_down_line, intral_time, target1_price)
line.set_xy2(t1_down_line, right_extension, target1_price)
line.set_color(t1_down_line, Color_Target1_Down)

var label t1_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target1_Down, size=size.small)
label.set_xy(t1_down_label, right_extension, target1_price)
label.set_text(t1_down_label, formatPrice(target1_price) + " ⬇ T1")
label.set_textcolor(t1_down_label, Color_Target1_Down)

// Target 2
var line t2_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target2_Down, width=2, style=target_style)
line.set_xy1(t2_down_line, intral_time, target2_price)
line.set_xy2(t2_down_line, right_extension, target2_price)
line.set_color(t2_down_line, Color_Target2_Down)

var label t2_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target2_Down, size=size.small)
label.set_xy(t2_down_label, right_extension, target2_price)
label.set_text(t2_down_label, formatPrice(target2_price) + " ⬇ T2")
label.set_textcolor(t2_down_label, Color_Target2_Down)

// Target 3
var line t3_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target3_Down, width=2, style=target_style)
line.set_xy1(t3_down_line, intral_time, target3_price)
line.set_xy2(t3_down_line, right_extension, target3_price)
line.set_color(t3_down_line, Color_Target3_Down)

var label t3_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target3_Down, size=size.small)
label.set_xy(t3_down_label, right_extension, target3_price)
label.set_text(t3_down_label, formatPrice(target3_price) + " ⬇ T3")
label.set_textcolor(t3_down_label, Color_Target3_Down)














// ===== إعدادات =====

src = input.source(close, "Source")
anchor = input.string( "top_right", "موقع الجدول", options=["top_left", "top_right","bottom_left","bottom_right"])
v_step = input.int(0, "تحريك عمودي 0 أعلى .. 1 أسفل", minval=0, maxval=1)
h_step = input.int(0, "تحريك أفقي 0 يسار .. 1 يمين", minval=0, maxval=1)
size_step = input.int(1, "حجم الخط 0 صغير جدًا .. 5 كبير", minval=0, maxval=5)
show_table = input.bool(true, "إظهار الجدول؟")

// ===== حساب RSI =====
r = ta.rsi(src, rsiLength)

// ===== حساب Flow (عرض وطلب) كمثال =====
FlowUp = close > open
FlowDown = close < open
FlowText = FlowUp ? "🟢" : FlowDown ? "🔴" : "⚪"

// ===== ألوان RSI =====
bgColor = r > 56 ? color.green : (r < 44 ? color.red : color.gray)
numColor = color.white

// ===== حجم الخط =====
textSizes = array.from(size.tiny, size.small, size.normal, size.large, size.large, size.large)
tsize = array.get(textSizes, size_step)

// ===== إنشاء جدول مصغر جدًا 2x2 =====
var int grid = 2
pos = anchor == "top_right" ? position.top_right :
anchor == "top_left" ? position.top_left :
anchor == "bottom_right" ? position.bottom_right : position.bottom_left

var table tbl = table.new(pos, grid, grid, frame_width=0, frame_color=color.black)

// ===== تحديث الجدول =====
if show_table
cellText = "قوة:" + str.tostring(r, "#.0") + FlowText
for row = 0 to grid-1
for col = 0 to grid-1
if row == v_step and col == h_step
table.cell(tbl, row, col, text=cellText, text_color=numColor, bgcolor=bgColor, text_size=tsize)












// # ========================================================================= #
// # | Colors |
// # ========================================================================= #

//#region

// # Core -------------------------------------------------------------------- #

colors_orange = color.rgb(246, 255, 0)
colors_blue = color.rgb(243, 246, 246)
colors_aqua = color.rgb(237, 245, 12)
colors_red = color.red
colors_green = color.rgb(246, 246, 16)
colors_maroon = color.maroon
colors_purple = color.rgb(9, 94, 253)
colors_gray = color.rgb(250, 6, 6)
colors_transparent = color.new(color.white,100)

//#endregion

// # ========================================================================= #
// # | End |
// # ========================================================================= #











// # ========================================================================= #
// # | Inputs |
// # ========================================================================= #

//#region

// # General ----------------------------------------------------------------- #

general_font = input.string("Monospace", "Text                         ", options = ["Default", "Monospace"], inline = "5", group = "General")
general_text = input.string("Tiny", "", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "5", group = "General", tooltip = "Customize global text size and style")
general_brand_show = input.bool(false, "Hide Brand", group = "General")

// # LKZ --------------------------------------------------------------------- #

hl_daily = input.bool(true, "Day                  ", inline = "1", group = "HTF Levels")
hl_weekly = input.bool(false, "Week                ", inline = "2", group = "HTF Levels")
hl_monthly = input.bool(false, "Month               ", inline = "3", group = "HTF Levels")
hl_quartely = input.bool(false, "Quarter             ", inline = "4", group = "HTF Levels")
hl_yearly = input.bool(false, "Year                  ", inline = "5", group = "HTF Levels")
hl_css_daily = input.color(colors_blue, "", inline = "1", group = "HTF Levels")
hl_css_weekly = input.color(colors_green, "", inline = "2", group = "HTF Levels")
hl_css_monthly = input.color(colors_purple, "", inline = "3", group = "HTF Levels")
hl_css_quaterly = input.color(colors_maroon, "", inline = "4", group = "HTF Levels")
hl_css_yearly = input.color(colors_gray, "", inline = "5", group = "HTF Levels")
hl_line_daily = input.string('⎯⎯⎯', '', inline = '1', group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'])
hl_line_weekly = input.string('⎯⎯⎯', '', inline = '2', group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'])
hl_line_monthly = input.string('⎯⎯⎯', '', inline = '3', group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'])
hl_line_quaterly = input.string('⎯⎯⎯', '', inline = '4', group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'])
hl_line_yearly = input.string('⎯⎯⎯', '', inline = '5', group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'])
hl_line_width_daily = input.int(1, '', inline = '1', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_weekly = input.int(1, '', inline = '2', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_monthly = input.int(1, '', inline = '3', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_quaterly = input.int(1, '', inline = '4', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_yearly = input.int(1, '', inline = '5', group = "HTF Levels", minval = 1, maxval = 5)
hl_midline = input.bool(true, "Show Average    ", inline = "6" , group = "HTF Levels")
hl_midline_css = input.color(colors_aqua, "", inline = "6", group = "HTF Levels")
hl_midline_type = input.string("----", "", inline = "6", group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'], tooltip = "Show highs & lows mid-line")
hl_midline_width = input.int(1, "", inline = "6", group = "HTF Levels", tooltip = "Change mid-line highs & lows width")
hl_openline = input.bool(true, "Show Open        ", inline = "7" , group = "HTF Levels")
hl_openline_css = input.color(colors_orange, "", inline = "7", group = "HTF Levels")
hl_openline_type = input.string("····", "", inline = "7", group = "HTF Levels", options = ['⎯⎯⎯', '----', '····'], tooltip = "Show highs & lows mid-line")
hl_openline_width = input.int(1, "", inline = "7", group = "HTF Levels", tooltip = "Change mid-line highs & lows width")

//#endregion

// # ========================================================================= #
// # | End |
// # ========================================================================= #











// # ========================================================================= #
// # | UDTs |
// # ========================================================================= #

//#region

type UDT_Store
line [] hl_ln
label [] hl_lbl

type UDT_MTF
int x1 = na
int x2 = na
float y1 = na
float y2 = na

type UDT_HTF_Candle
string tf
// real coordinates of HTF candle
float o
float c
float h
float l
int ot
int ct
int ht
int lt
bool bull

//#endregion

// # ========================================================================= #
// # | End |
// # ========================================================================= #











// # ========================================================================= #
// # | Functions |
// # ========================================================================= #

//#region

method text_size(string size) =>
out = switch size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
out

method line_style(string line) =>
out = switch line
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted

method font_style(string font) =>
out = switch font
'Default' => font.family_default
'Monospace' => font.family_monospace

shift_to_right(int current, int length, string tf) =>
current + timeframe.in_seconds(tf) * 1000 * (length + 1)

shift_to_left(int current, int prev, int length) =>
current - (current - prev) * length + 1

shift_bars_to_right(int bars) =>
bars + 20

//#endregion

// # ========================================================================= #
// # | End |
// # ========================================================================= #











// # ========================================================================= #
// # | Store |
// # ========================================================================= #

//#region

var UDT_Store bin = UDT_Store.new(hl_ln = array.new<line>(), hl_lbl = array.new<label>())

method clean_hl(UDT_Store store) =>
for obj in store.hl_ln
obj.delete()
for obj in store.hl_lbl
obj.delete()

store.hl_ln.clear()
store.hl_lbl.clear()

//#endregion

// # ========================================================================= #
// # | End |
// # ========================================================================= #











// # ========================================================================= #
// # | Highs & Lows MTF |
// # ========================================================================= #

//#region

method draw_pivots_ol_line(UDT_MTF mtf) =>
ol = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = hl_openline_css
, style = line_style(hl_openline_type)
, width = hl_openline_width
)
bin.hl_ln.push(ol)
mtf

method draw_pivots_hl_line(UDT_MTF mtf, color css, string pdhl_style, int line_width) =>
hl = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = css
, style = line_style(pdhl_style)
, width = line_width
)
bin.hl_ln.push(hl)
mtf

method draw_pivots_mid_line(UDT_MTF mtf) =>
ml = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = hl_midline_css
, style = line_style(hl_midline_type)
, width = hl_midline_width
)
bin.hl_ln.push(ml)
mtf

method draw_pivots_ll_line(UDT_MTF mtf, color css, string pdhl_style, int line_width) =>
ll = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = css
, style = line_style(pdhl_style)
, width = line_width
)
bin.hl_ln.push(ll)
mtf

method draw_pivots_label(UDT_MTF mtf, string fmt, string tf, color css) =>
lbl = label.new(
x = mtf.x2
, y = mtf.y2
, xloc = xloc.bar_time
, text = str.format(fmt, tf)
, color = colors_transparent
, textcolor = css
, size = text_size(general_text)
, style = label.style_label_left
, text_font_family = font_style(general_font)
)
bin.hl_lbl.push(lbl)
mtf

method mtf_pivots(UDT_HTF_Candle candle, tf, css

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.