Indicator · Pine Script v6 · On the chart

Saham: Papan Instrumen

by akhmfz

A comprehensive fundamental analysis dashboard overlay tailored for the Indonesian Stock Market (IDX).

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code1,814
Settings40inputs
LicenceMIT
Last update3 months ago8 Jul 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

1,814 lines of Pine Script v6 from src/PapanInstrumen.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

PapanInstrumen.pine
// Built from modules/ — edit modules, not this file
//@version=6
// ═══════════════════════════════════════════════════════════════════
//
//   SAHAM: PAPAN INSTRUMEN BY. AKHMFZ
//   Versi 0.3.0-beta — Build 010 (Phase A+B)
//
//   CHANGELOG BUILD 006 (ringkas)
//   ✓ FITUR BARU: FAKTOR INDONESIA — dimensi ke-7 dalam skor keseluruhan.
//     Menangkap karakteristik unik IDX: Likuiditas (volume/cap), Stabilitas
//     (beta/volatility), dan Dukungan Makro (IDR/komoditas). Opt-in via
//     toggle "Aktifkan Faktor Indonesia" — default OFF untuk backward
//     compatibility. Bobot efektif 10-18% tergantung sektor.
//   ✓ Data baru: FX_IDC:USDIDR (exchange rate), ta.beta() vs IDX Composite,
//     IDX sector indices sebagai commodity proxy (fallback).
//   ✓ UI: tampilIndonesia toggle, bobotIndonesia input kustom.
//   ✓ Performance: 0 tambahan request.financial(), 1 tambahan
//     request.security("FX_IDC:USDIDR").
//
//   CHANGELOG BUILD 007 (ringkas)
//   ✓ Render rows di-hide berdasarkan weight scoring (bukan hardcode sektor)
//     — Quality: margin hanya tampil jika wGross/wOp/wNet/wEbitda/wFcfM > 0.
//     — Health: leverage/liquidity hanya tampil jika wHDe/wHCR/wHAltman > 0.
//   ✓ Interest Cover threshold: 2-20 → 5-50 (kurangi skor 100 untuk bank).
//   ✓ Dividend Yield threshold: 0-5 → 3-8 (patokan BI Rate ~6%).
//   ✓ Hapus 3 field jarang terisi IDX: Forward P/E, Buyback Yield/Ratio
//     (hemat 3 request → total ~37 calls, safety margin terpenuhi).
//   ✓ Fix multi-variable float declarations (split 7→16 baris).
//   ✓ f_scoreLowerSafe: guard untuk rasio negatif (P/E, P/B, EV/EBITDA, dll).
//   ✓ debtAssetScore threshold: 80% skala persen → 0.8 desimal.
//   ✓ n/x denominators disinkronkan dengan ukuran array sungguhan.
//   ✓ Income: f_avg5 (dengan na) → f_avg4 (4 komponen eksplisit).
//
//   CHANGELOG BUILD 001 (ringkas — detail lengkap di changelog.md)
//   ✓ Guard ekuitas negatif, hapus normalisasi magnitude, f_avg6,
//     indikator kelengkapan data, toleransi siklikal Graham, modul
//     Risiko Likuiditas & Gorengan.
//
//   TIDAK DIUBAH DARI V2 (lihat architecture.md § Batasan Diketahui)
//   ✗ Kalibrasi ambang momentum/RSI/volatilitas masih gaya pasar AS
//   ✗ Belum ada normalisasi EPS multi-tahun sungguhan (keterbatasan
//     teknis request.financial di Pine Script — lihat catatan di kode)
//   ✗ Belum ada data broker summary / kepemilikan — modul risiko di
//     bawah ini murni proxy statistik harga & volume, BUKAN
//     "bandarmology" sungguhan.
//
//   PERINGATAN
//   Indikator ini adalah alat bantu analisis, BUKAN nasihat keuangan/
//   investasi. Skor "Risiko Likuiditas & Gorengan" adalah proxy
//   statistik berbasis harga & volume historis, bukan deteksi
//   manipulasi pasar yang terverifikasi. Selalu lakukan riset mandiri.
//
// ═══════════════════════════════════════════════════════════════════

indicator(
     title             = "Saham: Papan Instrumen By. Akhmfz",
     shorttitle        = "PnInstrum",
     overlay           = true,
     calc_bars_count   = 300)

//══════════════════════════════
//
// MODUL 01
// PENGATURAN
//
//══════════════════════════════
grupUtama = "Pengaturan Utama"

simbolInput = input.symbol("", "Simbol Saham", group = grupUtama, display = display.data_window)
sym         = simbolInput == "" ? syminfo.tickerid : simbolInput

indeksAcuan   = input.symbol("IDX:COMPOSITE", "Indeks Acuan / Benchmark", group = grupUtama, display = display.data_window)
periodeLaporan = input.string("FQ", "Periode Laporan Keuangan", options = ["FQ", "FY", "TTM"], group = grupUtama, display = display.data_window)

posisiInput = input.string("Kanan Atas", "Posisi Tabel",
     options = ["Kanan Atas", "Kiri Atas", "Kanan Bawah", "Kiri Bawah"], group = grupUtama, display = display.data_window)

ukuranTeksInput = input.string("Kecil Sekali", "Ukuran Teks",
     options = ["Kecil Sekali", "Kecil", "Normal"], group = grupUtama, display = display.data_window)

warnaTema = input.string("Profesional Gelap", "Tema Warna",
     options = ["Profesional Gelap", "Profesional Terang", "Bursa Hijau", "Biru Nusantara", "Emas Premium"],
     group = grupUtama, display = display.data_window)

tampilLatarSkor    = input.bool(true, "Gunakan Latar Skor Berwarna", group = grupUtama, display = display.data_window)
tampilBarSkor      = input.bool(true, "Tampilkan Bar Skor", group = grupUtama, display = display.data_window)
barisSelangSeling  = input.bool(true, "Baris Berselang-seling Halus", group = grupUtama, display = display.data_window)
headerBerwarna     = input.bool(true, "Header Bagian Berwarna", group = grupUtama, display = display.data_window)
tampilSimbolStatus = input.bool(true, "Tampilkan Simbol ▲ ▼", group = grupUtama, display = display.data_window)
tampilKelengkapan  = input.bool(true, "Tampilkan Indikator Kelengkapan Data (n/x)", group = grupUtama, display = display.data_window)
tampilCompact = input.bool(false, "Mode Ringkas (Compact Mode)", group = grupUtama,
     tooltip = "Tampilkan hanya skor + risiko + ringkasan. Sembunyikan" +
       " detail valuasi, kualitas, growth, kesehatan, dividen, " +
       "momentum, dan Indonesia di kolom kanan. Default OFF — backward compatible.",
     display = display.data_window)

bahasa = input.string("Indonesia", "Bahasa / Language",
     options = ["Indonesia", "English"],
     group = grupUtama,
     tooltip = "Bahasa tampilan dashboard. Label teknis (ROE, P/E, P/B, dll.) " +
        "tetap dalam bahasa Inggris karena bersifat universal.",
     display = display.data_window)

tampilRingkasan    = input.bool(true, "Tampilkan Ringkasan", group = grupUtama, display = display.data_window)
tampilValuasi      = input.bool(true, "Tampilkan Valuasi", group = grupUtama, display = display.data_window)
tampilKualitas     = input.bool(true, "Tampilkan Kualitas", group = grupUtama, display = display.data_window)
tampilPertumbuhan  = input.bool(true, "Tampilkan Pertumbuhan", group = grupUtama, display = display.data_window)
tampilKesehatan    = input.bool(true, "Tampilkan Kesehatan Keuangan", group = grupUtama, display = display.data_window)
tampilDividen      = input.bool(true, "Tampilkan Dividen & Imbal Hasil", group = grupUtama, display = display.data_window)
tampilMomentum     = input.bool(true, "Tampilkan Momentum", group = grupUtama, display = display.data_window)
tampilIndonesia = input.bool(false, "Aktifkan Faktor Indonesia (7th Factor)", group = grupUtama,
     tooltip = "Menambahkan Faktor Indonesia sebagai dimensi ke-7 dalam skor " +
        "keseluruhan. Mencakup Likuiditas IDX, Stabilitas Pasar (beta/vol), " +
        "dan Dukungan Makro (IDR/komoditas). Default OFF — backward compatible.",
     display = display.data_window)

// ── Sektor & Adaptasi (BARU di V2) ──
grupSektor = "Sektor & Adaptasi"

modeSektor = input.string("Otomatis", "Deteksi Sektor",
     options = ["Otomatis",
       "Finansial (Bank/Asuransi)", "Bank", "Asuransi", "Sekuritas",
       "Konsumer (Makanan/Minuman)", "Industri (Manufaktur)", "Kesehatan (Farmasi)",
       "Batubara", "CPO & Perkebunan",
       "Siklikal (Komoditas/Energi)", "Properti", "Infrastruktur",
       "Teknologi", "Transportasi", "Non-Finansial Umum"],
     group = grupSektor,
     tooltip = "Otomatis: mendeteksi dari syminfo.sector/industry + daftar ticker. " +
       "Override manual jika auto-detect salah. Kelas BARU Build 009: Konsumer, " +
       "Industri, Kesehatan, Batubara, CPO.",
     display = display.data_window)

toleransiSiklikal = input.bool(true, "Longgarkan Graham Number untuk Sektor Siklikal", group = grupSektor,
     tooltip = "Melebarkan pita skor Graham Number untuk saham komoditas/energi yang labanya naik-turun tajam. " +
       "Ini BUKAN normalisasi EPS multi-tahun sungguhan — lihat architecture.md.",
     display = display.data_window)

// ── Bobot Skor Keseluruhan (BARU di V2) ──
grupBobot = "Bobot Skor Keseluruhan"

gunakanBobotKustom = input.bool(false, "Gunakan Bobot Kustom (default: 6 faktor sama rata)", group = grupBobot, display = display.data_window)
presetBobot = input.string("Custom", "Preset Bobot",
     options = ["Custom", "Equal Weight", "Value-biased", "Quality-biased",
       "Growth-biased", "Conservative"],
     group = grupBobot,
     tooltip = "Preset mengisi bobot otomatis. Pilih 'Custom' untuk mengatur manual.",
     display = display.data_window)

