Moving Average Disparity Heatmaps

TrendAdvantage · study · 1340 行 · 点赞 3 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0
// at https://mozilla.org/MPL/2.0/
// © TrendAdvantage — tradingview.com/u/TrendAdvantage
// Any derivative work must retain this copyright notice.
 
//@version=6
 
// ─────────────────────────────────────────────────────────────────────────────
// Moving Average Disparity Heatmaps (MADH) — TrendAdvantage
// ─────────────────────────────────────────────────────────────────────────────
// [EN]
// Moving Average Disparity Heatmaps (MADH) is a multi-ticker indicator that
// measures how far price is from its moving averages, how far the averages are
// from each other, and how quickly these gaps are narrowing or widening. Each
// reading is converted to a percentile of the symbol's own history, so
// conditions can be compared across stocks, ETFs, currencies, commodities and
// crypto. Results are shown as heatmap tables, with each cell coloured by its
// percentile. MADH extends the Disparity Index, a Japanese technical tool. It is
// designed for analysis and does not generate buy or sell signals.
//
// [AR]
// خرائط التباعد الحرارية للمتوسطات المتحركة مؤشر متعدد الرموز يقيس مدى ابتعاد
// السعر عن متوسطاته المتحركة، ومدى تباعد المتوسطات بعضها عن بعض، ومدى سرعة
// تضيّق هذه الفجوات أو اتساعها. تُحوَّل كل قراءة إلى ترتيب مئوي مقارنةً بتاريخ
// الرمز نفسه، مما يتيح مقارنة الأوضاع بين الأسهم وصناديق المؤشرات المتداولة
// والعملات والسلع والعملات المشفرة. تُعرض النتائج في جداول خرائط حرارية، تُلوَّن
// فيها كل خلية بحسب ترتيبها المئوي. يوسّع هذا المؤشر فكرة مؤشر التباعد، وهو أداة
// تحليل فني يابانية. صُمّم المؤشر للتحليل ولا يُصدر إشارات شراء أو بيع.
//
// [ES]
// Moving Average Disparity Heatmaps (MADH) es un indicador multi-ticker que mide
// cuánto se aleja el precio de sus medias móviles, cuánto se separan las medias
// entre sí y con qué rapidez se estrechan o amplían esas diferencias. Cada
// lectura se convierte en un percentil respecto al propio historial del símbolo,
// lo que permite comparar condiciones entre acciones, ETF, divisas, materias
// primas y criptomonedas. Los resultados se muestran en tablas de mapa de calor,
// con cada celda coloreada según su percentil. MADH amplía el Disparity Index
// (índice de disparidad), una herramienta técnica japonesa. Está diseñado para
// el análisis y no genera señales de compra ni de venta.
//
// [TR]
// Moving Average Disparity Heatmaps (MADH), fiyatın hareketli ortalamalarından
// ne kadar uzaklaştığını, ortalamaların birbirinden ne kadar ayrıldığını ve bu
// farkların ne kadar hızlı daraldığını veya genişlediğini ölçen çoklu sembol
// göstergesidir. Her değer, sembolün kendi geçmişine göre yüzdelik dilime
// dönüştürülür; böylece hisse senetleri, ETF'ler, dövizler, emtialar ve kripto
// paralar arasında koşullar karşılaştırılabilir. Sonuçlar, her hücrenin
// yüzdelik değerine göre renklendirildiği ısı haritası tablolarında gösterilir.
// MADH, Japon kökenli bir teknik araç olan Disparity Index'i (Ayrışma Endeksi)
// genişletir. Analiz amacıyla tasarlanmıştır; alım veya satım sinyali üretmez.
// ─────────────────────────────────────────────────────────────────────────────
// Disclaimer: all outputs are descriptive statistics of past data and do not
// guarantee future results.
// ─────────────────────────────────────────────────────────────────────────────
 
indicator("Moving Average Disparity Heatmaps", shorttitle = "MA Disparity Heatmaps [TrendAdvantage]", overlay = true, max_bars_back = 1000)
 
// ─────────────────────────────────────────────────────────────────────────────
// Three multi-ticker tables, selected in the settings:
//   1 · Price-to-MA Distance     gap of price from each MA (log %) + percentile
//   2 · MA-to-MA Spread          spread between MA pairs (log %) + percentile
//   3 · Convergence Speed of Averages
//                                whether each MA pair is closing or widening
//                                (glyph) + speed percentile vs own history
// Tables 2 and 3 use the same MA pairs: Table 2 shows the LEVEL of each
// spread, Table 3 its RATE of change.
// All metrics are computed on every bar; the table selection only changes
// what is drawn on the last bar.
// Values are from each ticker's last closed bar of the table timeframe.
// Gaps and spreads are calculated in logs, so Table 2 spread = difference of
// Table 1 gaps: ln(F/L) = ln(P/L) − ln(P/F). The tables DISPLAY simple
// percentages (e.g. P/MA − 1), which match what users measure on the chart.
// Percentiles are identical either way, because the conversion keeps order.
//
// MA pairs are oriented by length: the shorter (faster) MA is always the
// first side, so a positive spread means fast above slow whatever order
// the pair was entered in (a 50 / 10 pair is shown as 10 / 50). A pair
// whose two MAs have the same length has no fast side and is always zero,
// so it stops the script with an error message.
//
// Composite ("Avg") columns:
//   Table 1: mean of the log gaps across the DISPLAYED MAs
//            = ln(price / geometric mean of those MAs), then its percentile.
//            Because it is computed in logs, it is not the simple average of
//            the displayed % cells.
//            A ticked MA whose length repeats an earlier ticked MA is a
//            duplicate: its column is kept, marked "(dup.)" and shown with
//            dashes, and it is left out of Avg and the sort, so no length
//            counts twice. The first occurrence stays active.
//   Table 2: each pair's log spread is divided by its RMS over the
//            percentile window (its typical size); the scaled spreads are
//            averaged across the ENABLED pairs and that average is ranked
//            over the percentile window.
//            Scaling gives every pair equal weight and stops chained pairs
//            from telescoping: a plain mean of 10/20, 20/50, 50/100, 100/200
//            equals ln(MA 10 / MA 200) / 4, so the middle MAs would drop out.
//            Top line: ▲ count / selected pairs = pairs whose faster MA is
//            above the slower one (e.g. ▲ 3/4).
//   Table 3: each pair's divergence rate is divided by its RMS over the
//            percentile window and capped at ±2 (typical sizes), so one
//            extreme pair cannot outweigh the others; the capped values are
//            averaged across the enabled pairs (sign flipped, so high = closing
//            fastest) and ranked over the percentile window.
//            Pairs that crossed within the × window are left out of the
//            composite (their cells keep the × mark and percentile): at a cross
//            the same motion flips from closing to widening.
//            Price action column (right after Ticker), built from all pairs:
//              trend     = ribbon order (majority of pairs with the faster MA on top)
//              direction = slope of the fastest MA in the enabled pairs,
//                          measured directly (valid for every MA type)
//              momentum  = composite sign: pairs widening on balance →
//                          faster, closing on balance → slower
//            Up + rising: Rise faster / slower / stable
//            Up + falling: Pullback · Down + rising: Rebound
//            Down + falling: Decline faster / slower / stable
//            Fastest MA flat: Sideways · pairs split evenly: Uncertain
//            Shown in green (▲) / red (▼) text on a neutral background, the
//            same meaning green / red have in Tables 1–2. The Avg column
//            carries only the combined speed percentile (blue / amber).
//            The label describes price; it is not a signal.
//   Composite policy (strict): a composite uses ALL enabled pairs (or all
//   displayed MAs) or shows n/a; it never averages a partial set. The only
//   designed exception is Table 3's × exclusion. Because of it, Table 3's
//   Avg history can mix composites built from different pair subsets.
//   RMS scaling puts pairs on a common scale but does not make those
//   distributions identical: a known methodological limitation.
//   A zero RMS (quantity identically zero over the window) gives a scaled
//   value of 0, not n/a; n/a is kept for warm-up only.
//   RMS is used instead of standard deviation because it keeps zero meaning
//   "MAs equal" / "not moving", so the sign survives the scaling.
//   Table 2's Avg and all of Table 3 are always coloured by percentile.
//
// Table 3 state (→← converging, ←→ diverging, = stable) is the sign of the
// pair's rate, with a stable band set as a multiple of that pair's own RMS
// rate, so one setting works for FX, equities and crypto alike. The same
// band (in units of each quantity's own RMS) decides when the fastest MA is
// flat and when the pairs are stable on balance for the price-action label.
// Pair cells show the glyph and the percentile only: the raw rate (points
// per bar) is not comparable across tickers, the percentile is.
//
// Languages: setting labels, group titles and tooltips show all four
// languages (English / Arabic / Spanish / Turkish). The Language input
// switches every text drawn in the table.
//
// Table width: the title and footer rows are merged across all columns. A
// merged cell wider than the columns below it widens the last column, so the
// title is two centered lines (table name, then settings) and the footer is
// split into lines with "\n". Narrow tables (5 columns or fewer, e.g. one or
// two MAs or pairs) use a compact form with one item per line. Column widths
// stay content-based, so they adapt to the text size and language settings.
// ─────────────────────────────────────────────────────────────────────────────
 
// ── Constants ─────────────────────────────────────────────────────────────
// Dropdown options carry all four languages (English / Arabic / Spanish /
// Turkish). The code always compares against these constants.
const string V1 = "1 · Price-to-MA Distance / بُعد السعر عن المتوسط / Distancia precio–media / Fiyat–ortalama uzaklığı"
const string V2 = "2 · MA-to-MA Spread / الفارق بين المتوسطات / Diferencial entre medias / Ortalamalar arası fark"
const string V3 = "3 · Convergence Speed of Averages / سرعة تقارب المتوسطات / Velocidad de convergencia de medias / Ortalamaların yakınsama hızı"
 
const string L_EN = "English"
const string L_AR = "العربية"
const string L_ES = "Español"
const string L_TR = "Türkçe"
 
const string S_NONE = "None (input order) / بلا (ترتيب الإدخال) / Ninguno (orden de entrada) / Yok (giriş sırası)"
const string S_HIGH = "Highest Avg first / الأعلى متوسطًا أولاً / Mayor Prom. primero / En yüksek Ort. önce"
const string S_LOW  = "Lowest Avg first / الأدنى متوسطًا أولاً / Menor Prom. primero / En düşük Ort. önce"
 
const string C_PCT  = "Percentage / النسبة المئوية / Porcentaje / Yüzde"
const string C_PCTL = "Percentile / الترتيب المئوي / Percentil / Yüzdelik"
 
const string SRC_C = "Close / الإغلاق / Cierre / Kapanış"
const string SRC_O = "Open / الافتتاح / Apertura / Açılış"
const string SRC_H = "High / الأعلى / Máximo / Yüksek"
const string SRC_L = "Low / الأدنى / Mínimo / Düşük"
 
const string TH_AUTO  = "Auto / تلقائي / Automático / Otomatik"
const string TH_LIGHT = "Light / فاتح / Claro / Açık"
const string TH_DARK  = "Dark / داكن / Oscuro / Koyu"
 
// Left-to-right mark (U+200E, invisible). Wrapping arrows and fractions in it
// keeps their order when they sit inside Arabic text, so →← is not shown
// as ←→ in right-to-left lines.
const string LRM  = "‎"
const string G_CV = "→←"
const string G_DV = "←→"
 
// Group titles (English / Arabic / Spanish / Turkish)
const string GG = "General / عام / General / Genel"
const string GD = "Display / العرض / Visualización / Gösterim"
const string GM = "Moving averages / المتوسطات المتحركة / Medias móviles / Hareketli ortalamalar"
const string GP = "MA pairs · Tables 2–3 / أزواج المتوسطات · الجدولان 2–3 / Pares de medias · Tablas 2–3 / Ortalama çiftleri · Tablo 2–3"
const string GX = "Advanced · defaults suit most users / متقدم · الإعدادات الافتراضية تناسب معظم المستخدمين / Avanzado · los valores por defecto sirven a la mayoría / Gelişmiş · varsayılanlar çoğu kullanıcıya uygundur"
const string GT = "Tickers / الرموز / Símbolos / Semboller"
const string GA = "Appearance / المظهر / Apariencia / Görünüm"
 
// Tooltips (English, Arabic, Spanish, Turkish, separated by blank lines)
const string TIP_LANG =
     "Language used for the table text and labels." + "\n\n" +
     "اللغة المستخدمة في نصوص الجدول وعناوينه." + "\n\n" +
     "Idioma usado para el texto y las etiquetas de la tabla." + "\n\n" +
     "Tablo metni ve etiketleri için kullanılan dil."
const string TIP_TABLE =
     "Table 1: Price relative to moving averages. Table 2: Spread between moving averages. Table 3: Convergence and divergence speed of moving-average pairs; it is not a trading signal." + "\n\n" +
     "الجدول 1: السعر مقارنةً بالمتوسطات المتحركة. الجدول 2: الفارق بين المتوسطات المتحركة. الجدول 3: سرعة تقارب أزواج المتوسطات المتحركة وتباعدها؛ وهو ليس إشارة تداول." + "\n\n" +
     "Tabla 1: precio respecto a las medias móviles. Tabla 2: diferencial entre medias móviles. Tabla 3: velocidad de convergencia y divergencia de los pares de medias móviles; no es una señal de trading." + "\n\n" +
     "Tablo 1: Fiyatın hareketli ortalamalara göre konumu. Tablo 2: Hareketli ortalamalar arasındaki fark. Tablo 3: Hareketli ortalama çiftlerinin yakınsama ve ıraksama hızı; bir işlem sinyali değildir."
const string TIP_TF =
     "Timeframe used for all tickers. It is set here, in the indicator settings, not from the chart's timeframe menu: changing the chart's timeframe does not change the table unless 'Chart' is selected here. Values come from each ticker's last closed bar." + "\n\n" +
     "الإطار الزمني المستخدم لكل الرموز. يُحدَّد من هنا، من إعدادات المؤشر، وليس من قائمة الإطار الزمني في الرسم البياني؛ فتغيير إطار الرسم البياني لا يغيّر الجدول إلا إذا اخترت هنا «الرسم البياني». القيم مأخوذة من آخر إغلاق للعمود لكل رمز." + "\n\n" +
     "Temporalidad usada para todos los símbolos. Se elige aquí, en la configuración del indicador, no en el menú de temporalidad del gráfico: cambiar la temporalidad del gráfico no afecta a la tabla, salvo que aquí se elija «Gráfico». Los valores provienen de la última barra cerrada de cada símbolo." + "\n\n" +
     "Tüm semboller için kullanılan zaman dilimi. Grafiğin zaman dilimi menüsünden değil, burada, gösterge ayarlarından seçilir: burada «Grafik» seçilmedikçe grafiğin zaman dilimini değiştirmek tabloyu etkilemez. Değerler her sembolün son kapanmış çubuğundan alınır."
const string TIP_COL =
     "Green = positive % or high percentile; red = negative % or low percentile. Darker colours indicate more extreme values. Table 2's Avg and all of Table 3 always use percentiles. In Table 3, blue = faster convergence; amber = faster divergence." + "\n\n" +
     "الأخضر = نسبة موجبة أو ترتيب مئوي مرتفع، الأحمر = نسبة سالبة أو ترتيب مئوي منخفض. الألوان الأغمق تدل على القيم القصوى. يستخدم عمود المتوسط في الجدول 2 وكامل الجدول 3 الترتيب المئوي دائمًا. في الجدول 3، الأزرق = تقارب أسرع، والبرتقالي = تباعد أسرع." + "\n\n" +
     "Verde = % positivo o percentil alto; rojo = % negativo o percentil bajo. Los colores más oscuros indican valores más extremos. La columna Prom. de la Tabla 2 y toda la Tabla 3 usan siempre percentiles. En la Tabla 3, azul = convergencia más rápida; ámbar = divergencia más rápida." + "\n\n" +
     "Yeşil = pozitif % veya yüksek yüzdelik; kırmızı = negatif % veya düşük yüzdelik. Daha koyu renkler daha uç değerleri gösterir. Tablo 2'nin Ort. sütunu ve Tablo 3'ün tamamı her zaman yüzdelik kullanır. Tablo 3'te mavi = daha hızlı yakınsama; kehribar = daha hızlı ıraksama."
const string TIP_SORT =
     "Sorts tickers by Avg; tickers showing n/a appear last. Table 1 sorts by the colouring measure (% or percentile)." + "\n" +
     "Avg: Table 1 = average price distance; Table 2 = percentile of the average pair spread; Table 3 = overall convergence-speed percentile (higher = faster). Avg is a composite, not the average of displayed values." + "\n\n" +
     "يرتّب الرموز حسب عمود المتوسط؛ وتظهر الرموز التي تعرض غ/م أسفل الجدول. يُرتَّب الجدول 1 حسب مقياس التلوين (النسبة المئوية أو الترتيب المئوي)." + "\n" +
     "عمود المتوسط: الجدول 1 = متوسط بُعد السعر؛ الجدول 2 = الترتيب المئوي لمتوسط فارق الأزواج؛ الجدول 3 = الترتيب المئوي لسرعة التقارب الإجمالية (الأعلى = أسرع). المتوسط قراءة مركّبة، وليس متوسط القيم المعروضة." + "\n\n" +
     "Ordena los símbolos por Prom.; los símbolos que muestran n/d aparecen al final. La Tabla 1 ordena por la medida de color (% o percentil)." + "\n" +
     "Prom.: Tabla 1 = distancia media del precio; Tabla 2 = percentil del diferencial medio de los pares; Tabla 3 = percentil de la velocidad de convergencia global (más alto = más rápida). Prom. es un compuesto, no el promedio de los valores mostrados." + "\n\n" +
     "Sembolleri Ort. sütununa göre sıralar; 'yok' gösteren semboller en sonda görünür. Tablo 1, renklendirme ölçütüne (% veya yüzdelik) göre sıralanır." + "\n" +
     "Ort.: Tablo 1 = fiyatın ortalama uzaklığı; Tablo 2 = çiftlerin ortalama farkının yüzdeliği; Tablo 3 = genel yakınsama hızı yüzdeliği (yüksek = daha hızlı). Ort. bileşik bir değerdir; gösterilen değerlerin ortalaması değildir."
const string TIP_TYPE =
     "Sets the type of all moving averages. The checkboxes below control which MAs appear in Table 1 and enter its Avg. EMA is recommended for Table 3; SMA can shift abruptly when old bars leave its window, while HMA reacts faster but may overshoot." + "\n\n" +
     "يحدد نوع جميع المتوسطات المتحركة. تتحكم مربعات الاختيار أدناه في المتوسطات التي تظهر في الجدول 1 وتدخل في عمود المتوسط الخاص به. يُنصح بالمتوسط الأسي للجدول 3؛ فقد يتغير المتوسط البسيط فجأة عند خروج الأعمدة القديمة من نافذته، بينما يستجيب متوسط هال أسرع لكنه قد يتجاوز السعر." + "\n\n" +
     "Define el tipo de todas las medias móviles. Las casillas de abajo controlan qué medias aparecen en la Tabla 1 y entran en su Prom. Se recomienda EMA para la Tabla 3; una SMA puede cambiar bruscamente cuando las barras antiguas salen de su ventana, mientras que HMA reacciona más rápido pero puede rebasar el precio." + "\n\n" +
     "Tüm hareketli ortalamaların türünü belirler. Aşağıdaki onay kutuları Tablo 1'de hangi ortalamaların görüneceğini ve Ort. sütununa gireceğini kontrol eder. Tablo 3 için EMA önerilir; SMA eski çubuklar penceresinden çıktığında aniden değişebilir, HMA ise daha hızlı tepki verir ancak fiyatı aşabilir."
const string TIP_SRC =
     "Price source used to calculate all moving averages and price-to-MA distances. HL2 = (H+L)/2; HLC3 = (H+L+C)/3; OHLC4 = (O+H+L+C)/4; HLCC4 = (H+L+2C)/4." + "\n\n" +
     "مصدر السعر المستخدم في حساب جميع المتوسطات المتحركة وأبعاد السعر عن المتوسطات. HL2 = (H+L)/2، HLC3 = (H+L+C)/3، OHLC4 = (O+H+L+C)/4، HLCC4 = (H+L+2C)/4." + "\n\n" +
     "Fuente de precio usada para calcular todas las medias móviles y las distancias precio–media. HL2 = (H+L)/2; HLC3 = (H+L+C)/3; OHLC4 = (O+H+L+C)/4; HLCC4 = (H+L+2C)/4." + "\n\n" +
     "Tüm hareketli ortalamaları ve fiyat–ortalama uzaklıklarını hesaplamak için kullanılan fiyat kaynağı. HL2 = (H+L)/2; HLC3 = (H+L+C)/3; OHLC4 = (O+H+L+C)/4; HLCC4 = (H+L+2C)/4."
const string TIP_LOOK =
     "Number of past bars used to calculate percentiles. As a guideline, use a lookback at least as long as the longest MA (e.g., 252 bars for a 200-bar MA). Longer lookbacks produce more stable percentiles but are less responsive to changing market conditions. Also sets the lookback for normalizing the Table 2 and Table 3 Avg columns." + "\n\n" +
     "عدد الأعمدة السابقة المستخدمة لحساب الترتيب المئوي. كقاعدة عامة، اجعل الفترة المرجعية بطول أطول متوسط على الأقل (مثلًا 252 عمودًا لمتوسط 200 عمود). الفترات الأطول تعطي ترتيبًا مئويًا أكثر استقرارًا لكنها أقل استجابة لتغير ظروف السوق. وتحدد أيضًا فترة التوحيد المعياري لعمود المتوسط في الجدولين 2 و3." + "\n\n" +
     "Número de barras pasadas usadas para calcular los percentiles. Como referencia, usa una ventana al menos tan larga como la media más larga (p. ej., 252 barras para una media de 200 barras). Las ventanas más largas producen percentiles más estables, pero responden menos a los cambios del mercado. También define la ventana de normalización de la columna Prom. de las Tablas 2 y 3." + "\n\n" +
     "Yüzdelikleri hesaplamak için kullanılan geçmiş çubuk sayısı. Genel kural olarak, pencereyi en az en uzun ortalama kadar uzun tutun (ör. 200 çubukluk ortalama için 252 çubuk). Daha uzun pencereler daha istikrarlı yüzdelikler verir ancak değişen piyasa koşullarına daha yavaş tepki verir. Tablo 2 ve 3'teki Ort. sütununun normalizasyon penceresini de belirler."
const string TIP_X =
     "Marks MA pairs that crossed within the last X bars, including the current bar. Set to 0 to disable. In Table 3, marked pairs are excluded from Avg because a crossover can reverse the meaning of their convergence rate." + "\n\n" +
     "يضع علامة × على أزواج المتوسطات التي تقاطعت خلال عدد الأعمدة المحدد، بما فيها العمود الحالي. اجعل القيمة 0 لإلغائها. في الجدول 3 تُستبعد الأزواج المعلَّمة من المتوسط، لأن التقاطع قد يعكس معنى معدل تقاربها." + "\n\n" +
     "Marca los pares de medias que se cruzaron en las últimas X barras, incluida la barra actual. Pon 0 para desactivarlo. En la Tabla 3, los pares marcados se excluyen del Prom., porque un cruce puede invertir el significado de su ritmo de convergencia." + "\n\n" +
     "Son X çubuk içinde (mevcut çubuk dahil) kesişen ortalama çiftlerini işaretler. Kapatmak için 0 girin. Tablo 3'te işaretli çiftler Ort. dışında tutulur; çünkü kesişme, yakınsama hızlarının anlamını tersine çevirebilir."
const string TIP_CONV =
     "Number of bars used to calculate the average change in the spread between each MA pair. Shorter lookbacks react faster to changes in convergence speed but may be noisier; longer lookbacks produce smoother, more stable readings but respond more slowly." + "\n\n" +
     "عدد الأعمدة المستخدمة لحساب متوسط تغير الفارق بين كل زوج من المتوسطات. الفترات الأقصر تستجيب أسرع لتغيرات سرعة التقارب لكنها قد تكون أكثر تذبذبًا؛ والفترات الأطول تعطي قراءات أنعم وأكثر استقرارًا لكنها أبطأ استجابة." + "\n\n" +
     "Número de barras usadas para calcular el cambio medio del diferencial de cada par de medias. Los periodos más cortos reaccionan antes a los cambios en la velocidad de convergencia, pero pueden tener más ruido; los más largos dan lecturas más suaves y estables, pero responden más despacio." + "\n\n" +
     "Her ortalama çiftindeki farkın ortalama değişimini hesaplamak için kullanılan çubuk sayısı. Kısa pencereler yakınsama hızındaki değişimlere daha hızlı tepki verir ancak daha gürültülü olabilir; uzun pencereler daha yumuşak ve istikrarlı okumalar verir ancak daha yavaş tepki verir."
const string TIP_FLAT =
     "Sets the threshold below which the change in the spread between an MA pair is considered stable (=), meaning neither converging nor diverging. It acts as a noise filter and scales to each pair's typical rate, allowing comparisons across markets." + "\n\n" +
     "يحدد الحد الذي يُعد تغير الفارق بين زوج المتوسطات دونه مستقرًا (=)، أي لا تقارب ولا تباعد. يعمل كمرشّح للضوضاء ويتكيف مع المعدل المعتاد لكل زوج، مما يسمح بالمقارنة بين الأسواق." + "\n\n" +
     "Define el umbral por debajo del cual el cambio del diferencial de un par de medias se considera estable (=), es decir, ni converge ni diverge. Actúa como filtro de ruido y se adapta al ritmo típico de cada par, lo que permite comparar mercados." + "\n\n" +
     "Bir ortalama çiftinin farkındaki değişimin altında sabit (=) sayıldığı eşiği belirler; yani ne yakınsama ne ıraksama vardır. Gürültü filtresi görevi görür ve her çiftin tipik hızına göre ölçeklenir; böylece piyasalar arasında karşılaştırma yapılabilir."
const string TIP_SCALE =
     "Sets the percentage distance at which full colour intensity is reached. Applies to Table 1 and the pair columns of Table 2 when colouring by Percentage." + "\n\n" +
     "يحدد نسبة البُعد التي تبلغ عندها شدة اللون أقصاها. يُطبَّق على الجدول 1 وأعمدة الأزواج في الجدول 2 عند التلوين حسب النسبة المئوية." + "\n\n" +
     "Define la distancia porcentual a la que se alcanza la intensidad de color máxima. Se aplica a la Tabla 1 y a las columnas de pares de la Tabla 2 al colorear por Porcentaje." + "\n\n" +
     "Tam renk yoğunluğuna ulaşılan yüzde uzaklığı belirler. Yüzde ile renklendirmede Tablo 1'e ve Tablo 2'nin çift sütunlarına uygulanır."
const string TIP_THEME =
     "Auto matches the chart's background theme. Light and Dark use fixed colour schemes. Text colour automatically adapts to each cell's background." + "\n\n" +
     "«تلقائي» يطابق سمة خلفية الرسم البياني. «فاتح» و«داكن» يستخدمان نظامي ألوان ثابتين. يتكيف لون النص تلقائيًا مع خلفية كل خلية." + "\n\n" +
     "Automático se ajusta al tema de fondo del gráfico. Claro y Oscuro usan esquemas de color fijos. El color del texto se adapta automáticamente al fondo de cada celda." + "\n\n" +
     "Otomatik, grafiğin arka plan temasına uyar. Açık ve Koyu sabit renk düzenleri kullanır. Metin rengi her hücrenin arka planına otomatik olarak uyum sağlar."
const string TIP_FOOT =
     "Shows the legend and sort order below the table. Turn off for a more compact table." + "\n\n" +
     "يعرض الشرح وطريقة الترتيب أسفل الجدول. ألغِ تفعيله للحصول على جدول أكثر إيجازًا." + "\n\n" +
     "Muestra la leyenda y el orden debajo de la tabla. Desactívalo para una tabla más compacta." + "\n\n" +
     "Tablonun altında açıklamayı ve sıralamayı gösterir. Daha kompakt bir tablo için kapatın."
 
// ══ Inputs ════════════════════════════════════════════════════════════════
// Order: the settings most users change come first; specialist settings are
// grouped last under "Advanced", after the long ticker list.
 
// ── 1 · General ───────────────────────────────────────────────────────────
lang = input.string(L_EN, "Language / اللغة / Idioma / Dil", options = [L_EN, L_AR, L_ES, L_TR], group = GG, tooltip = TIP_LANG)
view = input.string(V1, "Table / الجدول / Tabla / Tablo", options = [V1, V2, V3], group = GG, tooltip = TIP_TABLE)
tf   = input.timeframe("D", "Timeframe / الإطار الزمني / Temporalidad / Zaman dilimi", group = GG, tooltip = TIP_TF)
 
// ── 2 · Display ───────────────────────────────────────────────────────────
// The Avg column is not a setting: it is shown whenever two or more MAs
// (Table 1) or pairs (Tables 2–3) are selected.
colMode = input.string(C_PCT, "Colour by / التلوين حسب / Color por / Renk ölçütü",
     options = [C_PCT, C_PCTL], group = GD, tooltip = TIP_COL)
sortSel = input.string(S_HIGH, "Sort by / الترتيب حسب / Ordenar por / Sıralama",
     options = [S_NONE, S_HIGH, S_LOW], group = GD, tooltip = TIP_SORT)
 
// ── 3 · Moving averages ───────────────────────────────────────────────────
maType = input.string("EMA", "MA type / نوع المتوسط / Tipo de media / Ortalama türü", options = ["EMA", "SMA", "WMA", "RMA", "HMA"], group = GM, tooltip = TIP_TYPE)
srcIn  = input.string(SRC_C, "Price source / مصدر السعر / Fuente de precio / Fiyat kaynağı",
     options = [SRC_C, SRC_O, SRC_H, SRC_L, "HL2", "HLC3", "OHLC4", "HLCC4"], group = GM, tooltip = TIP_SRC)
ma1On = input.bool(true, "MA 1", inline = "m1", group = GM)
len1  = input.int(10, "", minval = 2, maxval = 500, inline = "m1", group = GM)
ma2On = input.bool(true, "MA 2", inline = "m2", group = GM)
len2  = input.int(20, "", minval = 2, maxval = 500, inline = "m2", group = GM)
ma3On = input.bool(true, "MA 3", inline = "m3", group = GM)
len3  = input.int(50, "", minval = 2, maxval = 500, inline = "m3", group = GM)
ma4On = input.bool(true, "MA 4", inline = "m4", group = GM)
len4  = input.int(100, "", minval = 2, maxval = 500, inline = "m4", group = GM)
ma5On = input.bool(true, "MA 5", inline = "m5", group = GM)
len5  = input.int(200, "", minval = 2, maxval = 500, inline = "m5", group = GM)
pLen  = input.int(252, "Percentile lookback (bars) / الفترة المرجعية (أعمدة) / Ventana del percentil (barras) / Yüzdelik penceresi (çubuk)",
     minval = 20, maxval = 1000, group = GM, tooltip = TIP_LOOK)
 
// ── 4 · MA pairs (Tables 2–3) ─────────────────────────────────────────────
pr1On = input.bool(true, "Pair 1 / زوج 1 / Par 1 / Çift 1", inline = "p1", group = GP)
pr1F  = input.string("MA 1", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p1", group = GP)
pr1S  = input.string("MA 2", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p1", group = GP)
pr2On = input.bool(true, "Pair 2 / زوج 2 / Par 2 / Çift 2", inline = "p2", group = GP)
pr2F  = input.string("MA 2", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p2", group = GP)
pr2S  = input.string("MA 3", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p2", group = GP)
pr3On = input.bool(true, "Pair 3 / زوج 3 / Par 3 / Çift 3", inline = "p3", group = GP)
pr3F  = input.string("MA 3", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p3", group = GP)
pr3S  = input.string("MA 4", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p3", group = GP)
pr4On = input.bool(true, "Pair 4 / زوج 4 / Par 4 / Çift 4", inline = "p4", group = GP)
pr4F  = input.string("MA 4", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p4", group = GP)
pr4S  = input.string("MA 5", "", options = ["MA 1", "MA 2", "MA 3", "MA 4", "MA 5"], inline = "p4", group = GP)
 
// ── 5 · Tickers ───────────────────────────────────────────────────────────
// Defaults: 10 ticked (5 equities, 2 crypto, 2 FX, gold) and 5 unticked
// equities the user can switch on.
en1   = input.bool(true, "", inline = "t1", group = GT)
sym1  = input.symbol("NASDAQ:AAPL", "", inline = "t1", group = GT)
en2   = input.bool(true, "", inline = "t2", group = GT)
sym2  = input.symbol("NASDAQ:MSFT", "", inline = "t2", group = GT)
en3   = input.bool(true, "", inline = "t3", group = GT)
sym3  = input.symbol("NASDAQ:NVDA", "", inline = "t3", group = GT)
en4   = input.bool(true, "", inline = "t4", group = GT)
sym4  = input.symbol("NASDAQ:AMZN", "", inline = "t4", group = GT)
en5   = input.bool(true, "", inline = "t5", group = GT)
sym5  = input.symbol("NASDAQ:TSLA", "", inline = "t5", group = GT)
en6   = input.bool(true, "", inline = "t6", group = GT)
sym6  = input.symbol("BITSTAMP:BTCUSD", "", inline = "t6", group = GT)
en7   = input.bool(true, "", inline = "t7", group = GT)
sym7  = input.symbol("BITSTAMP:ETHUSD", "", inline = "t7", group = GT)
en8   = input.bool(true, "", inline = "t8", group = GT)
sym8  = input.symbol("FX:EURUSD", "", inline = "t8", group = GT)
en9   = input.bool(true, "", inline = "t9", group = GT)
sym9  = input.symbol("FX:GBPUSD", "", inline = "t9", group = GT)
en10  = input.bool(true, "", inline = "t10", group = GT)
sym10 = input.symbol("OANDA:XAUUSD", "", inline = "t10", group = GT)
en11  = input.bool(false, "", inline = "t11", group = GT)
sym11 = input.symbol("NASDAQ:GOOGL", "", inline = "t11", group = GT)
en12  = input.bool(false, "", inline = "t12", group = GT)
sym12 = input.symbol("NASDAQ:META", "", inline = "t12", group = GT)
en13  = input.bool(false, "", inline = "t13", group = GT)
sym13 = input.symbol("NASDAQ:AMD", "", inline = "t13", group = GT)
en14  = input.bool(false, "", inline = "t14", group = GT)
sym14 = input.symbol("NASDAQ:AVGO", "", inline = "t14", group = GT)
en15  = input.bool(false, "", inline = "t15", group = GT)
sym15 = input.symbol("NASDAQ:MU", "", inline = "t15", group = GT)
 
// ── 6 · Appearance ────────────────────────────────────────────────────────
tPos   = input.string(position.top_right, "Position / الموضع / Posición / Konum",
     options = [position.top_right, position.middle_right, position.bottom_right, position.top_left, position.middle_left, position.bottom_left, position.top_center, position.bottom_center], group = GA)
tSize  = input.string(size.normal, "Text size / حجم النص / Tamaño del texto / Yazı boyutu",
     options = [size.tiny, size.small, size.normal], group = GA)
theme  = input.string(TH_AUTO, "Theme / السمة / Tema / Tema", options = [TH_AUTO, TH_LIGHT, TH_DARK], group = GA, tooltip = TIP_THEME)
showFoot = input.bool(true, "Show legend / إظهار الشرح / Mostrar leyenda / Açıklamayı göster", group = GA, tooltip = TIP_FOOT)
 
// ── 7 · Advanced (defaults suit most users) ───────────────────────────────
flatBand = input.float(0.25, "Stability threshold (× typical rate) / حد الاستقرار (× المعدل المعتاد) / Umbral de estabilidad (× ritmo típico) / Sabitlik eşiği (× tipik hız)",
     minval = 0.0, step = 0.05, group = GX, tooltip = TIP_FLAT)
nConv    = input.int(5, "Convergence bars / أعمدة التقارب / Barras de convergencia / Yakınsama çubukları",
     minval = 1, maxval = 100, group = GX, tooltip = TIP_CONV)
xWin  = input.int(5, "Mark crossovers within (bars) / علامة التقاطع خلال (أعمدة) / Marcar cruces en (barras) / Kesişme işareti (çubuk)",
     minval = 0, group = GX, tooltip = TIP_X)
pctScale = input.float(5.0, "Full colour at ± % / اللون الكامل عند ± % / Color pleno en ± % / Tam renk: ± %",
     minval = 0.1, step = 0.5, group = GX, tooltip = TIP_SCALE)
 
// ══ Colour scheme ═════════════════════════════════════════════════════════
// Perceived brightness, 0 (black) to 255 (white).
lum(color c) =>
    0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)
 
bool  isDark  = theme == TH_DARK ? true : theme == TH_LIGHT ? false : lum(chart.bg_color) < 128
color themeBg = theme == TH_AUTO ? chart.bg_color : isDark ? #131722 : #FFFFFF
 
// Opaque backgrounds, so the table looks the same whatever is behind it.
color CELL = isDark ? #2A2E39 : #F0F3FA
color HEAD = isDark ? #434651 : #D1D4DC
 
// Text colour chosen from the cell's own background, not from the chart.
textOn(color bg) =>
    lum(bg) < 140 ? #FFFFFF : #131722
 
// ══ Translation ═══════════════════════════════════════════════════════════
// Returns the table text in the selected language.
T(string en, string ar, string es, string tk) =>
    lang == L_AR ? ar : lang == L_ES ? es : lang == L_TR ? tk : en
 
// Keeps arrows / fractions in left-to-right order inside Arabic lines.
ltr(string s) =>
    LRM + s + LRM
 
string NA_TXT = T("n/a", "غ/م", "n/d", "yok")
 
srcName() =>
    srcIn == SRC_C ? T("Close", "الإغلاق", "Cierre", "Kapanış") :
         srcIn == SRC_O ? T("Open", "الافتتاح", "Apertura", "Açılış") :
         srcIn == SRC_H ? T("High", "الأعلى", "Máximo", "Yüksek") :
         srcIn == SRC_L ? T("Low", "الأدنى", "Mínimo", "Düşük") : srcIn
 
lookTxt() =>
    T("percentile lookback ", "الفترة المرجعية ", "ventana del percentil ", "yüzdelik penceresi ") + str.tostring(pLen)
 
// Table timeframe as shown in TradingView's menu ("1 day", "4 hours",
// "30 minutes"), in the selected language. An empty input means the chart's
// timeframe. Codes: number = minutes, S = seconds, D/W/M = days/weeks/months.
tfName() =>
    string t    = tf == "" ? timeframe.period : tf
    int    tl   = str.length(t)
    string last = str.substring(t, tl - 1)
    bool   unit = last == "S" or last == "D" or last == "W" or last == "M"
    string numS = unit ? str.substring(t, 0, tl - 1) : t
    int    n    = numS == "" ? 1 : int(str.tonumber(numS))
    string k    = unit ? last : n % 60 == 0 ? "H" : "m"
    if k == "H"
        n := int(n / 60)
    bool   one  = n == 1
    string num  = str.tostring(n) + " "
    string en = switch k
        "S" => one ? "second" : "seconds"
        "m" => one ? "minute" : "minutes"
        "H" => one ? "hour" : "hours"
        "D" => one ? "day" : "days"
        "W" => one ? "week" : "weeks"
        => one ? "month" : "months"
    string es = switch k
        "S" => one ? "segundo" : "segundos"
        "m" => one ? "minuto" : "minutos"
        "H" => one ? "hora" : "horas"
        "D" => one ? "día" : "días"
        "W" => one ? "semana" : "semanas"
        => one ? "mes" : "meses"
    string tk = switch k
        "S" => "saniye"
        "m" => "dakika"
        "H" => "saat"
        "D" => "gün"
        "W" => "hafta"
        => "ay"
    // Arabic: 1 → singular, 2 → dual, 3–10 → plural, 11+ → singular (accusative)
    string ar = switch k
        "S" => one ? "ثانية" : n == 2 ? "ثانيتان" : n <= 10 ? num + "ثوانٍ" : num + "ثانية"
        "m" => one ? "دقيقة" : n == 2 ? "دقيقتان" : n <= 10 ? num + "دقائق" : num + "دقيقة"
        "H" => one ? "ساعة" : n == 2 ? "ساعتان" : n <= 10 ? num + "ساعات" : num + "ساعة"
        "D" => one ? "يوم" : n == 2 ? "يومان" : n <= 10 ? num + "أيام" : num + "يومًا"
        "W" => one ? "أسبوع" : n == 2 ? "أسبوعان" : n <= 10 ? num + "أسابيع" : num + "أسبوعًا"
        => one ? "شهر" : n == 2 ? "شهران" : n <= 10 ? num + "أشهر" : num + "شهرًا"
    T(num + en, ar, num + es, num + tk)
 
// ── Helpers: input lookups ────────────────────────────────────────────────
maIdx(string s) =>
    switch s
        "MA 1" => 1
        "MA 2" => 2
        "MA 3" => 3
        "MA 4" => 4
        => 5
 
lenOf(int i) =>
    switch i
        1 => len1
        2 => len2
        3 => len3
        4 => len4
        => len5
 
maOn(int i) =>
    switch i
        1 => ma1On
        2 => ma2On
        3 => ma3On
        4 => ma4On
        => ma5On
 
prOn(int k) =>
    switch k
        1 => pr1On
        2 => pr2On
        3 => pr3On
        => pr4On
 
int pf1 = maIdx(pr1F)
int ps1 = maIdx(pr1S)
int pf2 = maIdx(pr2F)
int ps2 = maIdx(pr2S)
int pf3 = maIdx(pr3F)
int ps3 = maIdx(pr3S)
int pf4 = maIdx(pr4F)
int ps4 = maIdx(pr4S)
 
pfOf(int k) =>
    switch k
        1 => pf1
        2 => pf2
        3 => pf3
        => pf4
 
psOf(int k) =>
    switch k
        1 => ps1
        2 => ps2
        3 => ps3
        => ps4
 
// An enabled pair whose two MAs have the same length (the same MA twice, or
// two MAs set to the same length) has no fast side and a spread that is
// always zero, so it would turn every composite into n/a. Instead of the
// table, a message is shown in the table's position (in the selected
// language), so the user sees the cause where they are looking. Only
// Tables 2–3 use the pairs, so Table 1 is never blocked by a pair setting.
string pairErr = ""
for k = 1 to 4
    if view != V1 and prOn(k) and pairErr == ""
        int a = lenOf(pfOf(k))
        int b = lenOf(psOf(k))
        if a == b
            string n = str.tostring(k)
            string l = ltr(str.tostring(a) + " / " + str.tostring(b))
            pairErr := T(
                 "⚠ Pair " + n + " uses two MAs of the same length (" + l + ").\nChoose two MAs with different lengths, or untick the pair.",
                 "⚠ الزوج " + n + " يستخدم متوسطين بالطول نفسه (" + l + ").\nاختر متوسطين بطولين مختلفين، أو ألغِ تحديد الزوج.",
                 "⚠ El par " + n + " usa dos medias de la misma longitud (" + l + ").\nElija dos medias de longitudes distintas o desactive el par.",
                 "⚠ Çift " + n + " aynı uzunlukta iki ortalama kullanıyor (" + l + ").\nFarklı uzunlukta iki ortalama seçin veya çifti devre dışı bırakın.")
 
// Column header of a pair, always fast / slow (matches the oriented spread).
pairHdr(int k) =>
    int a = lenOf(pfOf(k))
    int b = lenOf(psOf(k))
    str.tostring(math.min(a, b)) + " / " + str.tostring(math.max(a, b))
 
// Composite settings: how many MAs / pairs enter each average, and the
// warm-up needed by the longest MA involved.
// Table 1 duplicates: a ticked MA whose length equals an earlier ticked MA.
// The first occurrence stays active; later ones are shown with dashes and
// left out of the composite, so no length counts twice.
dupOf(int m) =>
    bool d = false
    if m > 1 and maOn(m)
        for j = 1 to m - 1
            if maOn(j) and lenOf(j) == lenOf(m)
                d := true
    d
 
bool dup2   = dupOf(2)
bool dup3   = dupOf(3)
bool dup4   = dupOf(4)
bool dup5   = dupOf(5)
bool anyDup = dup2 or dup3 or dup4 or dup5
 
isDup(int m) =>
    switch m
        2 => dup2
        3 => dup3
        4 => dup4
        5 => dup5
        => false
 
int nMa   = (ma1On ? 1 : 0) + (ma2On and not dup2 ? 1 : 0) + (ma3On and not dup3 ? 1 : 0) +
     (ma4On and not dup4 ? 1 : 0) + (ma5On and not dup5 ? 1 : 0)
int warmG = math.max(ma1On ? len1 : 0, ma2On ? len2 : 0, ma3On ? len3 : 0, ma4On ? len4 : 0, ma5On ? len5 : 0)
int nPr   = (pr1On ? 1 : 0) + (pr2On ? 1 : 0) + (pr3On ? 1 : 0) + (pr4On ? 1 : 0)
int warmA = math.max(pr1On ? math.max(lenOf(pf1), lenOf(ps1)) : 0,
                     pr2On ? math.max(lenOf(pf2), lenOf(ps2)) : 0,
                     pr3On ? math.max(lenOf(pf3), lenOf(ps3)) : 0,
                     pr4On ? math.max(lenOf(pf4), lenOf(ps4)) : 0)
 
// Nothing selected: with no ticked MA (Table 1) or no ticked pair (Tables
// 2–3) the table would show only the Ticker (and Price) column, which looks
// broken. A message is shown instead, in the same way as the pair error.
if pairErr == "" and view == V1 and nMa == 0
    pairErr := T("⚠ No MA selected. Tick at least one MA.",
                 "⚠ لم يُحدَّد أي متوسط. حدّد متوسطًا واحدًا على الأقل.",
                 "⚠ Ninguna media seleccionada. Active al menos una media.",
                 "⚠ Ortalama seçilmedi. En az bir ortalamayı işaretleyin.")
if pairErr == "" and view != V1 and nPr == 0
    pairErr := T("⚠ No pair selected. Tick at least one pair.",
                 "⚠ لم يُحدَّد أي زوج. حدّد زوجًا واحدًا على الأقل.",
                 "⚠ Ningún par seleccionado. Active al menos un par.",
                 "⚠ Çift seçilmedi. En az bir çifti işaretleyin.")
 
// Fastest MA among the enabled pairs (shortest length): its slope gives the
// direction part of the Table 3 price-action label.
int fastIdx = 0
int fastLen = 0
for k = 1 to 4
    if prOn(k)
        int a = pfOf(k)
        int b = psOf(k)
        int c = lenOf(a) <= lenOf(b) ? a : b
        if fastIdx == 0 or lenOf(c) < fastLen
            fastIdx := c
            fastLen := lenOf(c)
 
// Cap for each pair's scaled rate in the Table 3 composite, in typical sizes
// (RMS units), so one extreme pair cannot outweigh the others.
const float ZCAP = 2.0
 
// Minimum share of valid (non-na) values in a percentile window. With fewer,
// the percentile is shown as n/a. Engineering choice, not a mathematical
// requirement. The input caps (MA length ≤ 500, convergence bars ≤ 100) are
// engineering limits too, set to keep history and load time manageable.
const float MIN_VALID = 0.8
 
// Rows are only built for bars within this window of the last bar
// (last_bar_time, so Bar Replay's cut-off is respected):
// 30 bars of the table timeframe, but never less than 10 days, so a ticker
// whose market is closed (weekend, holiday) still has its last bar covered.
int keepMs = math.max(30 * timeframe.in_seconds(tf), 10 * 86400) * 1000
 
// History each ticker needs: MA warm-up + RMS window + percentile window +
// convergence window + margin. EMA/RMA depend on their starting value, so
// they get a longer warm-up (remaining effect of the starting value ≈ e^-8,
// negligible). The extra pLen covers the RMS scaling of the Table 2–3
// composites, which must be filled before those composites are ranked.
int maxLen   = math.max(len1, len2, len3, len4, len5)
int warmMul  = maType == "RMA" ? 8 : maType == "EMA" ? 4 : 1
int needBars = maxLen * warmMul + 2 * pLen + nConv + 60
 
// ── Helpers: calculations (run inside request.security) ───────────────────
// Source is chosen by name and resolved here, so it uses each ticker's own
// OHLC. (input.source() would return the CHART symbol's series instead.)
srcOf() =>
    srcIn == SRC_O ? open :
         srcIn == SRC_H ? high :
         srcIn == SRC_L ? low :
         srcIn == "HL2" ? hl2 :
         srcIn == "HLC3" ? hlc3 :
         srcIn == "OHLC4" ? ohlc4 :
         srcIn == "HLCC4" ? hlcc4 : close
 
maCalc(float src, simple int len) =>
    switch maType
        "SMA" => ta.sma(src, len)
        "WMA" => ta.wma(src, len)
        "RMA" => ta.rma(src, len)
        "HMA" => ta.hma(src, len)
        => ta.ema(src, len)
 
pick(int i, float a1, float a2, float a3, float a4, float a5) =>
    switch i
        1 => a1
        2 => a2
        3 => a3
        4 => a4
        => a5
 
// Percentile of x among its previous pLen values (% of previous values ≤
// current, same definition as ta.percentrank). Masked until the inputs and
// the percentile window have enough history. Computed only for bars kept for the
// table, so older bars cost nothing.
// na values in the window (e.g. Table 3's Avg when every pair crossed
// recently) are skipped and the percentile is taken over the valid values
// only, so missing history does not bias it low. If fewer than MIN_VALID of
// the window is valid, the result is n/a.
pr(float x, int warmLen) =>
    float r = na
    if time >= last_bar_time - keepMs and bar_index >= warmLen + pLen and not na(x)
        int cnt = 0
        int nV  = 0
        for i = 1 to pLen
            float h = x[i]
            if not na(h)
                nV += 1
                if h <= x
                    cnt += 1
        r := nV >= MIN_VALID * pLen ? 100.0 * cnt / nV : na
    r
 
// Root mean square over the percentile window: typical size of x around ZERO (not
// around its mean), so dividing by it keeps the sign and the zero point.
rms(float x) =>
    math.sqrt(ta.sma(x * x, pLen))
 
// Scaled rate capped at ±ZCAP for the Table 3 composite (na stays na).
capZ(float z) =>
    na(z) ? na : math.max(-ZCAP, math.min(ZCAP, z))
 
// One MA pair, for Tables 2 and 3.
//   sp : log spread, % (Table 2 value; > 0 = faster MA above slower)
//   sq : percentile of sp
//   sx : bars since the MAs last crossed
//   lz : sp / RMS(sp)  — scaled level, feeds the Table 2 composite
//   (ds : change of sp per bar over nConv bars, used internally)
//   dz : sign(sp)·ds / RMS(sign(sp)·ds) — scaled divergence rate
//        (> 0 diverging, < 0 converging), sets the Table 3 state and composite
//   cp : percentile of the convergence rate −sign(sp)·ds
//        (high = closing fastest vs own history), Table 3 value
pairCalc(int fi, int si, float m1, float m2, float m3, float m4, float m5) =>
    // Oriented by length: f is always the shorter (faster) MA, so sp > 0
    // means fast above slow whatever order the pair was entered in.
    bool  sw = lenOf(fi) > lenOf(si)
    float f  = pick(sw ? si : fi, m1, m2, m3, m4, m5)
    float l  = pick(sw ? fi : si, m1, m2, m3, m4, m5)
    int   w  = math.max(lenOf(fi), lenOf(si))
    float sp = 100 * math.log(f / l)
    float sq = pr(sp, w)
    float sx = nz(float(ta.barssince(ta.cross(sp, 0))), 1e9)
    float rL = rms(sp)
    float lz = na(rL) ? na : rL > 0 ? sp / rL : 0.0
    float ds = (sp - sp[nConv]) / nConv
    float dv = math.sign(sp) * ds
    float rR = rms(dv)
    float dz = na(rR) ? na : rR > 0 ? dv / rR : 0.0
    float cp = pr(-dv, w + nConv)
    [sp, sq, sx, lz, dz, cp]
 
type Row
    float price
    // Table 1: log gap of price from each MA, and its percentile
    float g1
    float g2
    float g3
    float g4
    float g5
    float q1
    float q2
    float q3
    float q4
    float q5
    // Table 2: log spread of each pair, percentile, bars since last cross
    float a1
    float a2
    float a3
    float a4
    float aq1
    float aq2
    float aq3
    float aq4
    float ax1
    float ax2
    float ax3
    float ax4
    // Table 3: convergence-speed percentile, scaled divergence rate
    // (> 0 diverging, < 0 converging)
    float c1
    float c2
    float c3
    float c4
    float z1
    float z2
    float z3
    float z4
    // Composites
    float gA     // Table 1: mean log gap across displayed MAs
    float gAP    // percentile of gA
    float aZ     // Table 2: mean RMS-scaled spread across enabled pairs
    float aAP    // percentile of aZ
    float cvA    // Table 3: −mean capped RMS-scaled divergence rate (high = closing fastest)
    float cvAP   // percentile of cvA
    float fs     // Table 3: slope of the fastest MA, RMS-scaled (> 0 rising)
 
calc() =>
    float src = srcOf()
    // Moving averages
    float m1 = maCalc(src, len1)
    float m2 = maCalc(src, len2)
    float m3 = maCalc(src, len3)
    float m4 = maCalc(src, len4)
    float m5 = maCalc(src, len5)
    // Table 1: log gap of price from each MA, and its percentile
    float g1 = 100 * math.log(src / m1)
    float g2 = 100 * math.log(src / m2)
    float g3 = 100 * math.log(src / m3)
    float g4 = 100 * math.log(src / m4)
    float g5 = 100 * math.log(src / m5)
    float q1 = pr(g1, len1)
    float q2 = pr(g2, len2)
    float q3 = pr(g3, len3)
    float q4 = pr(g4, len4)
    float q5 = pr(g5, len5)
    // Tables 2–3: every pair
    [a1, aq1, ax1, lz1, z1, c1] = pairCalc(pf1, ps1, m1, m2, m3, m4, m5)
    [a2, aq2, ax2, lz2, z2, c2] = pairCalc(pf2, ps2, m1, m2, m3, m4, m5)
    [a3, aq3, ax3, lz3, z3, c3] = pairCalc(pf3, ps3, m1, m2, m3, m4, m5)
    [a4, aq4, ax4, lz4, z4, c4] = pairCalc(pf4, ps4, m1, m2, m3, m4, m5)
    // Composite, Table 1: mean log gap over displayed MAs (duplicates
    // excluded), then its percentile.
    // Any na input (warm-up) makes the mean na, so it never uses a partial set.
    float sG = 0.0
    if ma1On
        sG += g1
    if ma2On and not dup2
        sG += g2
    if ma3On and not dup3
        sG += g3
    if ma4On and not dup4
        sG += g4
    if ma5On and not dup5
        sG += g5
    float gA  = nMa > 0 ? sG / nMa : na
    float gAP = pr(gA, warmG)
    // Composite, Table 2: mean of RMS-scaled spreads over enabled pairs,
    // then its percentile. Equal weight per pair, no telescoping.
    float sL = 0.0
    if pr1On
        sL += lz1
    if pr2On
        sL += lz2
    if pr3On
        sL += lz3
    if pr4On
        sL += lz4
    float aZ  = nPr > 0 ? sL / nPr : na
    float aAP = pr(aZ, warmA + pLen)
    // Composite, Table 3: mean of RMS-scaled divergence rates over enabled
    // pairs, each capped at ±ZCAP, sign flipped so high = closing fastest,
    // then its percentile. Pairs that crossed within the last xWin bars
    // (bars since cross < xWin, latest bar included) are left out:
    // at a cross the same motion flips from closing to widening, which would
    // swing the composite. If every pair crossed recently, the value is na.
    float sD = 0.0
    int   nD = 0
    if pr1On and ax1 >= xWin
        sD += capZ(z1)
        nD += 1
    if pr2On and ax2 >= xWin
        sD += capZ(z2)
        nD += 1
    if pr3On and ax3 >= xWin
        sD += capZ(z3)
        nD += 1
    if pr4On and ax4 >= xWin
        sD += capZ(z4)
        nD += 1
    float cvA  = nD > 0 ? -sD / nD : na
    float cvAP = pr(cvA, warmA + nConv + pLen)
    // Table 3 price-action direction: slope of the fastest MA over nConv
    // bars, in units of its own RMS (> 0 rising, < 0 falling).
    float FM  = pick(fastIdx, m1, m2, m3, m4, m5)
    float fsl = 100 * (math.log(FM) - math.log(FM[nConv])) / nConv
    float rF  = rms(fsl)
    float fs  = na(rF) ? na : rF > 0 ? fsl / rF : 0.0
    //
    // Memory: a new Row on every bar of every ticker (15 × thousands of bars ×
    // 38 fields) exceeds the memory limit. All calculations above still run on
    // every bar, but a Row is only allocated for recent bars, which are the
    // only ones the table reads. Older bars share one empty Row per ticker.
    var Row EMPTY = Row.new()
    time >= last_bar_time - keepMs ?
         Row.new(price = src,
             g1 = g1, g2 = g2, g3 = g3, g4 = g4, g5 = g5,
             q1 = q1, q2 = q2, q3 = q3, q4 = q4, q5 = q5,
             a1 = a1, a2 = a2, a3 = a3, a4 = a4,
             aq1 = aq1, aq2 = aq2, aq3 = aq3, aq4 = aq4,
             ax1 = ax1, ax2 = ax2, ax3 = ax3, ax4 = ax4,
             c1 = c1, c2 = c2, c3 = c3, c4 = c4,
             z1 = z1, z2 = z2, z3 = z3, z4 = z4,
             gA = gA, gAP = gAP, aZ = aZ, aAP = aAP, cvA = cvA, cvAP = cvAP, fs = fs) : EMPTY
 
// ── Data requests: one call per ticker ────────────────────────────────────
// A disabled ticker requests the chart's own symbol instead of its own, so
// unticking it avoids loading and calculating that ticker's history.
//
// Confirmed bars only: calc()[1] with lookahead_on returns each ticker's last
// CLOSED bar of the table timeframe. The table does not change while a bar is
// forming; it updates once, when the bar closes (daily → once a day, 1H →
// once an hour). This is TradingView's standard non-repainting pattern.
//
// calc_bars_count limits each ticker to the bars the calculations need,
// instead of its full history.
Row r1  = request.security(en1  ? sym1  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r2  = request.security(en2  ? sym2  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r3  = request.security(en3  ? sym3  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r4  = request.security(en4  ? sym4  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r5  = request.security(en5  ? sym5  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r6  = request.security(en6  ? sym6  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r7  = request.security(en7  ? sym7  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r8  = request.security(en8  ? sym8  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r9  = request.security(en9  ? sym9  : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r10 = request.security(en10 ? sym10 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r11 = request.security(en11 ? sym11 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r12 = request.security(en12 ? sym12 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r13 = request.security(en13 ? sym13 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r14 = request.security(en14 ? sym14 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
Row r15 = request.security(en15 ? sym15 : syminfo.tickerid, tf, calc()[1], lookahead = barmerge.lookahead_on, calc_bars_count = needBars)
 
// ── Row accessors ─────────────────────────────────────────────────────────
method gap(Row r, int i) =>
    switch i
        1 => r.g1
        2 => r.g2
        3 => r.g3
        4 => r.g4
        => r.g5
 
method gapP(Row r, int i) =>
    switch i
        1 => r.q1
        2 => r.q2
        3 => r.q3
        4 => r.q4
        => r.q5
 
method spr(Row r, int k) =>
    switch k
        1 => r.a1
        2 => r.a2
        3 => r.a3
        => r.a4
 
method sprP(Row r, int k) =>
    switch k
        1 => r.aq1
        2 => r.aq2
        3 => r.aq3
        => r.aq4
 
method sinceX(Row r, int k) =>
    switch k
        1 => r.ax1
        2 => r.ax2
        3 => r.ax3
        => r.ax4
 
// Table 3: convergence-speed percentile (high = closing fastest)
method cvp(Row r, int k) =>
    switch k
        1 => r.c1
        2 => r.c2
        3 => r.c3
        => r.c4
 
// Table 3: scaled divergence rate (> 0 diverging, < 0 converging)
method dz(Row r, int k) =>
    switch k
        1 => r.z1
        2 => r.z2
        3 => r.z3
        => r.z4
 
// Table 3 state: −1 converging, +1 diverging, 0 stable (or n/a).
// Sign of the rate, with a stable band in units of the pair's own RMS rate.
method st(Row r, int k) =>
    float z = r.dz(k)
    na(z) ? 0 : z > flatBand ? 1 : z < -flatBand ? -1 : 0
 
// ── Helpers: formatting and colour ────────────────────────────────────────
tickName(string s) =>
    array<string> p = str.split(s, ":")
    p.size() > 0 ? p.last() : s
 
// Log % → simple %: 100 × (e^(x/100) − 1). Used for display and % colouring only.
logToPct(float x) =>
    na(x) ? na : 100 * (math.exp(x / 100) - 1)
 
fPct(float x) =>
    na(x) ? NA_TXT : (x >= 0 ? "+" : "") + str.tostring(x, "0.0") + "%"
 
// Table 3 price-action label from all enabled pairs (see header):
//   trend     = majority of pairs with the faster MA on top (tie → Uncertain)
//   direction = RMS-scaled slope of the fastest MA (within band → Sideways)
//   momentum  = composite cvA: > band closing (slower), < −band widening
//               (faster), otherwise stable
method paLabel(Row r) =>
    int nUp = 0
    int nDn = 0
    for k = 1 to 4
        if prOn(k)
            float v = r.spr(k)
            if v > 0
                nUp += 1
            else if v < 0
                nDn += 1
    string out = NA_TXT
    if not na(r.fs) and not na(r.cvA) and nUp + nDn > 0
        int tr  = nUp > nDn ? 1 : nUp < nDn ? -1 : 0
        int dir = r.fs > flatBand ? 1 : r.fs < -flatBand ? -1 : 0
        int mom = r.cvA > flatBand ? -1 : r.cvA < -flatBand ? 1 : 0
        string adj = mom == 1 ? T(" faster", " أسرع", " acelera", " hızlı") :
             mom == -1 ? T(" slower", " أبطأ", " frena", " yavaş") :
             T(" stable", " مستقر", " estable", " sabit")
        out := tr == 0 ? "◆ " + T("Uncertain", "غير مؤكد", "Incierto", "Belirsiz") :
             dir == 0 ? "◆ " + T("Sideways", "عرضي", "Lateral", "Yatay seyir") :
             tr == 1 and dir == -1 ? "▼ " + T("Pullback", "تراجع", "Retroceso", "Geri çekilme") :
             tr == -1 and dir == 1 ? "▲ " + T("Rebound", "ارتداد صاعد", "Rebote", "Tepki yükselişi") :
             tr == 1 ? "▲ " + T("Rise", "صعود", "Alza", "Yükseliş") + adj :
             "▼ " + T("Decline", "هبوط", "Caída", "Düşüş") + adj
    out
 
// Bar count with the right noun form in each language. Arabic (after a
// preposition such as خلال / آخر): 1 → عمود واحد, 2 → عمودين, 3–10 → أعمدة,
// 11–99 → عمودًا; hundreds follow the last two digits (100 → عمود).
barsTxt(int n) =>
    int    m  = n % 100
    string ns = str.tostring(n)
    string ar = n == 1 ? "عمود واحد" : n == 2 ? "عمودين" :
         m >= 3 and m <= 10 ? ns + " أعمدة" : m >= 11 ? ns + " عمودًا" : ns + " عمود"
    T(ns + (n == 1 ? " bar" : " bars"), ar, ns + (n == 1 ? " barra" : " barras"), ns + " çubuk")
 
fRank(float p) =>
    na(p) ? "" : str.tostring(math.round(p))
 
fPrice(float p) =>
    na(p) ? NA_TXT : p >= 1000 ? str.tostring(p, "#,##0") : p >= 10 ? str.tostring(p, "0.00") : str.tostring(p, "0.0000")
 
dPct(float p) =>
    na(p) ? na : (p - 50.0) / 50.0
 
dVal(float x) =>
    na(x) ? na : x / pctScale
 
// Keeps a tie-break term small and bounded.
clampT(float v) =>
    math.max(-100.0, math.min(100.0, v))
 
// d in [−1, 1]: positive → green, negative → red, darker with |d|.
// |d| < 0.1 (percentile 45–55, or a very small %) stays neutral.
heat(float d) =>
    color bg = na
    color fg = na
    if not na(d)
        float a = math.min(math.abs(d), 1.0)
        int lvl = a < 0.1 ? 0 : math.max(1, math.min(5, int(math.ceil(a * 5))))
        if lvl > 0
            bg := d > 0 ?
                 (lvl == 1 ? #C8E6C9 : lvl == 2 ? #81C784 : lvl == 3 ? #43A047 : lvl == 4 ? #2E7D32 : #1B5E20) :
                 (lvl == 1 ? #FFCDD2 : lvl == 2 ? #E57373 : lvl == 3 ? #E53935 : lvl == 4 ? #C62828 : #8E1515)
            fg := lvl >= 3 ? color.white : color.black
    [bg, fg]
 
// Neutral scale for Table 3, which measures the MA gap, not price direction:
// blue = closing fast (high percentile), amber = widening fast (low
// percentile). Green / red are kept for Tables 1–2.
// Direction colours for the Table 3 price-action text (same meaning as
// green / red in Tables 1–2).
color UPC = #089981
color DNC = #F23645
 
// Softened shades (lighter than Tables 1–2), so direction colours stay the
// strongest signal in the indicator; all five levels take dark text.
// Text colour is left to put(), which picks it from the background.
heatN(float d) =>
    color bg = na
    if not na(d)
        float a = math.min(math.abs(d), 1.0)
        int lvl = a < 0.1 ? 0 : math.max(1, math.min(5, int(math.ceil(a * 5))))
        if lvl > 0
            bg := d > 0 ?
                 (lvl == 1 ? #E3F2FD : lvl == 2 ? #BBDEFB : lvl == 3 ? #90CAF9 : lvl == 4 ? #64B5F6 : #42A5F5) :
                 (lvl == 1 ? #FFF3E0 : lvl == 2 ? #FFE0B2 : lvl == 3 ? #FFCC80 : lvl == 4 ? #FFB74D : #FFA726)
    color fg = na
    [bg, fg]
 
put(table t, int c, int r, string txt, color bg = na, color fg = na, string ha = text.align_center) =>
    t.cell(c, r, txt, text_color = na(fg) ? textOn(na(bg) ? CELL : bg) : fg, bgcolor = na(bg) ? CELL : bg,
         text_size = tSize, text_halign = ha)
 
// ── Rendering (last bar only) ─────────────────────────────────────────────
var table tbl = na
 
if barstate.islast
    if not na(tbl)
        tbl.delete()
    // Pair-setting error: one message cell instead of the table.
    if pairErr != ""
        tbl := table.new(tPos, 1, 1, border_width = 1, border_color = themeBg)
        put(tbl, 0, 0, pairErr, HEAD, na, lang == L_AR ? text.align_right : text.align_left)
    else
        // 8 columns: Table 1 needs up to 8 (Ticker, Price, 5 MAs, Avg);
        // Tables 2–3 use up to 6 (Ticker, 4 pairs, Avg).
        tbl := table.new(tPos, 8, 18, border_width = 1, border_color = themeBg)
 
        array<Row>    rows = array.from(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15)
        array<string> syms = array.from(sym1, sym2, sym3, sym4, sym5, sym6, sym7, sym8, sym9, sym10, sym11, sym12, sym13, sym14, sym15)
        array<bool>   ens  = array.from(en1, en2, en3, en4, en5, en6, en7, en8, en9, en10, en11, en12, en13, en14, en15)
        array<int>    act  = array.new<int>()
        for i = 0 to 14
            if ens.get(i)
                act.push(i)
        int nRows = act.size()
 
        // Avg is shown only when it combines something: two or more MAs
        // (Table 1, duplicates not counted) or two or more pairs (Tables 2–3).
        // With one MA or pair it would repeat that column, so it is hidden and
        // the sort uses that column instead (Table 1's Avg equals it exactly).
        bool avgOn = view == V1 ? nMa >= 2 : nPr >= 2
        int  onePr = pr1On ? 1 : pr2On ? 2 : pr3On ? 3 : 4
 
        // Row order, all tables. The sort key is the composite that colours the
        // Avg column: Table 1 → composite percentile (Percentile mode) or
        // composite % (Percentage mode); Tables 2–3 → composite percentile.
        // Equal percentiles are tie-broken on the underlying composite, scaled
        // well below one percentile step. Keys sort ascending; na goes last.
        array<int> ord = array.new<int>()
        if nRows > 0
            if sortSel == S_NONE
                for j = 0 to nRows - 1
                    ord.push(j)
            else
                bool highFirst = sortSel == S_HIGH
                array<float> keys = array.new<float>()
                for j = 0 to nRows - 1
                    Row   r = rows.get(act.get(j))
                    float k = na
                    if view == V1
                        if colMode == C_PCTL
                            k := na(r.gAP) or na(r.gA) ? na : r.gAP + 0.0001 * clampT(r.gA)
                        else
                            k := r.gA
                    else if view == V2
                        if avgOn
                            k := na(r.aAP) or na(r.aZ) ? na : r.aAP + 0.0001 * clampT(r.aZ)
                        else
                            k := na(r.sprP(onePr)) or na(r.spr(onePr)) ? na : r.sprP(onePr) + 0.0001 * clampT(r.spr(onePr))
                    else
                        if avgOn
                            k := na(r.cvAP) or na(r.cvA) ? na : r.cvAP + 0.0001 * clampT(r.cvA)
                        else
                            k := r.cvp(onePr)
                    keys.push(na(k) ? 1e9 : highFirst ? -k : k)
                ord := keys.sort_indices(order.ascending)
 
        // Shared table texts in the selected language
        string tickHdr = T("Ticker", "الرمز", "Símbolo", "Sembol")
        string dupMark = T(" (dup.)", " (مكرر)", " (dup.)", " (tekrar)")
        string avgHdr  = T("Avg", "المتوسط", "Prom.", "Ort.")
        string sortTxt = sortSel == S_NONE ? T("input order", "ترتيب الإدخال", "orden de entrada", "giriş sırası") :
             not avgOn ? (sortSel == S_HIGH ? T("highest first", "الأعلى أولاً", "mayor primero", "en yüksek önce") :
                                              T("lowest first", "الأدنى أولاً", "menor primero", "en düşük önce")) :
             sortSel == S_HIGH ? T("highest Avg first", "الأعلى متوسطًا أولاً", "mayor Prom. primero", "en yüksek Ort. önce") :
             T("lowest Avg first", "الأدنى متوسطًا أولاً", "menor Prom. primero", "en düşük Ort. önce")
        // Capitalised: it starts the last footer line.
        string sortLbl = T("Sorted: ", "الترتيب: ", "Orden: ", "Sıralama: ")
        string modeTxt = colMode == C_PCTL ? T("percentile", "الترتيب المئوي", "percentil", "yüzdelik") :
             T("percentage", "النسبة المئوية", "porcentaje", "yüzde")
        // × window: bars since the cross < xWin, i.e. exactly the last xWin
        // bars including the latest (0 turns the mark off).
        string crossTxt = xWin == 1 ?
             T("× = crossed on the latest bar", "× = تقاطع في آخر عمود", "× = cruce en la última barra", "× = son çubukta kesişme") :
             T("× = crossed within the last " + barsTxt(xWin), "× = تقاطع خلال آخر " + barsTxt(xWin),
               "× = cruce en las últimas " + barsTxt(xWin), "× = son " + barsTxt(xWin) + "ta kesişme")
        // No × line when the mark is turned off.
        string crossLine = xWin > 0 ? "\n" + crossTxt : ""
 
        int    lastCol = 0
        string title   = ""
        string footer  = ""
 
        // ── Table 1: price vs MA ──
        if view == V1
            title := T("Price-to-MA Distance", "بُعد السعر عن المتوسط", "Distancia precio–media", "Fiyat–ortalama uzaklığı") + "\n" +
                 maType + " · " + srcName() + " · " + tfName() + " · " + lookTxt()
            put(tbl, 0, 1, tickHdr, HEAD, na, text.align_left)
            put(tbl, 1, 1, srcIn == SRC_C ? T("Price", "السعر", "Precio", "Fiyat") : srcName(), HEAD)
            if nRows > 0
                for j = 0 to nRows - 1
                    int ix = act.get(ord.get(j))
                    Row r  = rows.get(ix)
                    put(tbl, 0, j + 2, tickName(syms.get(ix)), na, na, text.align_left)
                    put(tbl, 1, j + 2, fPrice(r.price))
            int col = 2
            for m = 1 to 5
                if maOn(m)
                    // Duplicate length: column kept with a mark and dashes,
                    // no heat colour, not in Avg.
                    bool dp = isDup(m)
                    put(tbl, col, 1, maType + " " + str.tostring(lenOf(m)) + (dp ? dupMark : ""), HEAD)
                    if nRows > 0
                        for j = 0 to nRows - 1
                            if dp
                                put(tbl, col, j + 2, "–")
                            else
                                Row r = rows.get(act.get(ord.get(j)))
                                float g = logToPct(r.gap(m))
                                float q = r.gapP(m)
                                [bg, fg] = heat(colMode == C_PCTL ? dPct(q) : dVal(g))
                                put(tbl, col, j + 2, na(g) ? NA_TXT : fPct(g) + "\n" + fRank(q), bg, fg)
                    col += 1
            if avgOn
                put(tbl, col, 1, avgHdr, HEAD)
                if nRows > 0
                    for j = 0 to nRows - 1
                        Row r = rows.get(act.get(ord.get(j)))
                        float g = logToPct(r.gA)
                        float q = r.gAP
                        [bg, fg] = heat(colMode == C_PCTL ? dPct(q) : dVal(g))
                        put(tbl, col, j + 2, na(g) ? NA_TXT : fPct(g) + "\n" + fRank(q), bg, fg)
                col += 1
            lastCol := col - 1
            // Legend and sort order on separate lines, so the merged footer does
            // not widen the last column.
            footer := T("Top: distance % · Bottom: percentile · Colour by ", "أعلى الخلية: البُعد % · أسفلها: الترتيب المئوي · التلوين حسب ",
                        "Arriba: distancia % · Abajo: percentil · Color por ", "Üst: uzaklık % · Alt: yüzdelik · Renk: ") +
                      modeTxt +
                      (anyDup ? "\n" + T("(dup.) = duplicate length, not in Avg", "(مكرر) = طول مكرر، غير محسوب في المتوسط",
                                         "(dup.) = longitud repetida, fuera del Prom.", "(tekrar) = tekrarlanan uzunluk, Ort. dışında") : "") +
                      "\n" + sortLbl + sortTxt
 
        // ── Table 2: MA vs MA ──
        else if view == V2
            title := T("MA-to-MA Spread", "الفارق بين المتوسطات", "Diferencial entre medias", "Ortalamalar arası fark") + "\n" +
                 maType + " · " + srcName() + " · " + tfName() + " · " + lookTxt()
            put(tbl, 0, 1, tickHdr, HEAD, na, text.align_left)
            if nRows > 0
                for j = 0 to nRows - 1
                    int ix = act.get(ord.get(j))
                    put(tbl, 0, j + 2, tickName(syms.get(ix)), na, na, text.align_left)
            int col = 1
            for k = 1 to 4
                if prOn(k)
                    put(tbl, col, 1, pairHdr(k), HEAD)
                    if nRows > 0
                        for j = 0 to nRows - 1
                            Row r = rows.get(act.get(ord.get(j)))
                            float v = logToPct(r.spr(k))
                            float q = r.sprP(k)
                            string mark = r.sinceX(k) < xWin ? "× " : ""
                            [bg, fg] = heat(colMode == C_PCTL ? dPct(q) : dVal(v))
                            put(tbl, col, j + 2, na(v) ? NA_TXT : mark + fPct(v) + "\n" + fRank(q), bg, fg)
                    col += 1
            // Avg: alignment count on top, percentile of the RMS-scaled mean
            // spread below. Always coloured by percentile (a mean of scaled
            // spreads has no % meaning).
            if avgOn
                put(tbl, col, 1, avgHdr, HEAD)
                if nRows > 0
                    for j = 0 to nRows - 1
                        Row r = rows.get(act.get(ord.get(j)))
                        int nUp = 0
                        for k = 1 to 4
                            if prOn(k) and r.spr(k) > 0
                                nUp += 1
                        [bg, fg] = heat(dPct(r.aAP))
                        put(tbl, col, j + 2, na(r.aAP) ? NA_TXT :
                             "▲ " + str.tostring(nUp) + "/" + str.tostring(nPr) + "\n" + fRank(r.aAP), bg, fg)
                col += 1
            lastCol := col - 1
            // One idea per footer line, so the merged footer does not widen the
            // last column. The ▲ line starts with the Avg header word, so the
            // Arabic line stays right-to-left.
            footer := T("Top: spread % · Bottom: percentile · Colour by ", "أعلى الخلية: الفارق % · أسفلها: الترتيب المئوي · التلوين حسب ",
                        "Arriba: diferencial % · Abajo: percentil · Color por ", "Üst: fark % · Alt: yüzdelik · Renk: ") +
                      modeTxt + crossLine +
                 (avgOn ? "\n" +
                     T("Avg ▲ = no. of pairs with fast MA above slow MA",
                       "المتوسط ▲ = عدد الأزواج التي يعلو فيها المتوسط السريع على البطيء",
                       "Prom. ▲ = n.º de pares con la media rápida sobre la lenta",
                       "Ort. ▲ = hızlı ort. üstte olan çift sayısı") : "") +
                 "\n" + sortLbl + sortTxt
 
        // ── Table 3: convergence speed of each pair ──
        else
            title := T("Convergence Speed of Averages (Percentile)", "سرعة تقارب المتوسطات (الترتيب المئوي)",
                       "Velocidad de convergencia de medias (percentil)", "Ortalamaların yakınsama hızı (yüzdelik)") + "\n" +
                 maType + " · " + srcName() + " · " + tfName() + " · " +
                 T("change over ", "التغير خلال ", "cambio en ", "değişim: ") + barsTxt(nConv) + " · " + lookTxt()
            bool paOn = nPr > 0
            put(tbl, 0, 1, tickHdr, HEAD, na, text.align_left)
            if paOn
                put(tbl, 1, 1, T("Price action", "حركة السعر", "Acción del precio", "Fiyat hareketi"), HEAD)
            if nRows > 0
                for j = 0 to nRows - 1
                    int ix = act.get(ord.get(j))
                    put(tbl, 0, j + 2, tickName(syms.get(ix)), na, na, text.align_left)
                    // Price action: neutral background, direction in the text
                    // colour (green ▲ / red ▼, automatic for ◆), the same meaning
                    // green and red have in Tables 1–2.
                    if paOn
                        Row    r   = rows.get(ix)
                        string lbl = r.paLabel()
                        color  lfg = str.startswith(lbl, "▲") ? UPC : str.startswith(lbl, "▼") ? DNC : na
                        put(tbl, 1, j + 2, lbl, na, lfg)
            int col = paOn ? 2 : 1
            for k = 1 to 4
                if prOn(k)
                    put(tbl, col, 1, pairHdr(k), HEAD)
                    if nRows > 0
                        for j = 0 to nRows - 1
                            Row r = rows.get(act.get(ord.get(j)))
                            if na(r.spr(k)) or na(r.dz(k)) or na(r.cvp(k))
                                put(tbl, col, j + 2, NA_TXT)
                            else
                                int    s     = r.st(k)
                                string glyph = s == -1 ? G_CV + " " : s == 1 ? G_DV + " " : "= "
                                // × = crossed within the last xWin bars. The reading is still valid
                                // (after a cross the MAs really are separating), but the
                                // widening is usually the same move continuing past zero,
                                // so the pair is left out of Avg for those bars.
                                string mark  = r.sinceX(k) < xWin ? "× " : ""
                                // Glyph = direction, number = convergence-speed percentile.
                                // The raw rate (points per bar) is not shown: it is not
                                // comparable across tickers, the percentile is.
                                string txt   = mark + glyph + fRank(r.cvp(k))
                                [bg, fg] = heatN(dPct(r.cvp(k)))
                                put(tbl, col, j + 2, txt, bg, fg)
                    col += 1
            // Avg: percentile of the mean capped RMS-scaled convergence rate,
            // crossed pairs excluded.
            if avgOn
                put(tbl, col, 1, avgHdr, HEAD)
                if nRows > 0
                    for j = 0 to nRows - 1
                        Row r = rows.get(act.get(ord.get(j)))
                        [bg, fg] = heatN(dPct(r.cvAP))
                        put(tbl, col, j + 2, na(r.cvAP) ? NA_TXT : fRank(r.cvAP), bg, fg)
                col += 1
            lastCol := col - 1
            // Glyph legend, symbol first (symbol = meaning). Arabic stays
            // word-first: a line that starts with a symbol can switch to
            // left-to-right; its arrows are wrapped with ltr() to keep their order.
            string glyphLeg = lang == L_AR ?
                 "تقارب " + ltr(G_CV) + " · تباعد " + ltr(G_DV) + " · مستقر " + ltr("=") :
                 G_CV + " " + T("converging", "", "convergiendo", "yakınsıyor") + " · " +
                 G_DV + " " + T("diverging", "", "divergiendo", "ıraksıyor") + " · = " +
                 T("stable", "", "estable", "sabit")
            footer := glyphLeg + "\n" +
                 T("Number = convergence speed percentile (100 = closing fastest)",
                   "الرقم = الترتيب المئوي لسرعة التقارب (100 = الأسرع تقاربًا)",
                   "Número = percentil de velocidad de convergencia (100 = cierra más rápido)",
                   "Sayı = yakınsama hızı yüzdeliği (100 = en hızlı yakınsayan)") +
                 crossLine +
                 "\n" + sortLbl + sortTxt
 
        // Narrow tables (5 columns or fewer): one item per line in the merged
        // title and footer, split at the " · " separators and before "(", so
        // these rows do not widen the last column. Wider tables are unchanged.
        if lastCol <= 4
            title  := str.replace_all(str.replace_all(title,  " · ", "\n"), " (", "\n(")
            footer := str.replace_all(str.replace_all(footer, " · ", "\n"), " (", "\n(")
 
        // ── Title and footer rows, merged across the columns actually used ──
        // Title centered; footer starts at the reading edge of the language
        // (right for Arabic, left otherwise). The footer (legend) is drawn
        // only when "Show legend" is on.
        string footHa = lang == L_AR ? text.align_right : text.align_left
        put(tbl, 0, 0, title, HEAD, na, text.align_center)
        if showFoot
            put(tbl, 0, nRows + 2, footer, na, na, footHa)
        if lastCol > 0
            tbl.merge_cells(0, 0, lastCol, 0)
            if showFoot
                tbl.merge_cells(0, nRows + 2, lastCol, nRows + 2)
 
// Keeps the script valid as an output-producing indicator; draws nothing.
plot(na, "hidden", display = display.none)

← 返回列表