本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sattam
//@version=6
indicator("Volionacci | Sattam", "Volionacci", overlay = false, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500)
// ═════════════════════════════════════════════════════════════════════════════
// Volionacci: market-maker candles read from volume, a Fibonacci drawn on the
// candle itself, entry on a close beyond level 100, targets on the extensions.
// ═════════════════════════════════════════════════════════════════════════════
// ───────────────────────────── Inputs · الإعدادات ─────────────────────────────
G_VOL = "Volume · الفوليوم"
maLen = input.int(20, "Volume MA length · طول متوسط الفوليوم", minval = 2, group = G_VOL)
devLen = input.int(20, "Deviation length · طول الانحراف", minval = 2, group = G_VOL)
devMult = input.float(2.0, "Deviation multiplier · مضاعف الانحراف", minval = 0.1, step = 0.1, group = G_VOL, tooltip = "Dotted line = MA + multiplier × standard deviation. A bar touching the MA is high volume, a bar touching the dotted line is ultra high.\nالخط المنقّط = المتوسط + المضاعف × الانحراف المعياري. العمود الذي يلامس المتوسط فوليوم عالٍ، والذي يلامس المنقّط عالٍ جداً.")
lowLen = input.int(20, "Lowest-volume lookback · نافذة أدنى فوليوم", minval = 2, group = G_VOL, tooltip = "A bar with the lowest volume of this many bars is painted yellow (very weak).\nالعمود الأدنى في هذه النافذة يُلوَّن بالأصفر (ضعيف جداً).")
cUltra = input.color(#0D1B8C, "Above dotted line · فوق المنقّط", group = G_VOL)
cLowest = input.color(#F5D90A, "Lowest · الأدنى", group = G_VOL)
cLess2 = input.color(#F4B6C2, "Below 2 previous · أقل من سابقتين", group = G_VOL)
cLess1 = input.color(#E0252B, "Below previous · أقل من السابقة", group = G_VOL)
cMore = input.color(#3A5BD9, "Above previous · أعلى من السابقة", group = G_VOL)
cMA = input.color(#2E8B57, "MA · المتوسط", group = G_VOL)
cDev = input.color(#9E9E9E, "Dotted line · المنقّط", group = G_VOL)
showInfo = input.bool(true, "Vol / MA / Dev values · قيم الفوليوم", group = G_VOL)
G_PAT = "Market-maker candles · شموع صانع السوق"
onClimax = input.bool(true, "Buying / Selling Climax · ذروة الشراء والبيع", group = G_PAT)
onUT = input.bool(true, "Upthrust / Shakeout · أب ثرست وشيك أوت", group = G_PAT)
onEffort = input.bool(true, "Effort to Fall / Rise · المجهود البيعي والشرائي", group = G_PAT)
onRev = input.bool(true, "Top / Bottom Reversal · انعكاس القمة والقاع", group = G_PAT)
onSV = input.bool(true, "Stopping Volume · فوليوم التوقف", group = G_PAT)
showTests = input.bool(true, "No Demand / No Supply (test bars) · شموع الاختبار", group = G_PAT, tooltip = "Small bar with volume below the two previous bars. A test of the background pattern, shown as a dot.\nشمعة صغيرة بفوليوم أقل من الشمعتين السابقتين: اختبار للخلفية، تظهر كنقطة.")
showERM = input.bool(false, "End of Rising Market (weak) · نهاية السوق الصاعد (ضعيفة)", group = G_PAT)
swingN = input.int(10, "Top / bottom lookback · نافذة القمة والقاع", minval = 2, group = G_PAT, tooltip = "The candle must make the highest high (lowest low) of this many bars: end of a trend or of a correction.\nيجب أن تصنع الشمعة أعلى قمة (أدنى قاع) في هذه النافذة: نهاية ترند أو نهاية تصحيح.")
rngLen = input.int(20, "Average range length · طول متوسط المدى", minval = 2, group = G_PAT)
wideMult = input.float(1.0, "Wide candle ≥ × average range · الشمعة الواسعة ≥ × متوسط المدى", minval = 0.1, step = 0.1, group = G_PAT)
climaxWick= input.float(0.20, "Climax wick ≥ (share of range) · ذيل الذروة ≥ (نسبة من المدى)", minval = 0.0, maxval = 1.0, step = 0.05, group = G_PAT)
utWick = input.float(0.50, "Upthrust / Shakeout wick ≥ · ذيل الأب ثرست والشيك أوت ≥", minval = 0.0, maxval = 1.0, step = 0.05, group = G_PAT)
svWick = input.float(0.25, "Stopping Volume wick ≥ · ذيل فوليوم التوقف ≥", minval = 0.0, maxval = 1.0, step = 0.05, group = G_PAT)
smallMult = input.float(0.7, "Test bar range < × average · مدى شمعة الاختبار < × المتوسط", minval = 0.1, step = 0.1, group = G_PAT)
effortBars= input.int(3, "Effort engulfs ≥ bars · المجهود يبتلع ≥ شموع", minval = 1, group = G_PAT)
useSweep = input.bool(true, "Require liquidity sweep · اشتراط سحب السيولة", group = G_PAT, tooltip = "Keep a candle only when it takes out the last pivot high (selling setups) or pivot low (buying setups).\nلا تُعتمد الشمعة إلا إذا تجاوزت آخر قمة محورية (للبيع) أو آخر قاع محوري (للشراء).")
pivotLen = input.int(5, "Pivot length · طول المحور", minval = 1, group = G_PAT)
G_FIB = "Fibonacci · الفيبوناتشي"
showFib = input.bool(true, "Draw the Fibonacci · رسم الفيبو", group = G_FIB)
lastLvlS = input.string("685.4", "Last level · آخر مستوى", options = ["685.4", "1109"], group = G_FIB, tooltip = "685.4 shows levels up to 685.4. 1109 adds 897.2 (50%) and 1109. Beyond the last level the candle is used up.\n685.4 يعرض حتى 685.4، و1109 يضيف 897.2 (50%) و1109. بعد آخر مستوى تُستهلك الشمعة.")
show786 = input.bool(false, "Show 78.6 · إظهار 78.6", group = G_FIB)
labelFmt = input.string("61.8 / 50%", "Level text · نص المستويات", options = ["61.8 / 50%", "0.618 / 1.309", "None · بدون"], group = G_FIB)
cBearFib = input.color(#E53935, "Selling fib · فيبو البيع", group = G_FIB)
cBullFib = input.color(#1E63D6, "Buying fib · فيبو الشراء", group = G_FIB)
cGolden = input.color(color.new(#FFEB3B, 25), "Golden zone 38.2–61.8 · المنطقة الذهبية", group = G_FIB)
fibWidth = input.int(1, "Line width · سماكة الخط", minval = 1, maxval = 4, group = G_FIB)
extendBars= input.int(15, "Extend right (bars) · الامتداد يميناً (شموع)", minval = 0, maxval = 400, group = G_FIB)
maxFibs = input.int(2, "Fibs kept on chart · عدد الفيبوهات المعروضة", minval = 1, maxval = 20, group = G_FIB)
G_TRD = "Trade · الصفقة"
maxWait = input.int(30, "Wait for the break (bars) · انتظار الكسر (شموع)", minval = 1, group = G_TRD, tooltip = "A candle that is not broken beyond level 100 within this many bars is dropped.\nالشمعة التي لا يُكسر مستوى 100 لها خلال هذه المدة تُلغى.")
oneTrade = input.bool(true, "One trade per direction · صفقة واحدة لكل اتجاه", group = G_TRD, tooltip = "While a trade is open, a new candle of the same direction is drawn only if it makes a new low (high) beyond the trade's level 0.\nما دامت الصفقة قائمة لا تُرسم شمعة جديدة في نفس الاتجاه إلا إذا صنعت قاعاً أدنى (قمة أعلى) من مستوى 0 للصفقة.")
entryVol = input.bool(false, "Break bar volume ≥ MA · فوليوم شمعة الكسر ≥ المتوسط", group = G_TRD)
stopMode = input.string("Close beyond 0 · إغلاق خلف 0", "Stop · الوقف", options = ["Close beyond 0 · إغلاق خلف 0", "Touch beyond 0 · ملامسة خلف 0"], group = G_TRD)
stopBuf = input.float(0.0, "Touch stop buffer (share of range) · هامش وقف الملامسة", minval = 0.0, step = 0.05, group = G_TRD)
tp1S = input.string("261.8", "Target 1 · الهدف الأول", options = ["261.8", "342.7"], group = G_TRD)
tp2 = input.float(423.6, "Target 2 · الهدف الثاني", group = G_TRD)
tp3 = input.float(685.4, "Target 3 · الهدف الثالث", group = G_TRD)
showTrade = input.bool(true, "Entry / target / stop marks · علامات الدخول والأهداف والوقف", group = G_TRD)
G_CL = "Clusters · الكلاستر"
showCl = input.bool(true, "Show clusters · إظهار الكلاستر", group = G_CL, tooltip = "Two levels (100 and beyond) from different fibs that meet within the tolerance. A star marks two 50% levels (strongest).\nمستويان (100 فما بعد) من فيبوهين مختلفين يلتقيان ضمن السماحية. النجمة = مستويان من نوع 50% (الأقوى).")
clTol = input.float(0.25, "Tolerance × ATR(14) · السماحية × ATR", minval = 0.01, step = 0.05, group = G_CL)
cCluster = input.color(color.new(#FF9800, 70), "Cluster color · لون الكلاستر", group = G_CL)
useHTF = input.bool(true, "Higher-timeframe fib · فيبو الفريم الأكبر", group = G_CL)
htf = input.timeframe("D", "Higher timeframe · الفريم الأكبر", group = G_CL)
cHTF = input.color(#7E57C2, "Higher-timeframe fib color · لون فيبو الفريم الأكبر", group = G_CL)
G_DIV = "Continuation divergence · الدايفرجنس الاستمراري"
showDiv = input.bool(true, "RSI continuation divergence · دايفرجنس RSI الاستمراري", group = G_DIV, tooltip = "Uptrend: higher price low with a lower RSI low. Downtrend: lower price high with a higher RSI high. Marks the end of a correction.\nترند صاعد: قاع سعري أعلى وقاع RSI أدنى. ترند هابط: قمة سعرية أدنى وقمة RSI أعلى. تدل على نهاية التصحيح.")
rsiLen = input.int(26, "RSI length · طول RSI", minval = 2, group = G_DIV)
divPiv = input.int(5, "Divergence pivot length · طول محور الدايفرجنس", minval = 1, group = G_DIV)
G_MAN = "Manual candle · شمعة يدوية"
manTime = input.time(0, "Candle time (0 = off) · وقت الشمعة (0 = إيقاف)", group = G_MAN, tooltip = "Draw the Fibonacci on any candle you choose, like drawing it by hand.\nارسم الفيبو على أي شمعة تختارها كأنك ترسمه بيدك.")
manDir = input.string("Auto · تلقائي", "Direction · الاتجاه", options = ["Auto · تلقائي", "Selling · بيع", "Buying · شراء"], group = G_MAN)
G_DSP = "Display · العرض"
lang = input.string("English", "Chart text · نص الشارت", options = ["English + العربية", "English", "العربية"], group = G_DSP)
txtSizeS = input.string("Small · صغير", "Text size · حجم النص", options = ["Tiny · صغير جداً", "Small · صغير", "Normal · متوسط"], group = G_DSP)
patMode = input.string("Traded candles · الشموع المتداولة", "Pattern names · أسماء النماذج", options = ["Traded candles · الشموع المتداولة", "All candles · كل الشموع", "Off · إيقاف"], group = G_DSP, tooltip = "Traded candles: the name appears on a candle once its fib triggers an entry, and on the candle still waiting for its break.\nالشموع المتداولة: يظهر الاسم على الشمعة عند تفعيل الدخول من فيبوها، وعلى الشمعة التي تنتظر الكسر الآن.")
showDash = input.bool(true, "Status table · جدول الحالة", group = G_DSP)
dashPosS = input.string("Top right · أعلى اليمين", "Table position · مكان الجدول", options = ["Top right · أعلى اليمين", "Top left · أعلى اليسار", "Bottom right · أسفل اليمين", "Bottom left · أسفل اليسار"], group = G_DSP)
// ───────────────────────────── Constants ─────────────────────────────
txtSize = txtSizeS == "Tiny · صغير جداً" ? size.tiny : txtSizeS == "Normal · متوسط" ? size.normal : size.small
tp1 = tp1S == "342.7" ? 342.7 : 261.8
lastLevel = lastLvlS == "685.4" ? 685.4 : 1109.0
stopClose = stopMode == "Close beyond 0 · إغلاق خلف 0"
patAll = patMode == "All candles · كل الشموع"
patTraded = patMode == "Traded candles · الشموع المتداولة"
// levels, and which of them are the 50% midpoints
var array<float> LV = array.from(0.0, 38.2, 61.8, 100.0, 130.9, 161.8, 211.8, 261.8, 342.7, 423.6, 554.5, 685.4, 897.2, 1109.0)
var array<bool> LM = array.from(false, false, false, false, true, false, true, false, true, false, true, false, true, false)
txt(string en, string ar) =>
lang == "English" ? en : lang == "العربية" ? ar : en + "\n" + ar
txt1(string en, string ar) =>
lang == "English" ? en : lang == "العربية" ? ar : en + " · " + ar
// type 1 climax, 2 upthrust/shakeout, 3 effort, 4 reversal, 5 stopping volume
rankOf(int t) =>
t == 1 ? 5 : t == 2 ? 4 : t == 3 ? 3 : t == 4 ? 2 : t == 5 ? 1 : 0
patName(int dir, int t) =>
string en = ""
string ar = ""
if t == 0
en := "Manual candle"
ar := "شمعة يدوية"
else if dir < 0
en := t == 1 ? "Buying Climax" : t == 2 ? "Upthrust" : t == 3 ? "Effort to Fall" : "Top Reversal"
ar := t == 1 ? "ذروة شراء" : t == 2 ? "أب ثرست" : t == 3 ? "مجهود بيعي" : "انعكاس قمة"
else
en := t == 1 ? "Selling Climax" : t == 2 ? "Shakeout" : t == 3 ? "Effort to Rise" : t == 4 ? "Bottom Reversal" : "Stopping Volume"
ar := t == 1 ? "ذروة بيع" : t == 2 ? "شيك أوت" : t == 3 ? "مجهود شرائي" : t == 4 ? "انعكاس قاع" : "فوليوم توقف"
[en, ar]
levelText(float L, bool mid) =>
labelFmt == "None · بدون" ? "" : labelFmt == "61.8 / 50%" ? (mid ? "50%" : str.tostring(L, "0.0")) : str.tostring(L / 100.0, "0.###")
// ───────────────────────────── Volume · الفوليوم ─────────────────────────────
vol = nz(volume)
volMA = ta.sma(vol, maLen)
volDv = volMA + devMult * ta.stdev(vol, devLen)
vLow = ta.lowest(vol, lowLen)
vcode = vol > volDv ? 1 : vol <= vLow ? 2 : vol < vol[1] and vol < vol[2] ? 3 : vol < vol[1] ? 4 : 5
vcolor = vcode == 1 ? cUltra : vcode == 2 ? cLowest : vcode == 3 ? cLess2 : vcode == 4 ? cLess1 : cMore
plot(vol, "Volume · الفوليوم", vcolor, style = plot.style_columns)
plot(volMA, "MA · المتوسط", cMA, 1)
plot(volDv, "Dev · المنقّط", cDev, 1, linestyle = plot.linestyle_dotted)
// ───────────────────────────── Pattern detection · كشف النماذج ─────────────────────────────
// returns [bear type, bull type, test (+1 no supply, -1 no demand), end of rising market]
detect() =>
float v = nz(volume)
float rng = high - low
float avgR = ta.sma(rng, rngLen)
float ma = ta.sma(v, maLen)
float up = high - math.max(open, close)
float dn = math.min(open, close) - low
// rounding margin: a value exactly on a threshold is read the same way everywhere
float eR = 1e-9 * nz(avgR)
float eV = 1e-9 * nz(ma)
// no volume (MA of 0) means no bar is high volume, otherwise signals would come from price alone
bool volHigh = ma > 0 and v >= ma - eV
bool top = high >= ta.highest(high, swingN)
bool bot = low <= ta.lowest(low, swingN)
bool wide = rng >= wideMult * avgR - eR
bool utShape = rng > 0 and up >= utWick * rng - eR and close <= low + 0.5 * rng + eR
bool soShape = rng > 0 and dn >= utWick * rng - eR and close >= high - 0.5 * rng - eR
float loPrev = ta.lowest(low, effortBars)[1]
float hiPrev = ta.highest(high, effortBars)[1]
float v1 = v[1]
float v2 = v[2]
float vMax = math.max(v1, v2)
bool top2 = math.max(high, high[1]) >= ta.highest(high, swingN)
bool bot2 = math.min(low, low[1]) <= ta.lowest(low, swingN)
int bear = 0
int bull = 0
// upthrust / shakeout first; a climax is ruled out only by a real one, not by the shape alone
bool isUT = onUT and utShape and wide and volHigh and v > v1 and top
bool isSO = onUT and soShape and wide and volHigh and v > v1 and bot
if onClimax
if close > open and wide and volHigh and rng > 0 and up >= climaxWick * rng - eR and top and not isUT
bear := 1
if close < open and wide and volHigh and rng > 0 and dn >= climaxWick * rng - eR and bot and not isSO
bull := 1
if isUT
bear := bear == 0 or rankOf(2) > rankOf(bear) ? 2 : bear
if isSO
bull := bull == 0 or rankOf(2) > rankOf(bull) ? 2 : bull
if onEffort and bar_index >= effortBars
if close < open and wide and close < loPrev and volHigh and v > vMax
bear := bear == 0 or rankOf(3) > rankOf(bear) ? 3 : bear
if close > open and wide and close > hiPrev and volHigh and v > vMax
bull := bull == 0 or rankOf(3) > rankOf(bull) ? 3 : bull
if onRev and bar_index >= 1
if close[1] > open[1] and close < open and close <= open[1] and v > v1 and top2
bear := bear == 0 or rankOf(4) > rankOf(bear) ? 4 : bear
if close[1] < open[1] and close > open and close >= open[1] and v > v1 and bot2
bull := bull == 0 or rankOf(4) > rankOf(bull) ? 4 : bull
if onSV
if close < open and rng > 0 and dn >= svWick * rng - eR and rng < avgR - eR and volHigh and v > v1 and bot
bull := bull == 0 or rankOf(5) > rankOf(bull) ? 5 : bull
bool small = rng < smallMult * avgR - eR
bool lowV = v < v1 and v < v2
int test = small and lowV ? (close < open ? 1 : close > open ? -1 : 0) : 0
bool erm = close > open and v > v1 and rng < high[1] - low[1] and rng < high[2] - low[2] and top
[bear, bull, test, erm]
[dBear0, dBull0, dTest0, dErm0] = detect()
// no reading before the longest window is full
warm = math.max(maLen, devLen, lowLen, rngLen, swingN)
ready = bar_index >= warm
dBear = ready ? dBear0 : 0
dBull = ready ? dBull0 : 0
dTest = ready ? dTest0 : 0
dErm = ready and dErm0
// strict pivots: higher (lower) than every bar `pivotLen` to each side
pivotsAt(int L) =>
float ph = na
float pl = na
if bar_index >= 2 * L
bool isH = true
bool isL = true
for j = 0 to 2 * L
if j != L
if not (high[L] > high[j])
isH := false
if not (low[L] < low[j])
isL := false
ph := isH ? high[L] : na
pl := isL ? low[L] : na
[ph, pl]
[pvH, pvL] = pivotsAt(pivotLen)
var float lastPH = na
var float lastPL = na
if not na(pvH)
lastPH := pvH
if not na(pvL)
lastPL := pvL
// ───────────────────────────── Setups · الإعدادات ─────────────────────────────
type Setup
int bar
int x1
int dir
int typ
float vol
float p0
float p100
int state = 0 // 0 waiting, 1 in trade, 2 done
int entryBar
float entry
int tp1Bar
int tp2Bar
int tp3Bar
bool dead = false
bool manual = false
int endBar // drawing stops here (na = still extending)
array<line> lines
array<label> labs
box gz
method lvl(Setup s, float L) =>
s.p0 + (s.p100 - s.p0) * L / 100.0
var array<Setup> live = array.new<Setup>() // waiting + in trade
var array<Setup> drawn = array.new<Setup>() // setups that carry drawings
var Setup pendBull = na
var Setup pendBear = na
var array<label> patLabs = array.new<label>()
atr14 = ta.atr(14)
volTotal = ta.cum(vol)
fibColor(Setup s) =>
s.dir < 0 ? cBearFib : cBullFib
deleteDrawing(Setup s) =>
if not na(s.lines)
for ln in s.lines
line.delete(ln)
for lb in s.labs
label.delete(lb)
box.delete(s.gz)
s.lines := na
s.labs := na
s.gz := na
// right end of a drawing: its end bar, or the current bar plus the extension
fibX2(Setup s) =>
na(s.endBar) ? bar_index + extendBars : s.endBar
createDrawing(Setup s) =>
if showFib and na(s.lines)
s.lines := array.new<line>()
s.labs := array.new<label>()
color c = fibColor(s)
int x2 = fibX2(s)
for i = 0 to array.size(LV) - 1
float L = array.get(LV, i)
if L <= lastLevel
float y = s.lvl(L)
int w = L == 100.0 ? fibWidth + 1 : fibWidth
array.push(s.lines, line.new(s.x1, y, x2, y, xloc.bar_index, extend.none, c, line.style_solid, w, force_overlay = true))
array.push(s.labs, label.new(x2, y, levelText(L, array.get(LM, i)), xloc.bar_index, yloc.price, color(na), label.style_label_lower_right, c, size.tiny, force_overlay = true))
if show786
float y = s.lvl(78.6)
array.push(s.lines, line.new(s.x1, y, x2, y, xloc.bar_index, extend.none, color.new(c, 40), line.style_dotted, fibWidth, force_overlay = true))
array.push(s.labs, label.new(x2, y, levelText(78.6, false), xloc.bar_index, yloc.price, color(na), label.style_label_lower_right, c, size.tiny, force_overlay = true))
s.gz := box.new(s.x1, math.max(s.lvl(38.2), s.lvl(61.8)), x2, math.min(s.lvl(38.2), s.lvl(61.8)), na, 0, line.style_solid, extend.none, xloc.bar_index, cGolden, force_overlay = true)
array.push(drawn, s)
// keep only the newest `maxFibs` (a manual candle is never removed)
int autoCount = 0
for x in drawn
if not x.manual
autoCount += 1
while autoCount > maxFibs
for k = 0 to array.size(drawn) - 1
Setup old = array.get(drawn, k)
if not old.manual
array.remove(drawn, k)
deleteDrawing(old)
break
autoCount -= 1
moveDrawing(Setup s) =>
if not na(s.lines)
int x2 = fibX2(s)
for ln in s.lines
line.set_x2(ln, x2)
for lb in s.labs
label.set_x(lb, x2)
box.set_right(s.gz, x2)
dropDrawn(Setup s) =>
int k = array.indexof(drawn, s)
if k >= 0
array.remove(drawn, k)
deleteDrawing(s)
var array<label> tradeLabs = array.new<label>()
// entry / target / stop marks, capped so they never push the fib drawings out of the 500-object pool
markTrade(string en, string ar, float y, bool up, color c, bool boxed) =>
if showTrade
array.push(tradeLabs, label.new(bar_index, y, txt1(en, ar), xloc.bar_index, yloc.price, boxed ? color.new(c, 10) : color(na), up ? label.style_label_up : label.style_label_down, boxed ? color.white : c, size.tiny, force_overlay = true))
if array.size(tradeLabs) > 120
label.delete(array.shift(tradeLabs))
// name of a market-maker candle, placed on the candle itself
makePatLabel(int x, float y, int d, int t, float v) =>
[en, ar] = patName(d, t)
color c = d < 0 ? cBearFib : cBullFib
string tip = en + " · " + ar + "\nVolume " + str.tostring(v, format.volume)
label.new(x, y, txt1(en, ar), xloc.bar_index, yloc.price, color.new(c, 15), d < 0 ? label.style_label_down : label.style_label_up, color.white, txtSize, tooltip = tip, force_overlay = true)
keepPatLabel(label lb) =>
array.push(patLabs, lb)
if array.size(patLabs) > 120
label.delete(array.shift(patLabs))
// hidden event values for verification
float eBull = na
float eBear = na
int xBull = 0
int xBear = 0
int kBull = 0
int kBear = 0
// 1) update open setups (closed bars only)
if barstate.isconfirmed and array.size(live) > 0
for i = array.size(live) - 1 to 0
Setup s = array.get(live, i)
int d = s.dir
if s.state == 0
bool broke = d < 0 ? close < s.p100 : close > s.p100
if broke and (not entryVol or (volMA > 0 and vol >= volMA))
s.state := 1
s.entryBar := bar_index
s.entry := close
if d > 0
eBull := bar_index - s.bar
else
eBear := bar_index - s.bar
if not s.manual
if d > 0
pendBull := na
else
pendBear := na
createDrawing(s)
if patTraded
keepPatLabel(makePatLabel(s.bar, s.p0, d, s.typ, s.vol))
markTrade(d < 0 ? "SELL" : "BUY", d < 0 ? "بيع" : "شراء", close, d > 0, fibColor(s), true)
alert(syminfo.ticker + " " + timeframe.period + (d < 0 ? " SELL · بيع" : " BUY · شراء") + " @ " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
else
bool inval = d < 0 ? close > s.p0 : close < s.p0
bool expired = bar_index - s.bar >= maxWait
// a manual candle stays until its break, whatever price does
if (inval or expired) and not s.manual
s.dead := true
if d > 0
kBull += inval ? 1 : 10
else
kBear += inval ? 1 : 10
if not s.manual
if d > 0
pendBull := na
else
pendBear := na
dropDrawn(s)
array.remove(live, i)
else if s.state == 1 and bar_index > s.entryBar
int code = 0
float eL = 1e-9 * math.abs(s.p100 - s.p0) // rounding margin for an exact touch
bool hit1 = d < 0 ? low <= s.lvl(tp1) + eL : high >= s.lvl(tp1) - eL
bool hit2 = d < 0 ? low <= s.lvl(tp2) + eL : high >= s.lvl(tp2) - eL
bool hit3 = d < 0 ? low <= s.lvl(tp3) + eL : high >= s.lvl(tp3) - eL
if na(s.tp1Bar) and hit1
s.tp1Bar := bar_index
code += 1
markTrade("TP1 ✓", "هدف 1", s.lvl(tp1), d < 0, #2E7D32, false)
if na(s.tp2Bar) and hit2
s.tp2Bar := bar_index
code += 10
markTrade("TP2 ✓", "هدف 2", s.lvl(tp2), d < 0, #2E7D32, false)
if na(s.tp3Bar) and hit3
s.tp3Bar := bar_index
code += 100
markTrade("TP3 ✓", "هدف 3", s.lvl(tp3), d < 0, #2E7D32, false)
if not na(s.tp3Bar)
s.state := 2
array.remove(live, i)
else
float buf = stopBuf * math.abs(s.p100 - s.p0)
bool sl = stopClose ? (d < 0 ? close > s.p0 : close < s.p0) : (d < 0 ? high >= s.p0 + buf - eL : low <= s.p0 - buf + eL)
if sl
s.state := 2
s.endBar := bar_index
code += 1000
markTrade("SL ✗", "وقف", s.p0, d > 0, #9E9E9E, false)
moveDrawing(s)
array.remove(live, i)
if code > 0
alert(syminfo.ticker + " " + timeframe.period + " " + (code >= 1000 ? "SL · وقف" : "Target · هدف"), alert.freq_once_per_bar_close)
if d > 0
xBull += code
else
xBear += code
// a fib is used up once price goes beyond its last level
if barstate.isconfirmed and array.size(drawn) > 0
for s in drawn
if s.state >= 1 and na(s.endBar) and bar_index > s.entryBar
bool beyond = s.dir < 0 ? low <= s.lvl(lastLevel) : high >= s.lvl(lastLevel)
if beyond
s.endBar := bar_index
moveDrawing(s)
// 2) new market-maker candles on this bar
int bearT = dBear
int bullT = dBull
if useSweep
if bearT != 0 and not (high > lastPH)
bearT := 0
if bullT != 0 and not (low < lastPL)
bullT := 0
newSetup(int d, int t, bool manual) =>
bool two = t == 4
float H = two ? math.max(high, high[1]) : high
float Lo = two ? math.min(low, low[1]) : low
Setup.new(bar_index, two ? bar_index - 1 : bar_index, d, t, vol, d < 0 ? H : Lo, d < 0 ? Lo : H, manual = manual)
if barstate.isconfirmed
for d in array.from(-1, 1)
int t = d < 0 ? bearT : bullT
// one fib per direction: an open trade blocks new candles that stay inside its level 0;
// a candle that makes a lower low (higher high) than that level is a new market-maker candle
bool busy = false
if oneTrade
for x in live
if x.dir == d and x.state == 1 and not x.manual and (d > 0 ? low >= x.p0 : high <= x.p0)
busy := true
if t != 0 and not busy
Setup old = d < 0 ? pendBear : pendBull
bool accept = true
if not na(old)
accept := rankOf(t) > rankOf(old.typ) or (rankOf(t) == rankOf(old.typ) and vol > old.vol)
if accept
old.dead := true
if d > 0
kBull += 100
else
kBear += 100
int k = array.indexof(live, old)
if k >= 0
array.remove(live, k)
dropDrawn(old)
if accept
Setup s = newSetup(d, t, false)
array.push(live, s)
if d < 0
pendBear := s
else
pendBull := s
[en, ar] = patName(d, t)
alert(syminfo.ticker + " " + timeframe.period + " " + en + " · " + ar, alert.freq_once_per_bar_close)
if t != 0 and patAll
keepPatLabel(makePatLabel(bar_index, d < 0 ? high : low, d, t, vol))
// manual candle: the first bar at or after the chosen time
isTop = high >= ta.highest(high, swingN)
isBot = low <= ta.lowest(low, swingN)
var bool manDone = false
var int firstTime = time
manTooOld = manTime > 0 and manTime < firstTime
if barstate.isconfirmed and manTime > 0 and not manTooOld and not manDone and time >= manTime
manDone := true
int d = manDir == "Selling · بيع" ? -1 : manDir == "Buying · شراء" ? 1 : isTop and not isBot ? -1 : isBot and not isTop ? 1 : close > open ? 1 : -1
int t = d < 0 ? bearT : bullT
Setup s = newSetup(d, t, true)
array.push(live, s)
createDrawing(s)
// test bars and end of rising market (dots on the candles)
plotshape(showTests and barstate.isconfirmed and dTest == 1, "No Supply · لا عرض", shape.circle, location.belowbar, cBullFib, size = size.tiny, force_overlay = true)
plotshape(showTests and barstate.isconfirmed and dTest == -1, "No Demand · لا طلب", shape.circle, location.abovebar, cBearFib, size = size.tiny, force_overlay = true)
plotshape(showERM and barstate.isconfirmed and dErm, "End of Rising Market · نهاية السوق الصاعد", shape.xcross, location.abovebar, color.new(cBearFib, 30), size = size.tiny, force_overlay = true)
// ───────────────────────────── Continuation divergence · الدايفرجنس ─────────────────────────────
rsiV = ta.rsi(close, rsiLen)
dPL = ta.pivotlow(low, divPiv, divPiv)
dPH = ta.pivothigh(high, divPiv, divPiv)
var float prevPL = na
var float prevPLr = na
var int prevPLb = na
var float prevPH = na
var float prevPHr = na
var int prevPHb = na
var array<line> divLines = array.new<line>()
var array<label> divLabs = array.new<label>()
keepDiv(line ln, label lb) =>
array.push(divLines, ln)
array.push(divLabs, lb)
if array.size(divLines) > 30
line.delete(array.shift(divLines))
label.delete(array.shift(divLabs))
if showDiv and not na(dPL)
float r = rsiV[divPiv]
if not na(prevPL) and dPL > prevPL and r < prevPLr
keepDiv(line.new(prevPLb, prevPL, bar_index - divPiv, dPL, xloc.bar_index, extend.none, cBullFib, line.style_dashed, 2, force_overlay = true), label.new(bar_index - divPiv, dPL, txt("Cont. div ▲", "دايفرجنس استمراري ▲"), xloc.bar_index, yloc.price, color(na), label.style_label_up, cBullFib, txtSize, force_overlay = true))
prevPL := dPL
prevPLr := r
prevPLb := bar_index - divPiv
if showDiv and not na(dPH)
float r = rsiV[divPiv]
if not na(prevPH) and dPH < prevPH and r > prevPHr
keepDiv(line.new(prevPHb, prevPH, bar_index - divPiv, dPH, xloc.bar_index, extend.none, cBearFib, line.style_dashed, 2, force_overlay = true), label.new(bar_index - divPiv, dPH, txt("Cont. div ▼", "دايفرجنس استمراري ▼"), xloc.bar_index, yloc.price, color(na), label.style_label_down, cBearFib, txtSize, force_overlay = true))
prevPH := dPH
prevPHr := r
prevPHb := bar_index - divPiv
// ───────────────────────────── Higher-timeframe fib · فيبو الفريم الأكبر ─────────────────────────────
// the latest market-maker candle of the higher timeframe, dropped once price passes its last level
htfAnchor() =>
[b, u, _t, _e] = detect()
var float p0 = na
var float p100 = na
var int tm = na
var int dir = 0
if b != 0 or u != 0
int d = b != 0 and (u == 0 or rankOf(b) >= rankOf(u)) ? -1 : 1
dir := d
p0 := d < 0 ? high : low
p100 := d < 0 ? low : high
tm := time
else if dir != 0
float lastY = p0 + (p100 - p0) * lastLevel / 100.0
if (dir < 0 and low <= lastY) or (dir > 0 and high >= lastY)
dir := 0
// the previous (closed) higher-timeframe candle, so a forming candle never moves the fib
[dir[1], p0[1], p100[1], tm[1]]
htfOn = useHTF and timeframe.in_seconds(htf) > timeframe.in_seconds()
int hDir = 0
float hP0 = na
float hP100 = na
int hTime = na
if htfOn
[a1, a2, a3, a4] = request.security(syminfo.tickerid, htf, htfAnchor(), lookahead = barmerge.lookahead_on)
hDir := nz(a1)
hP0 := a2
hP100 := a3
hTime := a4
// ───────────────────────────── Last bar: drawings, clusters, tables ─────────────────────────────
var array<box> clBoxes = array.new<box>()
var array<line> hLines = array.new<line>()
var array<label> hLabs = array.new<label>()
var table info = table.new(position.top_right, 2, 3)
dashPos = dashPosS == "Top left · أعلى اليسار" ? position.top_left : dashPosS == "Bottom right · أسفل اليمين" ? position.bottom_right : dashPosS == "Bottom left · أسفل اليسار" ? position.bottom_left : position.top_right
var table dash = table.new(dashPos, 1, 6, force_overlay = true)
var array<label> tmpLabs = array.new<label>()
if barstate.islast
// waiting setups get their fib and name now so the current candle is visible
for lb in tmpLabs
label.delete(lb)
array.clear(tmpLabs)
for s in live
if s.state == 0
createDrawing(s)
if patTraded
array.push(tmpLabs, makePatLabel(s.bar, s.p0, s.dir, s.typ, s.vol))
for s in drawn
moveDrawing(s)
// higher-timeframe fib (dashed)
for ln in hLines
line.delete(ln)
for lb in hLabs
label.delete(lb)
array.clear(hLines)
array.clear(hLabs)
int xr = time + extendBars * timeframe.in_seconds() * 1000
if htfOn and hDir != 0 and not na(hTime)
for i = 0 to array.size(LV) - 1
float L = array.get(LV, i)
if L <= lastLevel
float y = hP0 + (hP100 - hP0) * L / 100.0
array.push(hLines, line.new(hTime, y, xr, y, xloc.bar_time, extend.none, cHTF, line.style_dashed, 1, force_overlay = true))
array.push(hLabs, label.new(xr, y, htf + " " + levelText(L, array.get(LM, i)), xloc.bar_time, yloc.price, color(na), label.style_label_lower_right, cHTF, size.tiny, force_overlay = true))
// clusters: levels from 100 onward of different fibs within the tolerance
for bx in clBoxes
box.delete(bx)
array.clear(clBoxes)
if showCl
array<float> py = array.new<float>()
array<int> ps = array.new<int>()
array<bool> pm = array.new<bool>()
array<int> px = array.new<int>()
int src = 0
for s in drawn
if na(s.endBar)
for i = 3 to array.size(LV) - 1
float L = array.get(LV, i)
if L <= lastLevel
array.push(py, s.lvl(L))
array.push(ps, src)
array.push(pm, array.get(LM, i))
array.push(px, s.x1)
src += 1
if htfOn and hDir != 0
for i = 3 to array.size(LV) - 1
float L = array.get(LV, i)
if L <= lastLevel
array.push(py, hP0 + (hP100 - hP0) * L / 100.0)
array.push(ps, 999)
array.push(pm, array.get(LM, i))
array.push(px, bar_index - extendBars)
float tol = clTol * atr14
int n = array.size(py)
if n > 1
for i = 0 to n - 2
for j = i + 1 to n - 1
if array.get(ps, i) != array.get(ps, j) and math.abs(array.get(py, i) - array.get(py, j)) <= tol and array.size(clBoxes) < 12
float y1 = math.min(array.get(py, i), array.get(py, j)) - tol * 0.25
float y2 = math.max(array.get(py, i), array.get(py, j)) + tol * 0.25
bool strong = array.get(pm, i) and array.get(pm, j)
int x1 = math.max(array.get(px, i), array.get(px, j))
array.push(clBoxes, box.new(x1, y2, bar_index + extendBars, y1, color.new(cCluster, 40), 1, line.style_dotted, extend.none, xloc.bar_index, cCluster, (strong ? "★ " : "") + txt("Cluster", "كلاستر"), size.tiny, #E65100, text.align_right, force_overlay = true))
// values in the volume pane, like the classic volume window
if showInfo
table.cell(info, 0, 0, "Vol", text_color = cLowest, text_size = size.small)
table.cell(info, 1, 0, str.tostring(vol, format.volume), text_color = cLowest, text_size = size.small)
table.cell(info, 0, 1, "MA", text_color = cMA, text_size = size.small)
table.cell(info, 1, 1, str.tostring(volMA, format.volume), text_color = cMA, text_size = size.small)
table.cell(info, 0, 2, "Dev", text_color = cDev, text_size = size.small)
table.cell(info, 1, 2, str.tostring(volDv, format.volume), text_color = cDev, text_size = size.small)
// status of the newest setup
if showDash
table.clear(dash, 0, 0, 0, 5)
Setup last = na
for s in live
if na(last) or s.bar > last.bar
last := s
if na(last) and array.size(drawn) > 0
last := array.last(drawn)
color bg = color.new(#1E1E1E, 10)
if volTotal == 0
table.cell(dash, 0, 0, txt("No volume data", "لا توجد بيانات فوليوم"), text_color = color.orange, bgcolor = bg, text_size = size.tiny)
else if na(last)
table.cell(dash, 0, 0, txt("Waiting for a market-maker candle", "بانتظار شمعة صانع السوق"), text_color = color.white, bgcolor = bg, text_size = size.tiny)
else
[en, ar] = patName(last.dir, last.typ)
string st = last.state == 0 ? txt("Waiting for a close beyond 100", "انتظار إغلاق خلف 100") : last.state == 1 ? txt("In trade", "صفقة قائمة") : (not na(last.tp3Bar) ? txt("Target 3 reached", "تحقق الهدف 3") : txt("Closed", "مغلقة"))
table.cell(dash, 0, 0, (last.dir < 0 ? "▼ " : "▲ ") + txt(en, ar), text_color = color.white, bgcolor = fibColor(last), text_size = size.tiny)
table.cell(dash, 0, 1, st, text_color = color.white, bgcolor = bg, text_size = size.tiny)
float stopY = stopClose ? last.p0 : last.p0 - last.dir * stopBuf * math.abs(last.p100 - last.p0)
string entryTxt = last.state == 0 ? txt("Entry (100)", "الدخول (100)") + " " + str.tostring(last.lvl(100), format.mintick) : txt("Entry", "الدخول") + " " + str.tostring(last.entry, format.mintick)
table.cell(dash, 0, 2, entryTxt, text_color = color.white, bgcolor = bg, text_size = size.tiny)
table.cell(dash, 0, 3, (stopClose ? txt("Stop (close beyond 0)", "الوقف (إغلاق خلف 0)") : txt("Stop (touch)", "الوقف (ملامسة)")) + " " + str.tostring(stopY, format.mintick), text_color = color.white, bgcolor = bg, text_size = size.tiny)
table.cell(dash, 0, 4, "TP " + str.tostring(last.lvl(tp1), format.mintick) + " · " + str.tostring(last.lvl(tp2), format.mintick) + " · " + str.tostring(last.lvl(tp3), format.mintick), text_color = color.white, bgcolor = bg, text_size = size.tiny)
if manTooOld
table.cell(dash, 0, 5, txt("Manual candle is older than the loaded history", "الشمعة اليدوية أقدم من التاريخ المحمّل"), text_color = color.orange, bgcolor = bg, text_size = size.tiny)
// hidden event values used to verify the script against its reference model
plot(vcode, "vcol", display = display.none)
plot(bearT, "bear", display = display.none)
plot(bullT, "bull", display = display.none)
plot(dTest, "test", display = display.none)
plot(eBull, "eBull", display = display.none)
plot(eBear, "eBear", display = display.none)
plot(xBull, "xBull", display = display.none)
plot(xBear, "xBear", display = display.none)
plot(kBull, "kBull", display = display.none)
plot(kBear, "kBear", display = display.none)
plot(bar_index, "bi", display = display.none)