// Apply preset (overrides slider defaults)
bobotValue     = input.float(1.0, "Bobot Value", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotQuality   = input.float(1.0, "Bobot Quality", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotGrowth    = input.float(1.0, "Bobot Growth", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotHealth    = input.float(1.0, "Bobot Health", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotMomentum  = input.float(1.0, "Bobot Momentum", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotIncome    = input.float(1.0, "Bobot Income", minval = 0, step = 0.1, group = grupBobot, display = display.data_window)
bobotIndonesia = input.float(1.0, "Bobot Indonesia Factor", minval = 0, step = 0.1, group = grupBobot,
     tooltip = "Bobot untuk Faktor Indonesia (aktif hanya jika toggle ON). " +
       "Default 1.0 = ~14%. Naikkan ke 1.5 = ~20%, turunkan ke 0.7 = ~10%.",
     display = display.data_window)


// Preset bobot otomatis (override slider jika bukan Custom)
if presetBobot != "Custom"
    if presetBobot == "Equal Weight"
        bobotValue    := 1.0
        bobotQuality   := 1.0
        bobotGrowth    := 1.0
        bobotHealth    := 1.0
        bobotMomentum  := 1.0
        bobotIncome    := 1.0
    else if presetBobot == "Value-biased"
        bobotValue    := 2.0
        bobotQuality   := 1.0
        bobotGrowth    := 1.0
        bobotHealth    := 1.0
        bobotMomentum  := 0.5
        bobotIncome    := 0.5
    else if presetBobot == "Quality-biased"
        bobotValue    := 1.0
        bobotQuality   := 2.0
        bobotGrowth    := 1.0
        bobotHealth    := 1.0
        bobotMomentum  := 0.5
        bobotIncome    := 0.5
    else if presetBobot == "Growth-biased"
        bobotValue    := 1.0
        bobotQuality   := 1.0
        bobotGrowth    := 2.0
        bobotHealth    := 1.0
        bobotMomentum  := 0.5
        bobotIncome    := 0.5
    else if presetBobot == "Conservative"
        bobotValue    := 1.2
        bobotQuality   := 1.5
        bobotGrowth    := 0.8
        bobotHealth    := 1.5
        bobotMomentum  := 0.5
        bobotIncome    := 1.0
pakaiBobotTertimbang = gunakanBobotKustom or presetBobot != "Custom"
// ── Risiko Likuiditas & Gorengan (BARU di V2) ──
grupRisiko = "Risiko Likuiditas & Gorengan"

tampilRisikoGorengan = input.bool(true, "Tampilkan Modul Risiko Likuiditas", group = grupRisiko, display = display.data_window)
ambangARA        = input.float(24.0, "Ambang Deteksi ARA/ARB (%)", minval = 1, group = grupRisiko,
     tooltip = "Persentase perubahan harga harian yang dianggap 'mendekati/kena batas ARA-ARB'. " +
       "Aturan ARA/ARB IDX bertingkat menurut harga & pernah berubah — sesuaikan sendiri sesuai " +
       "aturan yang berlaku saat ini. Ini adalah proxy, bukan aturan resmi bursa.",
     display = display.data_window)
lookbackARA       = input.int(20, "Lookback Hari untuk Hitung ARA/ARB", minval = 5, maxval = 60, group = grupRisiko, display = display.data_window)
kapKecilMiliar    = input.float(1000, "Ambang Kapitalisasi 'Kecil' (Miliar Rp)", group = grupRisiko, display = display.data_window)
kapBesarMiliar    = input.float(10000, "Ambang Kapitalisasi 'Besar' (Miliar Rp)", group = grupRisiko, display = display.data_window)
likuiditasRendahJt = input.float(500, "Ambang Nilai Transaksi Harian 'Rendah' (Juta Rp, avg 20D)", group = grupRisiko, display = display.data_window)
likuiditasTinggiJt = input.float(20000, "Ambang Nilai Transaksi Harian 'Tinggi' (Juta Rp, avg 20D)", group = grupRisiko, display = display.data_window)
hargaRecehan      = input.float(50, "Ambang Harga 'Recehan' (Rp)", group = grupRisiko, display = display.data_window)

// ── Kesehatan Bank (P3-1) ──
grupBank = "Kesehatan Bank (Data Manual)"
carInput = input.float(-1.0, "CAR (%) — Rasio Kecukupan Modal", minval = -1.0, step = 0.1, group = grupBank,
     tooltip = "Capital Adequacy Ratio. Isi manual — tidak tersedia dari TV. " +
       "Data dari laporan keuangan bank. ≥ 12% = sehat. Nilai -1 = abaikan.",
     display = display.data_window)

nplInput = input.float(-1.0, "NPL Gross (%) — Non-Performing Loan", minval = -1.0, step = 0.1, group = grupBank,
     tooltip = "Non-Performing Loan ratio gross. Isi manual — tidak tersedia dari TV. " +
       "Data dari laporan keuangan bank. ≤ 3% = sehat. Nilai -1 = abaikan.",
     display = display.data_window)

ldrInput = input.float(-1.0, "LDR (%) — Loan-to-Deposit Ratio", minval = -1.0, step = 0.1, group = grupBank,
     tooltip = "Loan to Deposit Ratio. Isi manual — tidak tersedia dari TV. " +
       "Data dari laporan keuangan bank. 78-92% range ideal. Nilai -1 = abaikan.",
     display = display.data_window)

posisiTabel = switch posisiInput
    "Kiri Atas"    => position.top_left
    "Kanan Bawah"  => position.bottom_right
    "Kiri Bawah"   => position.bottom_left
    => position.top_right

ukuranTeks = switch ukuranTeksInput
    "Kecil Sekali" => size.tiny
    "Normal"       => size.normal
    => size.small

//══════════════════════════════
//
// MODUL 02
// TEMA WARNA
//
//══════════════════════════════
isLightTheme = warnaTema == "Profesional Terang"
isEmerald    = warnaTema == "Bursa Hijau"
isRoyal      = warnaTema == "Biru Nusantara"
isAmber      = warnaTema == "Emas Premium"
isDarkTheme  = not isLightTheme

tableBg = isLightTheme ? color.rgb(246, 247, 250) :
     isEmerald ? color.rgb(5, 18, 15) :
     isRoyal ? color.rgb(7, 12, 28) :
     isAmber ? color.rgb(19, 15, 9) :
     color.rgb(8, 14, 26)

altBg = isLightTheme ? color.rgb(235, 238, 243) :
     isEmerald ? color.rgb(7, 27, 22) :
     isRoyal ? color.rgb(10, 20, 45) :
     isAmber ? color.rgb(29, 23, 13) :
     color.rgb(10, 20, 36)

headerBg = isLightTheme ? color.rgb(215, 220, 228) :
     isEmerald ? color.rgb(5, 64, 49) :
     isRoyal ? color.rgb(14, 45, 105) :
     isAmber ? color.rgb(95, 58, 14) :
     color.rgb(15, 40, 78)

sectionBg = isLightTheme ? color.rgb(226, 230, 236) :
     isEmerald ? color.rgb(8, 38, 31) :
     isRoyal ? color.rgb(11, 28, 60) :
     isAmber ? color.rgb(49, 34, 14) :
     color.rgb(13, 27, 48)

gridCol = isLightTheme ? color.rgb(178, 184, 195) :
     isEmerald ? color.rgb(23, 91, 74) :
     isRoyal ? color.rgb(34, 69, 125) :
     isAmber ? color.rgb(112, 78, 32) :
     color.rgb(31, 59, 98)

mainTxt  = isLightTheme ? color.rgb(24, 27, 33) : color.rgb(215, 224, 238)
mutedTxt = isLightTheme ? color.rgb(78, 84, 96) : color.rgb(142, 158, 182)

titleTxt = isLightTheme ? color.rgb(15, 35, 60) :
     isEmerald ? color.rgb(95, 255, 197) :
     isRoyal ? color.rgb(105, 190, 255) :
     isAmber ? color.rgb(255, 197, 85) :
     color.rgb(94, 190, 255)

bullTxt    = isLightTheme ? color.rgb(24, 145, 91) : color.rgb(73, 220, 165)
bearTxt    = isLightTheme ? color.rgb(205, 52, 68) : color.rgb(255, 92, 120)
purpleTxt  = isLightTheme ? color.rgb(107, 79, 202) : color.rgb(160, 135, 255)
goldTxt    = isLightTheme ? color.rgb(168, 123, 25) : color.rgb(238, 207, 92)
cyanTxt    = isLightTheme ? color.rgb(34, 132, 156) : color.rgb(86, 204, 255)
neutralTxt = isLightTheme ? color.rgb(95, 101, 112) : color.rgb(164, 176, 195)

secValueBg     = color.rgb(16, 80, 55)
secQualityBg   = color.rgb(18, 70, 105)
secGrowthBg    = color.rgb(105, 75, 20)
secHealthBg    = color.rgb(105, 42, 50)
secMomentumBg  = color.rgb(72, 55, 125)
secIncomeBg    = color.rgb(95, 68, 18)
secSnapshotBg  = color.rgb(55, 65, 82)
secCompositeBg = color.rgb(20, 87, 95)
secRiskBg      = color.rgb(110, 30, 20)
secIndonesiaBg = color.rgb(140, 70, 20)

//══════════════════════════════
//
// MODUL 03
// UTILITAS
//
//══════════════════════════════
f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(x, hi))

f_safeDiv(float a, float b) =>
    na(a) or na(b) or b == 0 ? na : a / b

f_scoreHigher(float v, float bad, float good) =>
    na(v) ? na : f_clamp((v - bad) / (good - bad) * 100, 0, 100)

f_scoreLower(float v, float good, float bad) =>
    na(v) ? na : f_clamp((bad - v) / (bad - good) * 100, 0, 100)

// Build 007 — guard untuk rasio yang penyebutnya bisa negatif
// (P/E, P/B, PEG, EV/EBITDA dll). Jika v <= 0, return 0
// (risiko tinggi), bukan skor 100 karena rumus linear pecah.
f_scoreLowerSafe(float v, float good, float bad) =>
    na(v) ? na : v <= 0 ? 0.0 : f_scoreLower(v, good, bad)

f_scoreMid(float v, float loVal, float ideal, float hiVal) =>
    na(v) ? na : v <= ideal ? f_clamp((v - loVal) / (ideal - loVal) * 100, 0, 100) : f_clamp((hiVal - v) / (hiVal - ideal) * 100, 0, 100)

f_scorePositive(float v) =>
    na(v) ? na : v > 0 ? 100 : 0

// P3-2 — pengganti f_scorePositive untuk OCF/FCF:
// Bukan biner 0/100, graded berdasarkan rasio cash flow vs market cap
// (-2% -> 5%: dari negatif parah ke positif kuat)
f_scoreCashFlow(float cf, float mcapVal) =>
    na(cf) or na(mcapVal) or mcapVal == 0 ? na : f_scoreHigher(cf / mcapVal * 100, -2, 5)

f_avg5(float a, float b, float c, float d, float e) =>
    float sum = 0.0
    int n = 0
    if not na(a)
        sum += a
        n += 1
    if not na(b)
        sum += b
        n += 1
    if not na(c)
        sum += c
        n += 1
    if not na(d)
        sum += d
        n += 1
    if not na(e)
        sum += e
        n += 1
    n == 0 ? na : sum / n

f_avg3(float a, float b, float c) =>
    f_avg5(a, b, c, na, na)

// BARU V2 (Build 007) — rata-rata 4 komponen (Income)
f_avg4(float a, float b, float c, float d) =>
    f_avg5(a, b, c, d, na)

// BARU V2 — pengganti eksplisit untuk kasus 6-faktor yang di V1
// "ditumpangkan" ke dalam f_avg5 (lihat critique bug #4).
f_avg6(float a, float b, float c, float d, float e, float f) =>
    float sum = 0.0
    int n = 0
    if not na(a)
        sum += a
        n += 1
    if not na(b)
        sum += b
        n += 1
    if not na(c)
        sum += c
        n += 1
    if not na(d)
        sum += d
        n += 1
    if not na(e)
        sum += e
        n += 1
    if not na(f)
        sum += f
        n += 1
    n == 0 ? na : sum / n

// BARU V2 — rata-rata berbobot 6 faktor, melewati komponen na dan
// merenormalisasi bobot terhadap komponen yang tersedia saja.
f_wavg6(float a, float b, float c, float d, float e, float f,
     float wa, float wb, float wc, float wd, float we, float wf) =>
    float sum = 0.0
    float wsum = 0.0
    if not na(a) and wa > 0
        sum += a * wa
        wsum += wa
    if not na(b) and wb > 0
        sum += b * wb
        wsum += wb
    if not na(c) and wc > 0
        sum += c * wc
        wsum += wc
    if not na(d) and wd > 0
        sum += d * wd
        wsum += wd
    if not na(e) and we > 0
        sum += e * we
        wsum += we
    if not na(f) and wf > 0
        sum += f * wf
        wsum += wf
    wsum == 0 ? na : sum / wsum

// BARU V2 — indikator kelengkapan data (bug #6 di critique).
f_countValid5(float a, float b, float c, float d, float e) =>
    int n = 0
    if not na(a)
        n += 1
    if not na(b)
        n += 1
    if not na(c)
        n += 1
    if not na(d)
        n += 1
    if not na(e)
        n += 1
    n

f_countValid4(float a, float b, float c, float d) =>
    f_countValid5(a, b, c, d, na)

f_countValid6(float a, float b, float c, float d, float e, float f) =>
    f_countValid5(a, b, c, d, e) + (na(f) ? 0 : 1)

// BARU V2 (Build 006) — rata-rata 7 faktor (untuk Faktor Indonesia)
f_avg7(float a, float b, float c, float d, float e, float f, float g) =>
    float sum = 0.0
    int n = 0
    if not na(a)
        sum += a
        n += 1
    if not na(b)
        sum += b
        n += 1
    if not na(c)
        sum += c
        n += 1
    if not na(d)
        sum += d
        n += 1
    if not na(e)
        sum += e
        n += 1
    if not na(f)
        sum += f
        n += 1
    if not na(g)
        sum += g
        n += 1
    n == 0 ? na : sum / n

f_wavg7(float a, float b, float c, float d, float e, float f, float g,
     float wa, float wb, float wc, float wd, float we, float wf, float wg) =>
    float sum = 0.0
    float wsum = 0.0
    if not na(a) and wa > 0
        sum += a * wa
        wsum += wa
    if not na(b) and wb > 0
        sum += b * wb
        wsum += wb
    if not na(c) and wc > 0
        sum += c * wc
        wsum += wc
    if not na(d) and wd > 0
        sum += d * wd
        wsum += wd
    if not na(e) and we > 0
        sum += e * we
        wsum += we
    if not na(f) and wf > 0
        sum += f * wf
        wsum += wf
    if not na(g) and wg > 0
        sum += g * wg
        wsum += wg
    wsum == 0 ? na : sum / wsum

f_countValid7(float a, float b, float c, float d, float e, float f, float g) =>
    f_countValid6(a, b, c, d, e, f) + (na(g) ? 0 : 1)

// BARU V2 (Build 002) — rata-rata berbobot generik untuk array skor.
// Dipakai untuk Skor Valuasi supaya bobot tiap rasio bisa disesuaikan
// per model bisnis TANPA menduplikasi f_avgN/f_wavgN baru untuk setiap
// kombinasi sektor (prinsip "Avoid duplicated code" di system prompt
// reviewer). Komponen na atau berbobot 0 dilewati, sisanya dinormalisasi
// ulang terhadap total bobot yang valid.
f_wavgArr(array<float> vals, array<float> wts) =>
    float sum = 0.0
    float wsum = 0.0
    for i = 0 to array.size(vals) - 1
        v = array.get(vals, i)
        w = array.get(wts, i)
        if not na(v) and w > 0
            sum += v * w
            wsum += w
    wsum == 0 ? na : sum / wsum

f_countValidArr(array<float> vals) =>
    int n = 0
    for i = 0 to array.size(vals) - 1
        if not na(array.get(vals, i))
            n += 1
    n

pi_formatNumber(float v) =>
    na(v) ? "—" : str.tostring(v, "#.##")

pi_formatPercent(float v) =>
    na(v) ? "—" : str.tostring(v, "#.##") + "%"

pi_formatMoney(float v) =>
    na(v) ? "—" :
     math.abs(v) >= 1e12 ? str.tostring(v / 1e12, "#.##") + "T" :
     math.abs(v) >= 1e9 ? str.tostring(v / 1e9, "#.##") + "M" :
     math.abs(v) >= 1e6 ? str.tostring(v / 1e6, "#.##") + "Jt" :
     str.tostring(v, "#.##")

pi_grade(float s) =>
    isEN = bahasa == "English"
    na(s) ? (isEN ? "N/A" : "N/A") :
     s >= 85 ? (isEN ? "EXCELLENT" : "SANGAT BAIK") :
     s >= 70 ? (isEN ? "GOOD" : "BAIK") :
     s >= 55 ? (isEN ? "FAIR" : "CUKUP") :
     s >= 40 ? (isEN ? "WEAK" : "LEMAH") :
     (isEN ? "HIGH RISK" : "RISIKO TINGGI")

pi_overallBadge(float s) =>
    isEN = bahasa == "English"
    na(s) ? "N/A " :
     s >= 85 ? (isEN ? "EXCELLENT " : "SANGAT BAIK ") :
     s >= 70 ? (isEN ? "GOOD " : "BAIK ") :
     s >= 55 ? (isEN ? "FAIR " : "CUKUP ") :
     s >= 40 ? (isEN ? "WEAK " : "LEMAH ") :
     (isEN ? "HIGH RISK " : "RISIKO TINGGI ")

// BARU V2 — grade khusus untuk skor keamanan likuiditas (arah makna
// terbalik dari grade fundamental: skor tinggi = risiko gorengan rendah).
pi_riskGrade(float s) =>
    isEN = bahasa == "English"
    na(s) ? "N/A" :
     s >= 70 ? (isEN ? "LOW RISK" : "RISIKO RENDAH") :
     s >= 40 ? (isEN ? "MODERATE RISK" : "RISIKO SEDANG") :
     (isEN ? "HIGH RISK — CAUTION" : "RISIKO TINGGI — WASPADA")

pi_arrow(float v) =>
    not tampilSimbolStatus or na(v) ? "" : v > 0 ? "▲ " : v < 0 ? "▼ " : "■ "

pi_scoreText(float score) =>
    string result = "—"
    if not na(score)
        if tampilBarSkor
            int filled = int(math.round(f_clamp(score, 0, 100) / 100 * 6))
            string bar = ""
            for i = 0 to 5
                bar += i < filled ? "█" : "░"
            result := bar + " " + str.tostring(score, "#")
        else
            result := str.tostring(score, "#")
    result

f_rowBg(int row) =>
    barisSelangSeling and row % 2 == 0 ? altBg : tableBg

f_scoreColor(float s) =>
    na(s) ? neutralTxt :
     s >= 80 ? bullTxt :
     s >= 60 ? purpleTxt :
     s >= 40 ? goldTxt :
     bearTxt

// BARU V2 — skema warna terbalik untuk skor risiko (tinggi = aman = hijau)
f_riskColor(float s) =>
    na(s) ? neutralTxt :
     s >= 70 ? bullTxt :
     s >= 40 ? goldTxt :
     bearTxt

f_scoreBg(float s) =>
    not tampilLatarSkor ? tableBg :
     na(s) ? tableBg :
     color.new(f_scoreColor(s), isLightTheme ? 86 : 84)

f_riskBg(float s) =>
    not tampilLatarSkor ? tableBg :
     na(s) ? tableBg :
     color.new(f_riskColor(s), isLightTheme ? 86 : 84)

f_sectionBg(string title) =>
    not headerBerwarna ? sectionBg :
     str.contains(title, "SKOR KESELURUHAN") ? secCompositeBg :
     str.contains(title, "RINGKASAN") ? secSnapshotBg :
     str.contains(title, "VALUASI") ? secValueBg :
     str.contains(title, "KUALITAS") ? secQualityBg :
     str.contains(title, "PERTUMBUHAN") ? secGrowthBg :
     str.contains(title, "KESEHATAN") ? secHealthBg :
     str.contains(title, "MOMENTUM") ? secMomentumBg :
     str.contains(title, "DIVIDEN") ? secIncomeBg :
     str.contains(title, "RISIKO") ? secRiskBg :
     str.contains(title, "INDONESIA") ? secIndonesiaBg :
     sectionBg

f_categoryColor(string name, color fallback) =>
     str.contains(name, "Momentum") or str.contains(name, "RSI") or str.contains(name, "Return") or str.contains(name, "RS vs") ? purpleTxt :
      str.contains(name, "Growth") or str.contains(name, "Income") or str.contains(name, "Yield") or str.contains(name, "Payout") or str.contains(name, "Buyback") or str.contains(name, "Cash") or str.contains(name, "Health") or str.contains(name, "Debt") or str.contains(name, "Ratio") or str.contains(name, "Cover") or str.contains(name, "Altman") or str.contains(name, "OCF") or str.contains(name, "FCF") ? goldTxt :
      str.contains(name, "Quality") or str.contains(name, "ROE") or str.contains(name, "ROA") or str.contains(name, "Asset") or str.contains(name, "Piotroski") or str.contains(name, "ROIC") or str.contains(name, "Margin") or str.contains(name, "Profit") ? cyanTxt :
      str.contains(name, "Value") or str.contains(name, "P/E") or str.contains(name, "PEG") or str.contains(name, "P/S") or str.contains(name, "P/B") or str.contains(name, "EV/") or str.contains(name, "Graham") or str.contains(name, "EPS") or str.contains(name, "BVPS") or str.contains(name, "52W") ? bullTxt :
      str.contains(name, "Liquiditas") or str.contains(name, "Turnover") or str.contains(name, "Beta") or str.contains(name, "IDR") ? goldTxt :
      fallback


//══════════════════════════════
//
// MODUL 04
// MESIN PASAR (MARKET ENGINE)
//
//══════════════════════════════
type MarketData
    float dClose
    float rsi14
    float sma20
    float sma50
    float sma200
    float high52
    float low52
    float ret1m
    float ret3m
    float ret6m
    float ret12m
    float volatility
    float volAvg20
    float valTradedAvg20
    float araHits
    string sectorRaw
    string industriRaw

getMarketData() =>
    float hits = 0.0
    for i = 0 to lookbackARA - 1
        chg = f_safeDiv(close[i] - close[i + 1], close[i + 1]) * 100
        if not na(chg) and math.abs(chg) >= ambangARA
            hits += 1
    MarketData.new(
         close,
         ta.rsi(close, 14),
         ta.sma(close, 20),
         ta.sma(close, 50),
         ta.sma(close, 200),
         ta.highest(high, 252),
         ta.lowest(low, 252),
         (close / nz(close[21]) - 1) * 100,
         (close / nz(close[63]) - 1) * 100,
         (close / nz(close[126]) - 1) * 100,
         (close / nz(close[252]) - 1) * 100,
         ta.stdev(close / nz(close[1]) - 1, 63) * math.sqrt(252) * 100,
         ta.sma(volume, 20),
         ta.sma(close * volume, 20),
         hits,
         syminfo.sector,
         syminfo.industry)

dataPasar = request.security(sym, "D", getMarketData(), ignore_invalid_symbol = true)

dClose = na(dataPasar) ? na : dataPasar.dClose
rsi14  = na(dataPasar) ? na : dataPasar.rsi14
sma20  = na(dataPasar) ? na : dataPasar.sma20
sma50  = na(dataPasar) ? na : dataPasar.sma50
sma200 = na(dataPasar) ? na : dataPasar.sma200
high52 = na(dataPasar) ? na : dataPasar.high52
low52  = na(dataPasar) ? na : dataPasar.low52
ret1m  = na(dataPasar) ? na : dataPasar.ret1m
ret3m  = na(dataPasar) ? na : dataPasar.ret3m
ret6m  = na(dataPasar) ? na : dataPasar.ret6m
ret12m = na(dataPasar) ? na : dataPasar.ret12m
volatility     = na(dataPasar) ? na : dataPasar.volatility
volAvg20       = na(dataPasar) ? na : dataPasar.volAvg20
valTradedAvg20 = na(dataPasar) ? na : dataPasar.valTradedAvg20
araHits        = na(dataPasar) ? na : dataPasar.araHits
sektorRaw      = na(dataPasar) ? na : dataPasar.sectorRaw
industriRaw    = na(dataPasar) ? na : dataPasar.industriRaw

[bench6m, bench12m, benchClose] = request.security(indeksAcuan, "D",
     [(close / nz(close[126]) - 1) * 100, (close / nz(close[252]) - 1) * 100, close],
     ignore_invalid_symbol = true)

usdIdrClose = request.security("FX_IDC:USDIDR", "D", close, ignore_invalid_symbol = true)
float stockDailyRet = dClose / nz(dClose[1]) - 1
float benchDailyRet = benchClose / nz(benchClose[1]) - 1
float betaVal = ta.correlation(stockDailyRet, benchDailyRet, 252) * ta.stdev(stockDailyRet, 252) / ta.stdev(benchDailyRet, 252)

idrDailyRet = na(usdIdrClose) ? na : usdIdrClose / nz(usdIdrClose[1]) - 1
float idrStdev = ta.stdev(idrDailyRet, 63)
idrVol = na(idrDailyRet) ? na : idrStdev * math.sqrt(252) * 100

idrTrend3M = na(usdIdrClose) ? na : (usdIdrClose / nz(usdIdrClose[63]) - 1) * 100

f_watchlist(arr) =>
    array.includes(arr, syminfo.ticker)

// Daftar ticker IDX per sektor — Build 009 (15 kelas).
// Review setiap 6 bulan (IPO, merger, delisting).
// Sumber: https://www.idx.co.id/id/perusahaan-tercatat
tickerOnly = syminfo.ticker

var bankListIDX     = array.from("BBCA", "BBRI", "BBNI", "BMRI", "BBTN", "BJBR", "BJTM", "BRIS", "BTPS", "ARTO", "BBKP", "BNGA", "MEGA", "PNBN", "AGRO", "BABP", "BCIC", "BINA", "BNBA", "BSIM", "DNAR", "INPC", "MAYA", "NISP", "SDRA", "BGTG", "BEKS")
var coalListIDX     = array.from("ADRO", "PTBA", "ITMG", "BUMI", "HRUM", "INDY", "BYAN", "GEMS", "ADMR", "DOID", "GTBO", "KKGI", "MBAP", "MYOH", "SMMT", "ARTI")
var cpoListIDX      = array.from("AALI", "LSIP", "SIMP", "TBLA", "JAWA", "ANJT", "UNSP", "SSMS", "DSNG", "PALM", "GOLL", "PSGO", "MGRO", "SMAR", "SGRO")
var consumerListIDX = array.from("ICBP", "UNVR", "MYOR", "INDF", "GGRM", "HMSP", "MLBI", "ULTJ", "SKLT", "CMRY", "KEJU", "DLTA", "BUDI", "ROTI", "CLEO", "PSDN", "STTP", "AISA", "ADES", "ALTO")
var industriListIDX = array.from("ASII", "AUTO", "GJTL", "MPMX", "SMSM", "KBLM", "WTON", "SMGR", "INTP", "AMFG", "ARNA", "TOTO", "PTSN", "BRPT", "TPIA", "INKP", "SAIP", "BRNA", "AKRA", "CPIN")
var healthcareListIDX = array.from("KLBF", "SIDO", "MIKA", "HEAL", "SOHO", "RSCH", "PRDA", "DVLA", "SILO", "BMHS", "IRRA", "PEHA", "PYFA", "MERK", "TSPC")
var propertyListIDX = array.from("CTRA", "PWON", "LPKR", "SMRA", "BSDE", "PTPP", "WIKA", "ADHI", "TOTL", "BEST", "MAPI", "ASRI", "BKSL", "DILD", "LPCK", "NIRO", "GPRA", "RBMS", "RDTX", "MKPI")
var infraListIDX    = array.from("JSMR", "TLKM", "EXCL", "ISAT", "TOWR", "TBIG", "MTEL", "FREN", "CENT", "PGAS", "PNSE", "TURI", "WIFI", "IBST", "KEEN")
var techListIDX     = array.from("GOTO", "BUKA", "EMTK", "MTDL", "BLUE", "DMMX", "ASLI", "DCII", "MLPT", "MCAS", "HYGN", "KETR", "PURI", "SSTM", "KMDS", "NICE", "FORM", "MARK", "SAME", "RUNS")
var transportListIDX = array.from("ASSA", "BIRD", "SAFE", "TAXI", "GIAA", "CMPP", "BPTR", "SDMU", "TMAS", "WINS", "HITS", "BULL", "SUPR", "SMDR", "PPGL")

// FIX V2 (Build 002, revisi) — Bank/Asuransi/Sekuritas kini kelas
// eksplisit terpisah (sebelumnya ketiganya "menumpang" jadi satu
// isFinancialSector generik — benar secara hasil skor tapi tidak benar
// secara semantik/penamaan, lih. BACKLOG Build 002 sebelumnya).
//
// PENTING — batas sprint: untuk dimensi VALUASI, file1 TIDAK memberi
// bobot valuasi yang berbeda antara Bank vs Asuransi vs Sekuritas
// (ketiganya sama-sama memprioritaskan ROE/PBV/PER — perbedaan file1
// baru muncul di dimensi Financial Health, yaitu perlakuan Current
// Ratio/Quick Ratio/Cash Position, yang di luar scope sprint ini).
// Karena itu ketiga flag di bawah tetap DIGABUNG jadi isFinancialSector
// untuk keperluan bobot Valuasi (baris weighting TIDAK berubah dari
// revisi sebelumnya) — pemecahan ini murni menyiapkan detseksi yang
// benar untuk sprint Financial Health berikutnya, BUKAN mengubah skor
// Valuasi saat ini. Lihat kritik & analisis dampak di chat.
isFinancialLegacyMode = modeSektor == "Finansial (Bank/Asuransi)"

isBankSektor = modeSektor == "Bank" or
     (modeSektor == "Otomatis" and (f_watchlist(bankListIDX) or
       (not na(industriRaw) and str.contains(industriRaw, "Bank"))))

isAsuransiSektor = modeSektor == "Asuransi" or
     (modeSektor == "Otomatis" and not na(industriRaw) and str.contains(industriRaw, "Insuran"))

// CATATAN: emiten sekuritas IDX sering tidak konsisten mengisi field
// syminfo.industry (kadang "Diversified Financial Services", kadang
// kosong) — deteksi otomatis untuk kategori ini PALING LEMAH di antara
// semua kategori sektor. Override manual "Sekuritas" sangat disarankan
// dipakai langsung, jangan mengandalkan "Otomatis".
isSekuritasSektor = modeSektor == "Sekuritas" or
     (modeSektor == "Otomatis" and not na(industriRaw) and
       (str.contains(industriRaw, "Securities") or str.contains(industriRaw, "Capital Markets") or str.contains(industriRaw, "Investment Services")))

// FIX BUG (ditemukan saat review revisi ini): Build 001 punya fallback
// generik "sektorRaw contains 'Financ'" untuk menangkap emiten finansial
// yang TIDAK cocok kata kunci industri spesifik manapun (mis. holding
// company finansial, atau field industriRaw kosong tapi sektorRaw
// terisi). Saat memecah isFinancialSector jadi Bank/Asuransi/Sekuritas,
// fallback ini sempat HILANG tanpa sengaja — akibatnya emiten yang
// sebelumnya terdeteksi Finansial di Build 001 bisa jatuh ke
// "Non-Finansial Umum" di Otomatis (regresi diam-diam). Dikembalikan
// di sini sebagai kelas fallback eksplisit, BUKAN digabung lagi ke
// Bank/Asuransi/Sekuritas.
isFinancialGenericAuto = modeSektor == "Otomatis" and not isBankSektor and not isAsuransiSektor and not isSekuritasSektor and
     not na(sektorRaw) and str.contains(sektorRaw, "Financ")

isFinancialSector = isBankSektor or isAsuransiSektor or isSekuritasSektor or isFinancialLegacyMode or isFinancialGenericAuto

isSiklikalSektor = modeSektor == "Siklikal (Komoditas/Energi)" or
     (modeSektor == "Otomatis" and toleransiSiklikal and
       (f_watchlist(coalListIDX) or f_watchlist(cpoListIDX) or
        (not na(sektorRaw) and (str.contains(sektorRaw, "Energy") or str.contains(sektorRaw, "Materials"))) or
         (not na(industriRaw) and (str.contains(industriRaw, "Coal") or str.contains(industriRaw, "Mining") or str.contains(industriRaw, "Oil") or str.contains(industriRaw, "Metal") or str.contains(industriRaw, "Palm")))))

// REVISI V2 (Build 002) — 4 kategori berikut kini BISA di-override
// manual (sebelumnya hanya auto-detect di mode "Otomatis"). Tidak ada
// perubahan pada logika deteksi otomatisnya sendiri, hanya ditambah
// jalur "modeSektor == <label>" seperti kategori lain.
isPropertySektor = modeSektor == "Properti" or
     (modeSektor == "Otomatis" and
       (f_watchlist(propertyListIDX) or
        (not na(sektorRaw) and str.contains(sektorRaw, "Real Estate")) or
         (not na(industriRaw) and (str.contains(industriRaw, "Real Estate") or str.contains(industriRaw, "Property") or str.contains(industriRaw, "REIT")))))

isInfrastrukturSektor = modeSektor == "Infrastruktur" or
     (modeSektor == "Otomatis" and
       (f_watchlist(infraListIDX) or
        (not na(sektorRaw) and str.contains(sektorRaw, "Utilities")) or
         (not na(industriRaw) and (str.contains(industriRaw, "Utilit") or str.contains(industriRaw, "Infrastructure") or str.contains(industriRaw, "Toll") or str.contains(industriRaw, "Telecom")))))

isTechnologySektor = modeSektor == "Teknologi" or
     (modeSektor == "Otomatis" and
       (f_watchlist(techListIDX) or
        (not na(sektorRaw) and str.contains(sektorRaw, "Technology")) or
         (not na(industriRaw) and (str.contains(industriRaw, "Software") or str.contains(industriRaw, "Internet") or str.contains(industriRaw, "E-Commerce")))))

isTransportasiSektor = modeSektor == "Transportasi" or
     (modeSektor == "Otomatis" and
       (f_watchlist(transportListIDX) or
        (not na(sektorRaw) and str.contains(sektorRaw, "Transportation")) or
         (not na(industriRaw) and (str.contains(industriRaw, "Airlines") or str.contains(industriRaw, "Shipping") or str.contains(industriRaw, "Transport") or str.contains(industriRaw, "Logistics")))))

// BARU Build 009 — 5 kelas sektor tambahan:
// Konsumer, Industri, Kesehatan (dari Non-Finansial Umum)
// Batubara, CPO (dari Siklikal)

isKonsumerSektor = modeSektor == "Konsumer (Makanan/Minuman)" or
     (modeSektor == "Otomatis" and
       (f_watchlist(consumerListIDX) or
         (not na(industriRaw) and (str.contains(industriRaw, "Food") or str.contains(industriRaw, "Beverage") or str.contains(industriRaw, "Tobacco") or str.contains(industriRaw, "Household")))))

isIndustriSektor = modeSektor == "Industri (Manufaktur)" or
     (modeSektor == "Otomatis" and
       (f_watchlist(industriListIDX) or
         (not na(sektorRaw) and str.contains(sektorRaw, "Industrials")) or
          (not na(industriRaw) and (str.contains(industriRaw, "Automobile") or str.contains(industriRaw, "Cement") or str.contains(industriRaw, "Ceramics") or str.contains(industriRaw, "Chemical") or str.contains(industriRaw, "Tire") or str.contains(industriRaw, "Machinery")))))

isKesehatanSektor = modeSektor == "Kesehatan (Farmasi)" or
     (modeSektor == "Otomatis" and
       (f_watchlist(healthcareListIDX) or
         (not na(sektorRaw) and (str.contains(sektorRaw, "Healthcare") or str.contains(sektorRaw, "Health Care"))) or
          (not na(industriRaw) and (str.contains(industriRaw, "Pharma") or str.contains(industriRaw, "Hospital") or str.contains(industriRaw, "Medical") or str.contains(industriRaw, "Health")))))

isBatubaraSektor = modeSektor == "Batubara" or
     (modeSektor == "Otomatis" and
       (f_watchlist(coalListIDX) or
         (not na(industriRaw) and (str.contains(industriRaw, "Coal") or str.contains(industriRaw, "Mining") or str.contains(industriRaw, "Oil")))))

isCPOSektor = modeSektor == "CPO & Perkebunan" or
     (modeSektor == "Otomatis" and
       (f_watchlist(cpoListIDX) or
         (not na(industriRaw) and (str.contains(industriRaw, "Palm") or str.contains(industriRaw, "Plantation")))))

// Urutan prioritas label SENGAJA sama dengan urutan prioritas pada
// blok bobot valuasi di scoring engine (isFinancialSector dicek
// duluan, dst) — supaya label yang ditampilkan selalu konsisten
// dengan bobot yang benar-benar dipakai jika kategori tumpang tindih
// (mis. industriRaw memuat kata kunci >1 kategori sekaligus).
sektorLabel = isBankSektor ? "Finansial — Bank" :
     isAsuransiSektor ? "Finansial — Asuransi" :
     isSekuritasSektor ? "Finansial — Sekuritas" :
     isFinancialLegacyMode ? "Finansial (Bank/Asuransi)" :
     isFinancialGenericAuto ? "Finansial (Umum)" :
     isBatubaraSektor ? "Tambang — Batubara" :
     isCPOSektor ? "Perkebunan — CPO" :
     isKonsumerSektor ? "Konsumer (Makanan/Minuman)" :
     isIndustriSektor ? "Industri (Manufaktur)" :
     isKesehatanSektor ? "Kesehatan (Farmasi)" :
     isPropertySektor ? "Properti" :
     isInfrastrukturSektor ? "Infrastruktur" :
     isSiklikalSektor ? "Siklikal (Komoditas/Energi)" :
     isTechnologySektor ? "Teknologi" :
     isTransportasiSektor ? "Transportasi" :
     "Non-Finansial Umum"

//══════════════════════════════
//
// MODUL 05
// MESIN KEUANGAN (FINANCIAL ENGINE)
//
//══════════════════════════════
statPeriod = periodeLaporan == "TTM" ? "FQ" : periodeLaporan

f_fin(id) =>
    request.financial(sym, id, periodeLaporan, ignore_invalid_symbol = true)

f_stat(id) =>
    request.financial(sym, id, statPeriod, ignore_invalid_symbol = true)

f_ttm(id) =>
    request.financial(sym, id, "TTM", ignore_invalid_symbol = true)

sharesOut = f_stat("TOTAL_SHARES_OUTSTANDING")

epsTtm     = f_ttm("EARNINGS_PER_SHARE_DILUTED")
bvps       = f_stat("BOOK_VALUE_PER_SHARE")
revenueTtm = f_ttm("TOTAL_REVENUE")
evEbitda   = f_stat("ENTERPRISE_VALUE_EBITDA")
evSales    = f_stat("EV_REVENUE")

roe       = f_stat("RETURN_ON_EQUITY")
roa       = f_stat("RETURN_ON_ASSETS")
roic      = f_stat("RETURN_ON_INVESTED_CAPITAL")
grossM    = f_fin("GROSS_MARGIN")
opM       = f_fin("OPERATING_MARGIN")
netM      = f_fin("NET_MARGIN")
ebitdaM   = f_fin("EBITDA_MARGIN")
fcfMargin = f_fin("FREE_CASH_FLOW_MARGIN")
piotroski = f_stat("PIOTROSKI_F_SCORE")

revGrowth = f_fin("REVENUE_ONE_YEAR_GROWTH")
epsGrowth = f_fin("EARNINGS_PER_SHARE_DILUTED_ONE_YEAR_GROWTH")
sgr       = f_stat("SUSTAINABLE_GROWTH_RATE")

// CATATAN V2 (fix bug #2): TIDAK ADA LAGI normalisasi berbasis tebakan
// magnitude (math.abs(x) <= 5 ? x*100 : x). Field DEBT_TO_EQUITY dan
// CASH_TO_DEBT dari request.financial TradingView adalah RASIO desimal
// langsung (mis. 0.8 = 80%), bukan format campuran. Jika setelah
// compile Anda menemukan skala yang tidak masuk akal untuk emiten IDX
// tertentu, verifikasi field mentahnya dulu (jangan tebak lagi lewat
// kode) — lihat architecture.md § Batasan Diketahui.
debtEq        = f_stat("DEBT_TO_EQUITY")
debtAsset     = f_stat("DEBT_TO_ASSET")
debtEbitda    = f_stat("DEBT_TO_EBITDA")
netDebtEbitda = f_stat("NET_DEBT_TO_EBITDA")
cashDebt      = f_stat("CASH_TO_DEBT")
currRatio     = f_stat("CURRENT_RATIO")
quickRatio    = f_stat("QUICK_RATIO")
interestCover = f_stat("INTERST_COVER")
altmanZ       = f_stat("ALTMAN_Z_SCORE")
ocf           = f_fin("CASH_F_OPERATING_ACTIVITIES")
fcf           = f_fin("FREE_CASH_FLOW")

divYield     = f_stat("DIVIDENDS_YIELD")
payout       = f_fin("DIVIDEND_PAYOUT_RATIO")
dps          = f_fin("DPS_COMMON_STOCK_PRIM_ISSUE")


//══════════════════════════════
//
// MODUL 06
// MESIN ANTARMUKA (UI ENGINE)
//
//══════════════════════════════
const int ROWS = 90

var table papan = table.new(posisiTabel, 6, ROWS,
     bgcolor = tableBg, border_color = gridCol, border_width = 0,
     frame_color = gridCol, frame_width = 2)

f_cell(int col, int row, string txt, color bg, color tc) =>
    if row < ROWS
        table.cell(papan, col, row, txt, bgcolor = bg, text_color = tc, text_size = ukuranTeks)

f_boldCell(int col, int row, string txt, color bg, color tc) =>
    if row < ROWS
        table.cell(papan, col, row, txt, bgcolor = bg, text_color = tc, text_size = ukuranTeks, text_formatting = text.format_bold)

f_headerCell(int col, string txt, color bg, color tc) =>
    table.cell(papan, col, 0, txt, bgcolor = bg, text_color = tc, text_size = ukuranTeks, text_formatting = text.format_bold)

f_section(int col, int row, string title) =>
    bg = f_sectionBg(title)
    f_boldCell(col, row, title, bg, color.white)
    f_boldCell(col + 1, row, "Nilai", bg, color.white)
    f_boldCell(col + 2, row, "Skor", bg, color.white)
    row + 1

f_row(int col, int row, string name, string value, float score) =>
    bg = f_rowBg(row)
    scoreBg = tampilLatarSkor ? f_scoreBg(score) : bg
    scoreTxt = pi_scoreText(score)
    valTxtCol = na(score) ? mainTxt : isDarkTheme ? f_scoreColor(score) : f_categoryColor(name, f_scoreColor(score))
    f_cell(col, row, name, bg, mutedTxt)
    f_cell(col + 1, row, value, bg, valTxtCol)
    f_cell(col + 2, row, scoreTxt, scoreBg, valTxtCol)
    row + 1

// BARU V2 — varian f_row dengan skema warna risiko terbalik
f_riskRow(int col, int row, string name, string value, float score) =>
    bg = f_rowBg(row)
    scoreBg = tampilLatarSkor ? f_riskBg(score) : bg
    scoreTxt = pi_scoreText(score)
    valTxtCol = na(score) ? mainTxt : f_riskColor(score)
    f_cell(col, row, name, bg, mutedTxt)
    f_cell(col + 1, row, value, bg, valTxtCol)
    f_cell(col + 2, row, scoreTxt, scoreBg, valTxtCol)
    row + 1

f_scoreCard(int col, int row, string name, float score) =>
    bg = tampilLatarSkor ? f_scoreBg(score) : f_rowBg(row)
    tc = isDarkTheme ? f_scoreColor(score) : f_categoryColor(name, f_scoreColor(score))
    f_cell(col, row, name, bg, mainTxt)
    f_cell(col + 1, row, pi_scoreText(score), bg, tc)
    f_cell(col + 2, row, pi_grade(score), bg, tc)
    row + 1

// BARU V2 — kartu skor dengan indikator kelengkapan data (bug #6)
f_scoreCardN(int col, int row, string name, float score, int nValid, int nTotal) =>
    bg = tampilLatarSkor ? f_scoreBg(score) : f_rowBg(row)
    tc = isDarkTheme ? f_scoreColor(score) : f_categoryColor(name, f_scoreColor(score))
    label = tampilKelengkapan ? name + " (" + str.tostring(nValid) + "/" + str.tostring(nTotal) + ")" : name
    f_cell(col, row, label, bg, mainTxt)
    f_cell(col + 1, row, pi_scoreText(score), bg, tc)
    f_cell(col + 2, row, pi_grade(score), bg, tc)
    row + 1

f_warningCell(int col, int row, string msg) =>
    f_cell(col, row, msg, secRiskBg, color.white)
    f_cell(col + 1, row, "", tableBg, mainTxt)
    f_cell(col + 2, row, "", tableBg, mainTxt)
    row + 1

f_riskCard(int col, int row, string name, float score) =>
    bg = tampilLatarSkor ? f_riskBg(score) : f_rowBg(row)
    tc = f_riskColor(score)
    f_cell(col, row, name, bg, mainTxt)
    f_cell(col + 1, row, pi_scoreText(score), bg, tc)
    f_cell(col + 2, row, pi_riskGrade(score), bg, tc)
    row + 1


//══════════════════════════════
//
// MODUL 07 + 08
// MESIN SKOR (SCORING ENGINE) & RENDER
//
//══════════════════════════════
if barstate.islast
    // Build 009 — helper: emiten batubara/CPO diperlakukan
    // sebagai Siklikal untuk bobot scoring (siklus komoditas)
    isSiklikalLike = isSiklikalSektor or isBatubaraSektor or isCPOSektor
    relStr6m  = ret6m - bench6m
    relStr12m = ret12m - bench12m

    pos52 = na(high52) or na(low52) or high52 == low52 ? na : (dClose - low52) / (high52 - low52) * 100
    dist52High = na(high52) ? na : (dClose / high52 - 1) * 100

    maStatus = bahasa == "English" ?
         (dClose > sma20 and dClose > sma50 and dClose > sma200 ? "Bullish" :
          dClose > sma50 and dClose > sma200 ? "Strong" :
          dClose > sma200 ? "Neutral" :
          dClose > sma50 ? "Weak" :
          "Bearish") :
         (dClose > sma20 and dClose > sma50 and dClose > sma200 ? "Bullish" :
          dClose > sma50 and dClose > sma200 ? "Kuat" :
          dClose > sma200 ? "Neutral" :
          dClose > sma50 ? "Lemah" :
          "Bearish")

    maScore =
         dClose > sma20 and dClose > sma50 and dClose > sma200 ? 100 :
         dClose > sma50 and dClose > sma200 ? 80 :
         dClose > sma200 ? 60 :
         dClose > sma50 ? 45 :
         25

    // ── RASIO TURUNAN ──
    mcap = na(sharesOut) or na(dClose) ? na : sharesOut * dClose

    pe = f_safeDiv(dClose, epsTtm)
    ps = f_safeDiv(mcap, revenueTtm)
    pb = f_safeDiv(dClose, bvps)

    peg = na(pe) or na(epsGrowth) or epsGrowth <= 0 ? na : pe / epsGrowth

    earnYield = na(dClose) or na(epsTtm) or dClose == 0 ? na : epsTtm / dClose * 100
    opEarnYield = na(opM) or na(ps) or ps == 0 ? na : opM / ps
    fcfYield = na(fcf) or na(mcap) or mcap == 0 ? na : fcf / mcap * 100

    grahamPrice = na(epsTtm) or na(bvps) or epsTtm <= 0 or bvps <= 0 ? na : math.sqrt(22.5 * epsTtm * bvps)
    grahamUpside = na(grahamPrice) or na(dClose) or dClose == 0 ? na : (grahamPrice / dClose - 1) * 100

    dpsEst = na(dps) and not na(divYield) and not na(dClose) ? dClose * divYield / 100 : dps

    // ── SKOR VALUASI ──
    peScore        = f_scoreLowerSafe(pe, 8, 45)
    psScore        = f_scoreLowerSafe(ps, 1, 15)
    pbScore        = f_scoreLowerSafe(pb, 1, 12)
    pegScore       = f_scoreLowerSafe(peg, 0.5, 3.5)
    evScore        = f_scoreLowerSafe(evEbitda, 5, 30)
    evSalesScore   = f_scoreLowerSafe(evSales, 1, 15)
    earnYieldScore = f_scoreHigher(earnYield, 2, 12)
    opYieldScore   = f_scoreHigher(opEarnYield, 3, 15)
    // FIX V2 (bug #7, mitigasi): pita Graham dilebarkan untuk sektor
    // siklikal, karena EPS TTM mentah bisa berada di puncak/lembah siklus.
    grahamLow  = isSiklikalLike ? -50.0 : -30.0
    grahamHigh = isSiklikalLike ? 80.0 : 50.0
    grahamScore = f_scoreHigher(grahamUpside, grahamLow, grahamHigh)

    // ── VALUE WEIGHT TABLE (Sector-Aware) ──
    // Default (Non-Finansial): wPe=1.0 wPeg=1.0 wPs=1.0 wPb=1.0 wEv=1.0 wEvSales=3.0 wEY=1.5 wOY=1.5 wGraham=3.0
    // Bank/Asuransi/Sek:   wPb×1.5  wPe×1.3  wPeg×0.5  wGraham×0.3
    // Properti:            wPb×1.5  wPeg×0.3
    // Infrastruktur:       wPe×0.4  wEv×1.3
    // Siklikal/Batub/CPO:  wPeg×0.3 wEY×1.3   wOY×1.3
    // Teknologi:           wPe×0.3  wPb×0.3   wPeg×0.3  wGraham×0.2  wEvSales×1.5
    // Transportasi:        wPe×0.4
    // Konsumer:            wPe×1.2  wPb×1.2
    // Industri:            wPe×0.5  wEv×1.2
    // Kesehatan:           wPe×1.2  wPeg×1.3
    wPe        = 1.0
    wPeg       = 1.0
    wPs        = 1.0
    wPb        = 1.0
    wEv        = 1.0
    wEvSales   = 3.0
    wEarnYield = 1.5
    wOpYield   = 1.5
    wGraham    = 3.0

    if isFinancialSector
        wPb     *= 1.5
        wPe     *= 1.3
        wPeg    *= 0.5
        wGraham *= 0.3
    else if isPropertySektor
        wPb   *= 1.5
        wPeg  *= 0.3
    else if isInfrastrukturSektor
        wPe  *= 0.4
        wEv  *= 1.3
    else if isSiklikalLike
        wPeg       *= 0.3
        wEarnYield *= 1.3
        wOpYield   *= 1.3
    else if isTechnologySektor
        wPe      *= 0.3
        wPb      *= 0.3
        wPeg     *= 0.3
        wGraham  *= 0.2
        wEvSales *= 1.5
    else if isTransportasiSektor
        wPe  *= 0.4
    else if isKonsumerSektor
        // Konsumer: earnings stabil → P/E lebih bermakna.
        // Scale bisnis besar → P/B naik, PEG standar.
        wPe  *= 1.2
        wPb  *= 1.2
    else if isIndustriSektor
        // Industri: capital intensive seperti Property/Infra.
        // Beban depresiasi → PER kurang informatif, EV metrics naik.
        wPe *= 0.5
        wEv *= 1.2
    else if isKesehatanSektor
        // Kesehatan: laba stabil, growth premium → PEG naik.
        wPe    *= 1.2
        wPeg   *= 1.3

    valueVals = array.from(peScore, pegScore, psScore, pbScore, evScore, evSalesScore, earnYieldScore, opYieldScore, grahamScore)
    valueWts  = array.from(wPe, wPeg, wPs, wPb, wEv, wEvSales, wEarnYield, wOpYield, wGraham)

    valueScore = f_wavgArr(valueVals, valueWts)
    valueN     = (na(peScore) or wPe <= 0 ? 0 : 1) +
         (na(pegScore) or wPeg <= 0 ? 0 : 1) +
         (na(psScore) or wPs <= 0 ? 0 : 1) +
         (na(pbScore) or wPb <= 0 ? 0 : 1) +
         (na(evScore) or wEv <= 0 ? 0 : 1) +
         (na(evSalesScore) or wEvSales <= 0 ? 0 : 1) +
         (na(earnYieldScore) or wEarnYield <= 0 ? 0 : 1) +
         (na(opYieldScore) or wOpYield <= 0 ? 0 : 1) +
         (na(grahamScore) or wGraham <= 0 ? 0 : 1)

    // ── SKOR KUALITAS ──
    roeScore       = f_scoreHigher(roe, 5, 25)
    roaScore       = f_scoreHigher(roa, 2, 15)
    roicScore      = f_scoreHigher(roic, 5, 25)
    grossScore     = f_scoreHigher(grossM, 20, 60)
    opScore        = f_scoreHigher(opM, 5, 30)
    netScore       = f_scoreHigher(netM, 3, 25)
    ebitdaScore    = f_scoreHigher(ebitdaM, 8, 35)
    fcfMarginScore = f_scoreHigher(fcfMargin, 0, 20)
    piotroskiScore = na(piotroski) ? na : f_clamp(piotroski / 9 * 100, 0, 100)

    // ── QUALITY WEIGHT TABLE (Sector-Aware) ──
    // Default: wRoe=1.0 wRoa=1.0 wRoic=1.0 wGross=1.0 wOp=1.0 wNet=1.0 wEbitda=1.5 wFcfM=1.5 wPiotroski=3.0
    // Bank/Asuransi: wRoe×1.5 wRoa×1.3 wRoic×1.2 wPiot×1.2  wGross/Op/Net/Ebitda/FcfM→0 (di-skip, NIM-based)
    // Sekuritas:     wRoe×1.3 wOp×1.2 wNet×1.2 wFcfM×1.3  wGross×0.7  (commission/opex-based)
    // Properti:      wRoic×1.3  wGross×1.2  wNet×1.1
    // Infra:         wEbitda×1.5 wFcfM×1.3  wRoic×1.2  wRoe×0.7
    // Siklikal:      wEbitda×1.3 wFcfM×1.3  wPiot×1.2
    // Teknologi:     wGross×1.5 wOp×1.3  wNet×1.3
    // Transport:     wRoa×1.2    wEbitda×1.3 wFcfM×1.2
    // Konsumer:      wGross×1.3  wNet×1.3   wFcfM×1.2
    // Industri:      wEbitda×1.3 wFcfM×1.3  wRoic×1.2
    // Kesehatan:     wRoe×1.3    wNet×1.3   wRoic×1.2
    wRoe     = 1.0
    wRoa     = 1.0
    wRoic    = 1.0
    wGross   = 1.0
    wOp      = 1.0
    wNet     = 1.0
    wEbitda  = 1.5
    wFcfM    = 1.5
    wPiotroski = 3.0

    if isBankSektor or isAsuransiSektor
        // Bank/Asuransi: NIM-based → margin tradisional di-skip
        wRoe      *= 1.5
        wRoa      *= 1.3
        wRoic     *= 1.2
        wPiotroski *= 1.2
        wGross    := 0
        wOp       := 0
        wNet      := 0
        wEbitda   := 0
        wFcfM     := 0
    else if isSekuritasSektor
        // Sekuritas: commission/opex-based, bukan NIM-based.
        // Op/Net Margin relevant (brokerage efficiency).
        wRoe      *= 1.3
        wOp       *= 1.2
        wNet      *= 1.2
        wFcfM     *= 1.3
        wGross    *= 0.7
    else if isPropertySektor
        wRoic  *= 1.3
        wGross *= 1.2
        wNet   *= 1.1
    else if isInfrastrukturSektor
        wEbitda *= 1.5
        wFcfM   *= 1.3
        wRoic   *= 1.2
        wRoe    *= 0.7
    else if isSiklikalLike
        wEbitda   *= 1.3
        wFcfM     *= 1.3
        wPiotroski *= 1.2
    else if isTechnologySektor
        wGross *= 1.5
        wOp    *= 1.3
        wNet   *= 1.3
    else if isTransportasiSektor
        wRoa    *= 1.2
        wEbitda *= 1.3
        wFcfM   *= 1.2
    else if isKonsumerSektor
        // Konsumer: margin adalah indikator utama (brand power).
        // Gross/Net Margin punya nilai prediktif tinggi.
        wGross *= 1.3
        wNet   *= 1.3
        wFcfM  *= 1.2
    else if isIndustriSektor
        // Industri: capital heavy → EBITDA/FCF Margin is proxy
        // efisiensi operasional. ROIC naik untuk capital efficiency.
        wEbitda *= 1.3
        wFcfM   *= 1.3
        wRoic   *= 1.2
    else if isKesehatanSektor
        // Kesehatan: stabilitas margin tinggi. ROE + Net Margin
        // adalah indikator utama keunggulan kompetitif.
        wRoe    *= 1.3
        wNet    *= 1.3
        wRoic   *= 1.2

    qualityVals = array.from(roeScore, roaScore, roicScore, grossScore, opScore, netScore, ebitdaScore, fcfMarginScore, piotroskiScore)
    qualityWts  = array.from(wRoe, wRoa, wRoic, wGross, wOp, wNet, wEbitda, wFcfM, wPiotroski)

    qualityScore = f_wavgArr(qualityVals, qualityWts)
    qualityN     = (na(roeScore) or wRoe <= 0 ? 0 : 1) +
         (na(roaScore) or wRoa <= 0 ? 0 : 1) +
         (na(roicScore) or wRoic <= 0 ? 0 : 1) +
         (na(grossScore) or wGross <= 0 ? 0 : 1) +
         (na(opScore) or wOp <= 0 ? 0 : 1) +
         (na(netScore) or wNet <= 0 ? 0 : 1) +
         (na(ebitdaScore) or wEbitda <= 0 ? 0 : 1) +
         (na(fcfMarginScore) or wFcfM <= 0 ? 0 : 1) +
         (na(piotroskiScore) or wPiotroski <= 0 ? 0 : 1)

    // ── GROWTH WEIGHT TABLE (Sector-Aware) ──
    // Default: wGRev=1.0 wGEps=1.0 wGSgr=1.0
    // Finansial:  wGRev×0.7  wGEps×1.0  wGSgr×1.7
    // Properti:   wGRev×1.3  wGEps×0.3  wGSgr×0.7
    // Infra:      wGRev×1.1  wGEps×0.7  wGSgr×1.1
    // Siklikal:   wGRev×1.3  wGEps×0.2  wGSgr×0.3
    // Teknologi:  wGRev×1.7  wGEps×0.5  wGSgr×0 (di-skip)
    // Transport:  wGRev×1.2  wGEps×0.8  wGSgr×0.8
    // Konsumer:   wGEps×1.3
    // Industri:   wGRev×1.2
    // Kesehatan:  wGEps×1.3
    revScore = f_scoreHigher(revGrowth, 0, 25)
    epsScore = f_scoreHigher(epsGrowth, 0, 30)
    sgrScore = f_scoreHigher(sgr, 0, 20)

    // Bobot dasar (1:1:1 = f_avg3 utk Non-Finansial Umum)
    wGRev = 1.0
    wGEps = 1.0
    wGSgr = 1.0

    if isFinancialSector
        wGRev *= 0.7
        wGEps *= 1.0
        wGSgr *= 1.7
    else if isPropertySektor
        wGRev *= 1.3
        wGEps *= 0.3
        wGSgr *= 0.7
    else if isInfrastrukturSektor
        wGRev *= 1.1
        wGEps *= 0.7
        wGSgr *= 1.1
    else if isSiklikalLike
        wGRev *= 1.3
        wGEps *= 0.2
        wGSgr *= 0.3
    else if isTechnologySektor
        wGRev *= 1.7
        wGEps *= 0.5
        wGSgr := 0
    else if isTransportasiSektor
        wGRev *= 1.2
        wGEps *= 0.8
        wGSgr *= 0.8
    else if isKonsumerSektor
        // Konsumer: EPS Growth prioritas (volume×harga yang bisa
        // dinaikkan secara konsisten lebih meaningful).
        wGEps *= 1.3
    else if isIndustriSektor
        // Industri: Rev Growth dari kontrak/order book.
        wGRev *= 1.2
    else if isKesehatanSektor
        // Kesehatan: EPS Growth is lead metric (margin scalable).
        wGEps *= 1.3

    growthVals = array.from(revScore, epsScore, sgrScore)
    growthWts  = array.from(wGRev, wGEps, wGSgr)

    growthBaseScore = f_wavgArr(growthVals, growthWts)

    // Layer 2: Multi-Factor Growth Quality Modifier
    // Terinspirasi oleh konsep Piotroski F-Score (point 4: OCF > NI)
    // dan AQR Quality Factor — diimplementasikan sebagai heuristik
    // sendiri, bukan replikasi rumus aslinya.
    //
    // Faktor 1 — Rev-EPS Spread (progresif, max -40%):
    // Spread negatif = margin compression. Semakin parah, semakin besar
    // pengurangan. Progressif (bukan linier) biar tidak terlalu drastis
    // untuk spread kecil.
    growthSpread = na(revGrowth) or revGrowth == 0 ? na : f_safeDiv(epsGrowth - revGrowth, math.abs(revGrowth)) * 100
    spreadModifier = na(growthSpread) ? (revGrowth == 0 and epsGrowth < 0 ? 0.9 : 1.0) :
         growthSpread >= 0 ? 1.0 :
         math.max(0.6, 1.0 + growthSpread / 100 * 0.6)
    // multiplier 0.6 bikin -50% spread → modifier 0.7 (bukan 0.5),
    // -100% spread → modifier 0.6 (max).

    // Faktor 2 — Earnings Quality (Piotroski F-Score point 4 proxy):
    // OCF positif = laba berbasis kas. OCF negatif = risiko akrual.
    // Note: ini hanya cek tanda OCF (bukan full OCF > Net Income check
    // seperti Piotroski asli — keterbatasan data Pine Script).
    earningsQuality = na(ocf) ? 1.0 : ocf > 0 ? 1.0 : 0.9

    growthModifier = spreadModifier * earningsQuality

    growthScore = na(growthBaseScore) ? na : growthBaseScore * growthModifier
    growthN = (na(revScore) or wGRev <= 0 ? 0 : 1) +
         (na(epsScore) or wGEps <= 0 ? 0 : 1) +
         (na(sgrScore) or wGSgr <= 0 ? 0 : 1)

    // ── HEALTH WEIGHT TABLE (Sector-Aware, plus threshold overrides) ──
    // Default: wHDe=1.0 wHDa=1.0 wHDeB=1.0 wHNetD=1.0 wHCash=1.0 wHIC=1.0 wHCR=1.5 wHQR=1.5 wHAltman=3.0 wHOCF=1.5 wHFCF=1.5
    // Bank:      all leverage→0  wHIC:=1.5  wHOCF:=1.5  wHFCF:=1.5
    // Asuransi:  all leverage→0  wHIC:=1.0  wHOCF:=1.5  wHFCF:=1.5
    // Sekuritas: wHDe:=0.7 wHDa:=0.7 wHDeB→0 wHNetD→0 wHCash:=1.3 wHIC:=1.0 wHCR:=0.7 wHQR:=0.7 wHAltman→0 wHOCF:=1.5 wHFCF:=1.5
    //            debtEqB:=5.0 debtEbitdaB:=8.0 currL:=0.5 currI:=1.5 currH:=4.0 intBad:=2.0 intGood:=15.0
    // Infra:     wHDeB×1.3 wHOCF×1.3 wHIC×0.7  debtEqB:=5.0 debtEbitdaB:=8.0 currL:=0.5 currI:=1.5 currH:=3.0 intBad:=1.5 intGood:=10.0
    // Properti:  wHDeB×1.2 wHNetD×1.2 wHCR×0.5 wHQR×0.5 wHOCF×1.3 wHFCF×1.3
    //            debtEqB:=4.0 debtEbitdaB:=8.0 currL:=0.5 currI:=1.5 currH:=3.0 intBad:=2.0 intGood:=10.0
    // Teknologi: wHDe×0.3 wHDa×0.3 wHDeB×0.3 wHNetD×0.3 wHCash×1.5 wHCR×1.3 wHFCF×1.3
    //            debtEqB:=2.0 debtEbitdaB:=4.0 currL:=1.0 currI:=2.5 currH:=6.0 intBad:=5.0 intGood:=25.0
    // Siklikal:  wHIC×1.3  intBad:=3.0 intGood:=20.0
    // Konsumer:  wHCash×1.2
    // Industri:  wHOCF×1.3  debtEqB:=4.0 intBad:=2.0 intGood:=15.0
    // Kesehatan: wHCR×1.2  wHCash×1.2
    float debtEqG = 0.0
    float debtEqB = 2.5
    float debtEbitdaG = 0.0
    float debtEbitdaB = 6.0
    float netDebtEbitdaG = 0.0
    float netDebtEbitdaB = 5.0
    float currL = 0.5
    float currI = 2.0
    float currH = 5.0
    float quickL = 0.3
    float quickI = 1.5
    float quickH = 4.0
    float intBad = 5.0
    float intGood = 50.0
    float altmanBad = 1.1
    float altmanGood = 2.6

    wHDe = 1.0
    wHDa = 1.0
    wHDeB = 1.0
    wHNetD = 1.0
    wHCash = 1.0
    wHIC = 1.0
    wHCR = 1.5
    wHQR = 1.5
    wHAltman = 3.0
    wHOCF = 1.5
    wHFCF = 1.5

    if isBankSektor
        wHDe := 0
        wHDa := 0
        wHDeB := 0
        wHNetD := 0
        wHCash := 0
        wHIC := 1.5
        wHCR := 0
        wHQR := 0
        wHAltman := 0
        wHOCF := 1.5
        wHFCF := 1.5
    else if isAsuransiSektor
        wHDe := 0
        wHDa := 0
        wHDeB := 0
        wHNetD := 0
        wHCash := 0
        wHIC := 1.0
        wHCR := 0
        wHQR := 0
        wHAltman := 0
        wHOCF := 1.5
        wHFCF := 1.5
    else if isSekuritasSektor
        wHDe := 0.7
        wHDa := 0.7
        wHDeB := 0
        wHNetD := 0
        wHCash := 1.3
        wHIC := 1.0
        wHCR := 0.7
        wHQR := 0.7
        wHAltman := 0
        wHOCF := 1.5
        wHFCF := 1.5
        debtEqB := 5.0
        debtEbitdaB := 8.0
        currL := 0.5
        currI := 1.5
        currH := 4.0
        intBad := 2.0
        intGood := 15.0
    else if isInfrastrukturSektor
        wHDeB *= 1.3
        wHOCF *= 1.3
        wHIC *= 0.7
        debtEqB := 5.0
        debtEbitdaB := 8.0
        currL := 0.5
        currI := 1.5
        currH := 3.0
        intBad := 1.5
        intGood := 10.0
    else if isPropertySektor
        wHDeB *= 1.2
        wHNetD *= 1.2
        wHCR *= 0.5
        wHQR *= 0.5
        wHOCF *= 1.3
        wHFCF *= 1.3
        debtEqB := 4.0
        debtEbitdaB := 8.0
        currL := 0.5
        currI := 1.5
        currH := 3.0
        intBad := 2.0
        intGood := 10.0
    else if isTechnologySektor
        wHDe *= 0.3
        wHDa *= 0.3
        wHDeB *= 0.3
        wHNetD *= 0.3
        wHCash *= 1.5
        wHCR *= 1.3
        wHFCF *= 1.3
        debtEqB := 2.0
        debtEbitdaB := 4.0
        currL := 1.0
        currI := 2.5
        currH := 6.0
        intBad := 5.0
        intGood := 25.0
    else if isSiklikalLike
        wHIC *= 1.3
        intBad := 3.0
        intGood := 20.0
    else if isKonsumerSektor
        wHCash *= 1.2
    else if isIndustriSektor
        wHOCF *= 1.3
        debtEqB := 4.0
        intBad := 2.0
        intGood := 15.0
    else if isKesehatanSektor
        wHCR *= 1.2
        wHCash *= 1.2

    // Guard ekuitas negatif: beri skor 0 langsung
    debtEqScore = na(debtEq) ? na :
         debtEq < 0 ? 0.0 : f_scoreLower(debtEq, debtEqG, debtEqB)
    debtAssetScore     = f_scoreLowerSafe(debtAsset, 0, 0.8)
    debtEbitdaScore    = f_scoreLowerSafe(debtEbitda, debtEbitdaG, debtEbitdaB)
    netDebtEbitdaScore = f_scoreLowerSafe(netDebtEbitda, netDebtEbitdaG, netDebtEbitdaB)
    cashDebtScore      = f_scoreHigher(cashDebt, 0, 1.5)
    currScore          = f_scoreMid(currRatio, currL, currI, currH)
    quickScore         = f_scoreMid(quickRatio, quickL, quickI, quickH)
    interestScore      = f_scoreHigher(interestCover, intBad, intGood)
    altmanScore        = f_scoreHigher(altmanZ, altmanBad, altmanGood)
    ocfScore           = f_scoreCashFlow(ocf, mcap)
    fcfScore           = f_scoreCashFlow(fcf, mcap)

    // P3-1: Bank-specific CAR/NPL/LDR (manual inputs — data tidak tersedia di TV)
    carScore  = carInput >= 0 ? f_scoreHigher(carInput, 8, 15) : na
    nplScore  = nplInput >= 0 ? f_scoreLower(nplInput, 1, 8) : na
    ldrScore  = ldrInput >= 0 ? f_scoreMid(ldrInput, 60, 85, 110) : na

    healthVals = array.from(debtEqScore, debtAssetScore, debtEbitdaScore,
         netDebtEbitdaScore, cashDebtScore, interestScore,
         currScore, quickScore, altmanScore, ocfScore, fcfScore)
    healthWts  = array.from(wHDe, wHDa, wHDeB, wHNetD, wHCash, wHIC,
         wHCR, wHQR, wHAltman, wHOCF, wHFCF)

    // P3-1: bank health score with CAR/NPL/LDR (if manual inputs provided)
    if isBankSektor and (carInput >= 0 or nplInput >= 0 or ldrInput >= 0)
        healthVals := array.from(debtEqScore, debtAssetScore, debtEbitdaScore,
             netDebtEbitdaScore, cashDebtScore, interestScore,
             currScore, quickScore, altmanScore, ocfScore, fcfScore,
             carScore, nplScore, ldrScore)
        healthWts  := array.from(wHDe, wHDa, wHDeB, wHNetD, wHCash, wHIC,
             wHCR, wHQR, wHAltman, wHOCF, wHFCF,
             2.0, 2.0, 1.5)

    healthScore = f_wavgArr(healthVals, healthWts)
    healthN = (na(debtEqScore) or wHDe <= 0 ? 0 : 1) +
         (na(debtAssetScore) or wHDa <= 0 ? 0 : 1) +
         (na(debtEbitdaScore) or wHDeB <= 0 ? 0 : 1) +
         (na(netDebtEbitdaScore) or wHNetD <= 0 ? 0 : 1) +
         (na(cashDebtScore) or wHCash <= 0 ? 0 : 1) +
         (na(interestScore) or wHIC <= 0 ? 0 : 1) +
         (na(currScore) or wHCR <= 0 ? 0 : 1) +
         (na(quickScore) or wHQR <= 0 ? 0 : 1) +
         (na(altmanScore) or wHAltman <= 0 ? 0 : 1) +
         (na(ocfScore) or wHOCF <= 0 ? 0 : 1) +
         (na(fcfScore) or wHFCF <= 0 ? 0 : 1)

    // ── SKOR DIVIDEN / INCOME ──
    yieldScore        = f_scoreHigher(divYield, 3, 8)
    payoutScore       = f_scoreMid(payout, 0, 40, 100)
    fcfYieldScore     = f_scoreHigher(fcfYield, 0, 8)
    dpsScore          = f_scorePositive(dpsEst)

    incomeScore = f_avg4(yieldScore, payoutScore, fcfYieldScore, dpsScore)

    incomeN = f_countValid4(yieldScore, payoutScore, fcfYieldScore, dpsScore)

    // ── SKOR MOMENTUM ──
    rsiScore  = f_scoreMid(rsi14, 30, 60, 85)
    posScore  = f_scoreHigher(pos52, 20, 90)
    rs6Score  = f_scoreHigher(relStr6m, -20, 25)
    rs12Score = f_scoreHigher(relStr12m, -25, 35)
    volScore  = f_scoreLower(volatility, 10, 80)

    momentumScore = f_avg5(
         rsiScore,
         posScore,
         rs6Score,
         rs12Score,
         f_avg3(maScore, volScore, na))
    momentumN = f_countValid5(rsiScore, posScore, rs6Score, rs12Score, f_avg3(maScore, volScore, na))

    // ── FAKTOR INDONESIA (BARU Build 006) ──
    // Dimensi ke-7: Likuiditas IDX + Stabilitas Pasar + Dukungan Makro.
    // Aktif via toggle tampilIndonesia (default OFF). Bobot sector-aware.
    // 3 komponen, rata-rata via f_avg3.
    // Hitung ulang var likuiditas lokal (sebelum risk module mendefinisikan)
    indoMcapMiliar  = na(mcap) ? na : mcap / 1e9
    indoValTradedJt = na(valTradedAvg20) ? na : valTradedAvg20 / 1e6
    indoTurnoverPct = na(volAvg20) or na(sharesOut) or sharesOut == 0 ? na : volAvg20 / sharesOut * 100
    indoLiqScore = f_avg5(
         f_scoreHigher(indoValTradedJt, likuiditasRendahJt, likuiditasTinggiJt),
         f_scoreHigher(indoTurnoverPct, 0.05, 1.0),
         f_scoreHigher(indoMcapMiliar, kapKecilMiliar, kapBesarMiliar),
         na, na)
    // Stabilitas: beta moderat (U-shaped), RS positif, vol moderat
    indoBetaScore = f_avg3(
         f_scoreMid(betaVal, 0.2, 0.9, 2.5),
         na(relStr6m) or na(relStr12m) ? na : f_scoreHigher((relStr6m + relStr12m) / 2, -15, 20),
         f_scoreMid(volatility, 15, 40, 100))
    // Makro: IDR stability + sector-specific commodity proxy
    indoIdrScore = f_scoreLower(idrVol, 5, 20)
    indoIdrTrend = na(idrTrend3M) ? na :
         isSiklikalLike ? f_scoreHigher(idrTrend3M, -5, 15) :  // eksportir: IDR lemah = bullish
         f_scoreLower(idrTrend3M, -5, 5)                          // lain: IDR menguat = skor tinggi (f_scoreLower, good=-5)
    indoMacroScore = f_avg3(indoIdrScore, indoIdrTrend, na)
    // Bobot sector-aware untuk Faktor Indonesia
    wIndonesia = 1.0
    if isSiklikalLike
        wIndonesia := 1.3
    else if isTechnologySektor
        wIndonesia := 1.2
    else if isBankSektor or isAsuransiSektor or isSekuritasSektor or isInfrastrukturSektor
        wIndonesia := 0.8
    indonesiaScore = f_avg3(indoLiqScore, indoBetaScore, indoMacroScore)
    indonesiaN = (na(indoLiqScore) ? 0 : 1) + (na(indoBetaScore) ? 0 : 1) + (na(indoMacroScore) ? 0 : 1)
    effectiveBobotIndonesia = bobotIndonesia * wIndonesia

    // ── SKOR KESELURUHAN ──
    // FIX V2 (bug #4): f_avg6 eksplisit, 6 faktor benar-benar setara.
    // ENHANCE V2 (Build 006): jika tampilIndonesia ON, gunakan f_avg7
    // dengan Faktor Indonesia sebagai dimensi ke-7 (bobot ~14-18%).
    // Default OFF untuk backward compatibility.
    overallScore = tampilIndonesia ?
         (pakaiBobotTertimbang ?
              f_wavg7(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore, indonesiaScore,
                   bobotValue, bobotQuality, bobotGrowth, bobotHealth, bobotMomentum, bobotIncome, effectiveBobotIndonesia) :
              f_avg7(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore, indonesiaScore)) :
         (pakaiBobotTertimbang ?
              f_wavg6(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore,
                   bobotValue, bobotQuality, bobotGrowth, bobotHealth, bobotMomentum, bobotIncome) :
              f_avg6(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore))
    overallN = tampilIndonesia ?
         f_countValid7(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore, indonesiaScore) :
         f_countValid6(valueScore, qualityScore, growthScore, healthScore, momentumScore, incomeScore)

    // ── RISIKO LIKUIDITAS & GORENGAN (BARU V2) ──
    // Skor terpisah, TIDAK dicampur ke overallScore. Semakin TINGGI
    // skor ini, semakin AMAN (risiko gorengan rendah) — kebalikan dari
    // skema skor fundamental di atas. Ini proxy statistik harga/volume,
    // bukan deteksi manipulasi terverifikasi.
    mcapMiliar = na(mcap) ? na : mcap / 1e9
    valTradedJt = na(valTradedAvg20) ? na : valTradedAvg20 / 1e6
    turnoverPct = na(volAvg20) or na(sharesOut) or sharesOut == 0 ? na : volAvg20 / sharesOut * 100

    mcapScore     = f_scoreHigher(mcapMiliar, kapKecilMiliar, kapBesarMiliar)
    liqScore      = f_scoreHigher(valTradedJt, likuiditasRendahJt, likuiditasTinggiJt)
    volRiskScore  = f_scoreLower(volatility, 30, 120)
    araRiskScore  = f_scoreLower(araHits, 0, lookbackARA * 0.4)
    priceTierScore = f_scoreHigher(dClose, hargaRecehan * 0.5, hargaRecehan * 5)

    riskSafetyScore = f_avg5(mcapScore, liqScore, volRiskScore, araRiskScore, priceTierScore)

    // ── RENDER KE TABEL ──
    table.clear(papan, 0, 0, 5, ROWS - 1)

    overallTxt = pi_overallBadge(overallScore) + pi_formatNumber(overallScore) +
         (tampilKelengkapan ? " (" + str.tostring(overallN) + (tampilIndonesia ? "/7)" : "/6)") : "")

    f_headerCell(0, bahasa == "English" ? "INSTRUMENT PANEL" : "PAPAN INSTRUMEN", headerBg, titleTxt)
    f_headerCell(1, sym, headerBg, titleTxt)
    f_headerCell(2, periodeLaporan, headerBg, titleTxt)
    f_headerCell(3, "Sektor: " + sektorLabel, headerBg, titleTxt)
    f_headerCell(4, indeksAcuan, headerBg, titleTxt)
    f_headerCell(5, overallTxt, headerBg, f_scoreColor(overallScore))

    noData = na(epsTtm) and na(bvps) and na(roe) and na(debtEq) and na(divYield)
    isEN = bahasa == "English"

    int l = 1
    int r = 1

    // ── LEFT COLUMN ──
    if noData
        l := f_warningCell(0, l, isEN ? "NO DATA" : "DATA TIDAK TERSEDIA")
        l := f_warningCell(0, l, isEN ? "This issuer has no fundamental" : "Emiten ini belum memiliki data")
        l := f_warningCell(0, l, isEN ? "data on TradingView." : "fundamental di TradingView.")
        l := f_warningCell(0, l, isEN ? "Try Daily timeframe or switch" : "Coba timeframe Daily atau ganti")
        l := f_warningCell(0, l, isEN ? "to another symbol." : "simbol lain.")

    if not noData
        l := f_section(0, l, isEN ? "OVERALL SCORE" : "SKOR KESELURUHAN")
        l := f_scoreCardN(0, l, "Quality", qualityScore, qualityN, 9)
        l := f_scoreCardN(0, l, "Value", valueScore, valueN, 9)
        l := f_scoreCardN(0, l, "Growth", growthScore, growthN, 3)
        l := f_scoreCardN(0, l, "Health", healthScore, healthN, 11)
        l := f_scoreCardN(0, l, "Income", incomeScore, incomeN, 4)
        l := f_scoreCardN(0, l, "Momentum", momentumScore, momentumN, 5)
        if tampilIndonesia
            l := f_scoreCardN(0, l, "Indonesia", indonesiaScore, indonesiaN, 3)

    if tampilRisikoGorengan
        l := f_section(0, l, isEN ? "LIQUIDITY RISK" : "RISIKO LIKUIDITAS")
        l := f_riskCard(0, l, isEN ? "Liquidity Safety" : "Keamanan Likuiditas", riskSafetyScore)

    if tampilRingkasan
        l := f_section(0, l, isEN ? "SUMMARY" : "RINGKASAN")
        l := f_row(0, l, "Price", pi_formatNumber(dClose), na)
        l := f_row(0, l, "Market Cap", pi_formatMoney(mcap), na)
        l := f_row(0, l, "52W Position", pi_arrow(pos52 - 50) + pi_formatPercent(pos52), posScore)
        l := f_row(0, l, "Dist. From 52W High", pi_arrow(dist52High) + pi_formatPercent(dist52High), posScore)

    if tampilValuasi and not tampilCompact
        l := f_section(0, l, isEN ? "VALUATION" : "VALUASI")
        l := f_row(0, l, "P/E TTM", pi_formatNumber(pe), peScore)
        if not na(peg)
            l := f_row(0, l, "PEG Ratio", pi_formatNumber(peg), pegScore)
        l := f_row(0, l, "P/S TTM", pi_formatNumber(ps), psScore)
        l := f_row(0, l, "P/B", pi_formatNumber(pb), pbScore)
        if not na(evEbitda)
            l := f_row(0, l, "EV/EBITDA", pi_formatNumber(evEbitda), evScore)
        l := f_row(0, l, "EV/Sales", pi_formatNumber(evSales), evSalesScore)
        l := f_row(0, l, "Earnings Yield", pi_formatPercent(earnYield), earnYieldScore)
        l := f_row(0, l, "Operating Earn. Yield", pi_formatPercent(opEarnYield), opYieldScore)
        l := f_row(0, l, "Graham Price", pi_formatNumber(grahamPrice), grahamScore)
        l := f_row(0, l, "Graham No. Upside", pi_arrow(grahamUpside) + pi_formatPercent(grahamUpside), grahamScore)
        l := f_row(0, l, "EPS TTM", pi_formatNumber(epsTtm), na)
        l := f_row(0, l, "BVPS", pi_formatNumber(bvps), pbScore)

    if tampilDividen and not tampilCompact
        l := f_section(0, l, isEN ? "DIVIDEND & YIELD" : "DIVIDEN & IMBAL HASIL")
        l := f_row(0, l, "Dividend Yield", pi_formatPercent(divYield), yieldScore)
        l := f_row(0, l, "Payout Ratio", pi_formatPercent(payout), payoutScore)
        l := f_row(0, l, "FCF Yield", pi_formatPercent(fcfYield), fcfYieldScore)
        l := f_row(0, l, "DPS", pi_formatNumber(dpsEst), dpsScore)

    // ── RIGHT COLUMN ──
    if noData
        r := f_warningCell(3, r, isEN ? "NO DATA" : "DATA TIDAK TERSEDIA")
        r := f_warningCell(3, r, isEN ? "This issuer has no fundamental" : "Emiten ini belum memiliki data")
        r := f_warningCell(3, r, isEN ? "data on TradingView." : "fundamental di TradingView.")
        r := f_warningCell(3, r, isEN ? "Try Daily timeframe or switch" : "Coba timeframe Daily atau ganti")
        r := f_warningCell(3, r, isEN ? "to another symbol." : "simbol lain.")

    if not noData and tampilKualitas and not tampilCompact
        r := f_section(3, r, isEN ? "QUALITY" : "KUALITAS")
        if isBankSektor or isAsuransiSektor or isSekuritasSektor
            r := f_row(3, r, "(Sektor Finansial: margin", "non-bank di-skip)", na)
        r := f_row(3, r, "ROE", pi_formatPercent(roe), roeScore)
        r := f_row(3, r, "Asset Return / ROA", pi_formatPercent(roa), roaScore)
        r := f_row(3, r, "ROIC", pi_formatPercent(roic), roicScore)
        r := f_row(3, r, "Piotroski F-Score", pi_formatNumber(piotroski), piotroskiScore)
        if wGross > 0
            r := f_row(3, r, "Gross Margin", pi_formatPercent(grossM), grossScore)
        if wOp > 0
            r := f_row(3, r, "Operating Margin", pi_formatPercent(opM), opScore)
        if wNet > 0
            r := f_row(3, r, "Net Margin", pi_formatPercent(netM), netScore)
        if wEbitda > 0
            r := f_row(3, r, "EBITDA Margin", pi_formatPercent(ebitdaM), ebitdaScore)
        if wFcfM > 0
            r := f_row(3, r, "FCF Margin", pi_formatPercent(fcfMargin), fcfMarginScore)

    if not noData and tampilPertumbuhan and not tampilCompact
        r := f_section(3, r, isEN ? "GROWTH" : "PERTUMBUHAN")
        r := f_row(3, r, "Revenue Growth", pi_arrow(revGrowth) + pi_formatPercent(revGrowth), revScore)
        r := f_row(3, r, "EPS Growth", pi_arrow(epsGrowth) + pi_formatPercent(epsGrowth), epsScore)
        r := f_row(3, r, "Sustainable Growth", pi_arrow(sgr) + pi_formatPercent(sgr), sgrScore)

    if not noData and tampilIndonesia and not tampilCompact
        r := f_section(3, r, isEN ? "INDONESIA FACTOR" : "FAKTOR INDONESIA")
        r := f_row(3, r, "Liquiditas", pi_formatMoney(valTradedAvg20), indoLiqScore)
        r := f_row(3, r, "Turnover Harian", pi_formatPercent(turnoverPct), na)
        r := f_row(3, r, "Beta vs IDX", pi_formatNumber(betaVal), indoBetaScore)
        r := f_row(3, r, "IDR Volatility", pi_formatPercent(idrVol), indoIdrScore)
        r := f_row(3, r, "IDR 3M Trend", pi_arrow(idrTrend3M) + pi_formatPercent(idrTrend3M), indoIdrTrend)

    if not noData and tampilKesehatan and not tampilCompact
        r := f_section(3, r, isEN ? "FINANCIAL HEALTH" : "KESEHATAN KEUANGAN")
        if isBankSektor or isAsuransiSektor or isSekuritasSektor
            r := f_row(3, r, "(Sektor Finansial: rasio", "terbatas — lihat skor)", na)
        if isBankSektor and carInput >= 0
            r := f_row(3, r, "CAR (manual input)", pi_formatPercent(carInput), carScore)
        if isBankSektor and nplInput >= 0
            r := f_row(3, r, "NPL Gross (manual)", pi_formatPercent(nplInput), nplScore)
        if isBankSektor and ldrInput >= 0
            r := f_row(3, r, "LDR (manual input)", pi_formatPercent(ldrInput), ldrScore)
        if wHDe > 0
            r := f_row(3, r, "Debt / Equity", pi_formatNumber(debtEq), debtEqScore)
        if wHDa > 0
            r := f_row(3, r, "Debt / Assets", pi_formatNumber(debtAsset), debtAssetScore)
        if wHDeB > 0
            r := f_row(3, r, "Debt / EBITDA", pi_formatNumber(debtEbitda), debtEbitdaScore)
        if wHNetD > 0
            r := f_row(3, r, "Net Debt / EBITDA", pi_formatNumber(netDebtEbitda), netDebtEbitdaScore)
        if wHCash > 0
            r := f_row(3, r, "Cash / Debt", pi_formatNumber(cashDebt), cashDebtScore)
        if wHIC > 0
            r := f_row(3, r, "Interest Cover", pi_formatNumber(interestCover), interestScore)
        if wHCR > 0
            r := f_row(3, r, "Current Ratio", pi_formatNumber(currRatio), currScore)
        if wHQR > 0
            r := f_row(3, r, "Quick Ratio", pi_formatNumber(quickRatio), quickScore)
        if wHAltman > 0
            r := f_row(3, r, "Altman Z-Score", pi_formatNumber(altmanZ), altmanScore)
        r := f_row(3, r, "OCF", pi_formatMoney(ocf), ocfScore)
        r := f_row(3, r, "FCF", pi_formatMoney(fcf), fcfScore)

    if not noData and tampilMomentum and not tampilCompact
        r := f_section(3, r, isEN ? "MARKET MOMENTUM" : "MOMENTUM PASAR")
        r := f_row(3, r, "RSI 14", pi_formatNumber(rsi14), rsiScore)
        r := f_row(3, r, "1M Return", pi_arrow(ret1m) + pi_formatPercent(ret1m), na)
        r := f_row(3, r, "3M Return", pi_arrow(ret3m) + pi_formatPercent(ret3m), na)
        r := f_row(3, r, "6M Return", pi_arrow(ret6m) + pi_formatPercent(ret6m), na)
        r := f_row(3, r, "12M Return", pi_arrow(ret12m) + pi_formatPercent(ret12m), na)
        r := f_row(3, r, "6M RS vs Index", pi_arrow(relStr6m) + pi_formatPercent(relStr6m), rs6Score)
        r := f_row(3, r, "12M RS vs Index", pi_arrow(relStr12m) + pi_formatPercent(relStr12m), rs12Score)
        r := f_row(3, r, "Volatility", pi_formatPercent(volatility), volScore)
        r := f_row(3, r, "MA 20/50/200", maStatus, maScore)

    if not noData and tampilRisikoGorengan and not tampilCompact
        r := f_section(3, r, isEN ? "PUMP & DUMP RISK" : "DETAIL RISIKO GORENGAN")
        r := f_riskRow(3, r, "Market Cap", pi_formatMoney(mcap), mcapScore)
        r := f_riskRow(3, r, "Nilai Transaksi 20D", pi_formatMoney(valTradedAvg20), liqScore)
        r := f_riskRow(3, r, "Turnover Harian (20D)", pi_formatPercent(turnoverPct), na)
        r := f_riskRow(3, r, "Volatilitas Tahunan", pi_formatPercent(volatility), volRiskScore)
        r := f_riskRow(3, r, "Hari Kena/Dekat ARA-ARB", str.tostring(araHits, "#") + "/" + str.tostring(lookbackARA), araRiskScore)
        r := f_riskRow(3, r, "Tingkat Harga", pi_formatNumber(dClose), priceTierScore)

//══════════════════════════════
//
// BACKLOG → GitHub Issues: https://github.com/akhmfz/papan-instrumen/issues
// Detail: docs/DEVELOPMENT.md § Backlog
//
//══════════════════════════════

Overview

Saham: Papan Instrumen evaluates stocks across up to seven dimensions: Value, Quality, Growth, Health, Income, Momentum, and an optional Indonesia macro factor. The script automatically classifies stocks into 15 sector categories to adjust scoring thresholds and weights accordingly. Features include a dedicated risk assessment module for liquidity and volatility, customizable dimension weights, compact display modes, and bilingual support. It renders a structured fundamental analysis table directly on the price chart.

Details

Published by

akhmfz on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Screeners & dashboards

Markets

Stocks

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Simbol SahamsymbolsimbolInput
Indeks Acuan / BenchmarksymbolIDX:COMPOSITEindeksAcuan
Periode Laporan KeuanganstringFQperiodeLaporan
Posisi TabelstringKanan AtasposisiInput
Ukuran TeksstringKecil SekaliukuranTeksInput
Tema WarnastringProfesional GelapwarnaTema
Gunakan Latar Skor BerwarnabooltruetampilLatarSkor
Tampilkan Bar SkorbooltruetampilBarSkor
Baris Berselang-seling HalusbooltruebarisSelangSeling
Header Bagian BerwarnabooltrueheaderBerwarna
Tampilkan Simbol ▲ ▼booltruetampilSimbolStatus
Tampilkan Indikator Kelengkapan Data (n/x)booltruetampilKelengkapan
Show all 40 settings
SettingTypeDefaultVariable
Mode Ringkas (Compact Mode)boolfalsetampilCompact
Bahasa / LanguagestringIndonesiabahasa
Tampilkan RingkasanbooltruetampilRingkasan
Tampilkan ValuasibooltruetampilValuasi
Tampilkan KualitasbooltruetampilKualitas
Tampilkan PertumbuhanbooltruetampilPertumbuhan
Tampilkan Kesehatan KeuanganbooltruetampilKesehatan
Tampilkan Dividen & Imbal HasilbooltruetampilDividen
Tampilkan MomentumbooltruetampilMomentum
Aktifkan Faktor Indonesia (7th Factor)boolfalsetampilIndonesia
Deteksi SektorstringOtomatismodeSektor
Longgarkan Graham Number untuk Sektor SiklikalbooltruetoleransiSiklikal
Gunakan Bobot Kustom (default: 6 faktor sama rata)boolfalsegunakanBobotKustom
Preset BobotstringCustompresetBobot
Bobot Valuefloat1.0bobotValue
Bobot Qualityfloat1.0bobotQuality
Bobot Growthfloat1.0bobotGrowth
Bobot Healthfloat1.0bobotHealth
Bobot Momentumfloat1.0bobotMomentum
Bobot Incomefloat1.0bobotIncome
Bobot Indonesia Factorfloat1.0bobotIndonesia
Tampilkan Modul Risiko LikuiditasbooltruetampilRisikoGorengan
Ambang Deteksi ARA/ARB (%)float24.0ambangARA
Lookback Hari untuk Hitung ARA/ARBint20lookbackARA
Ambang Kapitalisasi 'Kecil' (Miliar Rp)float1000kapKecilMiliar
Ambang Kapitalisasi 'Besar' (Miliar Rp)float10000kapBesarMiliar
Ambang Nilai Transaksi Harian 'Rendah' (Juta Rp, avg 20D)float500likuiditasRendahJt
Ambang Nilai Transaksi Harian 'Tinggi' (Juta Rp, avg 20D)float20000likuiditasTinggiJt
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Symbol Info Helper

by everget
948 stars

Symbol Info Helper is an informational utility script that displays metadata about the currently selected instrument directly on the main price chart. It gathers built-in symbol properties including ticker identifier, description, instrument type, point value,

Indicator v4 Screeners & dashboards
Updated 10 days ago · GPL-3.0 GitHub repository of Symbol Info Helper
575 stars

The indicator plots ICT displacement candles on the price chart and can switch to retracement scanning. Displacement requires a move larger than a set share of the 14-bar average high-low range, lasting at least a chosen number of bars, with optional close, pr

Indicator v6 SMC / ICT / price actionCandlestick patterns
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Displacement Candles Indicator
330 stars

This indicator monitors multiple cryptocurrency symbols for trading signals. It calculates and plots entry prices, take profit, and stop loss levels for each symbol including BTCUSDT, ETHUSDT, BNBUSDT and others. Price crossovers trigger buy, sell or close ale

Indicator v5 Support & resistanceScreeners & dashboards
Updated 2 months ago · None stated GitHub repository of Multi Alert Long/Short [Alorse]

Pricing Table

by namuan
318 stars

This indicator calculates theoretical options contract values and in-the-money probabilities using historical realized volatility across multiple standard deviations. It displays these metrics in a table overlay directly on the price chart. Users can adjust th

Indicator v4 Volatility & bandsScreeners & dashboards
Updated 2 months ago · MIT GitHub repository of Pricing Table

3938 Tracker

by Allen1212
303 stars

3938 Tracker visualizes historical buying and selling activity from ARK Invest funds directly on the main price chart. It plots labels at specific timestamps corresponding to trade dates, indicating buy or sell actions along with the count of participating ETF

Indicator v4 Screeners & dashboards
Updated 2 years ago · None stated GitHub repository of 3938 Tracker

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers