Khajanchi Smart Holdings Tracker

rishabfinances · study · 493 行 · 点赞 24 · TradingView 原页

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

Pine Script

//@version=6
// [v1.0] Khajanchi Smart Holdings Tracker (Multi-Broker & Asset Bucket Portfolio HUD)
indicator("Khajanchi Smart Holdings Tracker", shorttitle="KW Holdings", overlay=true, max_boxes_count=10, max_labels_count=10, max_lines_count=10)
 
// ==============================================================================
// 1. SEGMENTED PORTFOLIO LEDGERS (8 ASSET / BROKER BUCKETS)
// Format: TICKER, QTY, AVG_BUY_PRICE, YYYY-MM-DD (Set Qty = 0 to disable)
// ==============================================================================
GRP_1 = "1. Primary Equity Account (Broker A)"
string defDhan = "RELIANCE, 10, 1280.00, 2026-06-15\nTCS, 5, 3450.00, 2026-07-10\nINFY, 12, 1520.00, 2026-08-05"
inDhan = input.text_area(defDhan, "Broker A Equity Holdings", group=GRP_1)
 
GRP_2 = "2. Secondary Equity Account (Broker B)"
string defGroww = "HDFCBANK, 15, 1640.00, 2026-05-20\nICICIBANK, 20, 1250.00, 2026-07-18\nITC, 50, 465.00, 2026-09-01"
inGroww = input.text_area(defGroww, "Broker B Equity Holdings", group=GRP_2)
 
GRP_3 = "3. Crypto Spot Holdings"
string defCrypto = "BTCUSDT, 0.01500000, 68500.00, 2026-06-08\nETHUSDT, 0.25000000, 2450.00, 2026-06-08\nSOLUSDT, 3.50000000, 135.00, 2026-07-12"
inCrypto = input.text_area(defCrypto, "Crypto Holdings", group=GRP_3)
cryptoExch = input.string("BINANCE", "Exchange Prefix for Crypto Pricing", options=["BINANCE", "BYBIT", "COINBASE", "OKX", "KUCOIN"], group=GRP_3)
 
GRP_4A = "4A. Listed REITs"
string defReits = "EMBASSY, 20, 385.00, 2026-06-12\nMINDSPACE, 15, 360.00, 2026-07-15\nBIRET, 25, 290.00, 2026-08-10\nNXST, 40, 145.00, 2026-09-05"
inReits = input.text_area(defReits, "REIT Holdings", group=GRP_4A)
 
GRP_4B = "4B. Listed InvITs"
string defInvits = "INDIGRID, 50, 138.00, 2026-06-20\nPGINVIT, 80, 92.50, 2026-07-25\nIRBINVIT, 100, 64.00, 2026-08-18"
inInvits = input.text_area(defInvits, "InvIT Holdings", group=GRP_4B)
 
GRP_5 = "5. Commodities / Bullion ETFs"
string defComm = "GOLDBEES, 50, 62.50, 2026-05-21\nSILVERBEES, 40, 88.00, 2026-05-21"
inComm = input.text_area(defComm, "Commodities / ETFs", group=GRP_5)
 
GRP_6 = "6. Index ETFs"
string defIdx = "NIFTYBEES, 25, 265.00, 2026-06-01\nJUNIORBEES, 0, 700.00, 2026-01-01\nBANKBEES, 0, 520.00, 2026-01-01"
inIdx = input.text_area(defIdx, "Index ETFs (Set Qty > 0 to activate)", group=GRP_6)
 
GRP_7 = "7. Mutual Funds / Listed Units"
string defMF = "MOM100, 0, 150.00, 2026-01-01"
inMF = input.text_area(defMF, "Mutual Fund / Listed Units (Set Qty > 0 to activate)", group=GRP_7)
 
// ==============================================================================
// 2. DUAL USDT/INR FX & VISUAL CUSTOMIZATION
// ==============================================================================
GRP_FX       = "8. Dual USDT/INR Conversion (Crypto INR Valuation)"
buyFxRate    = input.float(86.50, "Avg Buy USDT/INR Rate (Historical Entry FX)", minval=1.0, step=0.05, group=GRP_FX)
curFxRate    = input.float(89.20, "Current USDT/INR Rate (Live Exit FX)", minval=1.0, step=0.05, group=GRP_FX)
useInterbank = input.bool(false, "Override Current FX with Global Interbank FX_IDC:USDINR", group=GRP_FX)
 
GRP_VIS      = "9. Chart Line & Marker Customization"
showBgBox    = input.bool(false, "Highlight Background Box (Off = Clean Candles)", group=GRP_VIS)
bgBoxColor   = input.color(color.new(#000000, 92), "Background Highlight Color", group=GRP_VIS)
showBuyLine  = input.bool(true, "Show Horizontal Avg Buy Price Line", group=GRP_VIS)
buyLineStyle = input.string("Dashed", "Avg Buy Line Style", options=["Solid", "Dashed", "Dotted"], group=GRP_VIS)
buyLineWidth = input.int(1, "Avg Buy Line Thickness", minval=1, maxval=4, group=GRP_VIS)
buyLineCol   = input.color(color.new(#000000, 45), "Avg Buy Line Color", group=GRP_VIS)
showBuyMark  = input.bool(true, "Show Buy Candle Marker Label", group=GRP_VIS)
markerBgCol  = input.color(color.new(#000000, 0), "Buy Marker Background Color", group=GRP_VIS)
markerTxtCol = input.color(color.new(#FFFFFF, 0), "Buy Marker Text Color", group=GRP_VIS)
 
GRP_HUD        = "10. Monochrome HUD Customization"
showHUD        = input.bool(true, "Show Holdings HUD", group=GRP_HUD)
showBucketTot  = input.bool(true, "Show Active Bucket Total Valuation (Equities / REITs / InvITs)", group=GRP_HUD)
showCryptoTot  = input.bool(true, "Show Total Portfolio Section (on Crypto Charts)", group=GRP_HUD)
hudPosIn       = input.string("Top Right", "HUD Position", options=["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left", "Top Center", "Middle Center", "Bottom Center"], group=GRP_HUD)
hudSizeIn      = input.string("Small", "HUD Body Text Size", options=["Tiny", "Small", "Normal"], group=GRP_HUD)
hudHdrSizeIn   = input.string("Tiny", "HUD Section Header Size", options=["Tiny", "Small"], group=GRP_HUD)
hudBgCol       = input.color(color.new(#000000, 5), "HUD Primary Background", group=GRP_HUD)
hudSecBgCol    = input.color(color.new(#181818, 5), "HUD Section Sub-Header Background", group=GRP_HUD)
hudBorderCol   = input.color(color.new(#FFFFFF, 75), "HUD Border Color", group=GRP_HUD)
hudTxtCol      = input.color(color.white, "HUD Primary Text Color", group=GRP_HUD)
hudSecTxtCol   = input.color(color.new(#BBBBBB, 0), "HUD Section Label Color", group=GRP_HUD)
hudPosCol      = input.color(color.new(#00E676, 0), "Positive PnL Color", group=GRP_HUD)
hudNegCol      = input.color(color.new(#FF5252, 0), "Negative PnL Color", group=GRP_HUD)
 
// ==============================================================================
// 3. EXCHANGE & CURRENCY DETECTION
// ==============================================================================
bool isINR = syminfo.prefix == "NSE" or syminfo.prefix == "BSE" or syminfo.currency == "INR"
float liveInterbank = request.security("FX_IDC:USDINR", "D", close, ignore_invalid_symbol=true)
float activeCurFx   = (useInterbank and not na(liveInterbank) and liveInterbank > 0) ? liveInterbank : curFxRate
 
// ==============================================================================
// 4. MULTI-BUCKET LEDGER PARSER
// ==============================================================================
var bool   hasHolding   = false
var float  holdQty      = 0.0
var float  totalCost    = 0.0
var float  avgBuyPrice  = 0.0
var int    earliestTs   = na
var string buyDateStr   = ""
var string bucketLabel  = ""
 
f_parseBucket(string rawBlock, string bucketName) =>
    bool   found   = false
    float  qSum    = 0.0
    float  cSum    = 0.0
    int    minTs   = na
    string minDStr = ""
    string[] rows  = str.split(rawBlock, "\n")
    if array.size(rows) > 0
        for i = 0 to array.size(rows) - 1
            string row = str.trim(array.get(rows, i))
            if row != ""
                string[] cols = str.split(row, ",")
                if array.size(cols) >= 4
                    string tkr = str.upper(str.replace_all(array.get(cols, 0), " ", ""))
                    if tkr == str.upper(syminfo.ticker)
                        float q = nz(str.tonumber(str.replace_all(array.get(cols, 1), " ", "")), 0.0)
                        float p = nz(str.tonumber(str.replace_all(array.get(cols, 2), " ", "")), 0.0)
                        string dStr = str.replace_all(array.get(cols, 3), " ", "")
                        if q > 0 and p > 0
                            found := true
                            qSum  += q
                            cSum  += (q * p)
                            string[] dParts = str.split(dStr, "-")
                            if array.size(dParts) == 3
                                int y = int(str.tonumber(array.get(dParts, 0)))
                                int m = int(str.tonumber(array.get(dParts, 1)))
                                int d = int(str.tonumber(array.get(dParts, 2)))
                                int ts = timestamp(syminfo.timezone, y, m, d, 0, 0, 0)
                                if na(minTs) or ts < minTs
                                    minTs   := ts
                                    minDStr := dStr
    [found, qSum, cSum, minTs, minDStr, bucketName]
 
if barstate.isfirst
    string[] blocks = array.from(inDhan, inGroww, inCrypto, inReits, inInvits, inComm, inIdx, inMF)
    string[] names  = array.from("Primary Equity", "Secondary Equity", "Crypto Spot", "Listed REITs", "Listed InvITs", "Commodities", "Index ETFs", "Mutual Funds")
    
    for b = 0 to 7
        [fnd, qB, cB, tsB, dStrB, bName] = f_parseBucket(array.get(blocks, b), array.get(names, b))
        if fnd
            hasHolding  := true
            holdQty     += qB
            totalCost   += cB
            bucketLabel := bucketLabel == "" ? bName : bucketLabel + " + " + bName
            if na(earliestTs) or (not na(tsB) and tsB < earliestTs)
                earliestTs := tsB
                buyDateStr := dStrB
 
    if hasHolding and holdQty > 0
        avgBuyPrice := totalCost / holdQty
 
int targetBuyTime = hasHolding ? earliestTs : na
 
// ==============================================================================
// 5. CONTEXT-AWARE LIVE AGGREGATOR (STAYING STRICTLY WITHIN 40 SECURITY CALLS)
// ==============================================================================
f_extractArrays(string rawBlock) =>
    string[] tkrs   = array.new_string()
    float[]  qtys   = array.new_float()
    float[]  prices = array.new_float()
    string[] rows   = str.split(rawBlock, "\n")
    if array.size(rows) > 0
        for i = 0 to array.size(rows) - 1
            string row = str.trim(array.get(rows, i))
            if row != ""
                string[] cols = str.split(row, ",")
                if array.size(cols) >= 3
                    string t = str.upper(str.replace_all(array.get(cols, 0), " ", ""))
                    float q  = nz(str.tonumber(str.replace_all(array.get(cols, 1), " ", "")), 0.0)
                    float p  = nz(str.tonumber(str.replace_all(array.get(cols, 2), " ", "")), 0.0)
                    if t != "" and q > 0 and p > 0
                        array.push(tkrs, t)
                        array.push(qtys, q)
                        array.push(prices, p)
    [tkrs, qtys, prices]
 
var string[] dTkrs = array.new_string(), var float[] dQtys = array.new_float(), var float[] dPrices = array.new_float()
var string[] gTkrs = array.new_string(), var float[] gQtys = array.new_float(), var float[] gPrices = array.new_float()
var string[] rTkrs = array.new_string(), var float[] rQtys = array.new_float(), var float[] rPrices = array.new_float()
var string[] iTkrs = array.new_string(), var float[] iQtys = array.new_float(), var float[] iPrices = array.new_float()
var string[] cTkrs = array.new_string(), var float[] cQtys = array.new_float(), var float[] cPrices = array.new_float()
 
if barstate.isfirst
    [tD, qD, pD] = f_extractArrays(inDhan)
    dTkrs := tD, dQtys := qD, dPrices := pD
    [tG, qG, pG] = f_extractArrays(inGroww)
    gTkrs := tG, gQtys := qG, gPrices := pG
    [tR, qR, pR] = f_extractArrays(inReits)
    rTkrs := tR, rQtys := qR, rPrices := pR
    [tI, qI, pI] = f_extractArrays(inInvits)
    iTkrs := tI, iQtys := qI, iPrices := pI
    [tC, qC, pC] = f_extractArrays(inCrypto)
    cTkrs := tC, cQtys := qC, cPrices := pC
 
bool isDhanChart   = bucketLabel == "Primary Equity"
bool isGrowwChart  = bucketLabel == "Secondary Equity"
bool isReitChart   = bucketLabel == "Listed REITs"
bool isInvitChart  = bucketLabel == "Listed InvITs"
bool isReitOrInvit = isReitChart or isInvitChart
 
f_resolveSym(string rawTkr, bool isCryptoMode) =>
    if rawTkr == ""
        ""
    else if isCryptoMode
        cryptoExch + ":" + rawTkr
    else if str.contains(rawTkr, ":")
        rawTkr
    else if str.length(rawTkr) == 6 and not na(str.tonumber(rawTkr))
        "BSE:" + rawTkr
    else
        "NSE:" + rawTkr
 
string[] eqTkrs   = isGrowwChart ? gTkrs : dTkrs
float[]  eqQtys   = isGrowwChart ? gQtys : dQtys
float[]  eqPrices = isGrowwChart ? gPrices : dPrices
bool     pollEq   = showBucketTot and (isDhanChart or isGrowwChart)
 
f_evalSlot(string[] tkrs, float[] qtys, float[] prices, int idx, bool isCryptoMode, bool enabled) =>
    bool valid  = enabled and idx < array.size(tkrs)
    string rawT = valid ? array.get(tkrs, idx) : ""
    string sym  = valid ? f_resolveSym(rawT, isCryptoMode) : ""
    float  qty  = valid ? array.get(qtys, idx) : 0.0
    float  avg  = valid ? array.get(prices, idx) : 0.0
    float  ltp  = valid and sym != "" ? request.security(sym, "D", close, ignore_invalid_symbol=true) : 0.0
    float  inv  = qty * avg
    float  cur  = qty * nz(ltp, avg)
    [inv, cur]
 
// Group A: 24 slots for Primary OR Secondary Equity (polled only on Equity charts)
[eqInv0,  eqCur0]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 0,  false, pollEq)
[eqInv1,  eqCur1]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 1,  false, pollEq)
[eqInv2,  eqCur2]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 2,  false, pollEq)
[eqInv3,  eqCur3]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 3,  false, pollEq)
[eqInv4,  eqCur4]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 4,  false, pollEq)
[eqInv5,  eqCur5]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 5,  false, pollEq)
[eqInv6,  eqCur6]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 6,  false, pollEq)
[eqInv7,  eqCur7]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 7,  false, pollEq)
[eqInv8,  eqCur8]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 8,  false, pollEq)
[eqInv9,  eqCur9]  = f_evalSlot(eqTkrs, eqQtys, eqPrices, 9,  false, pollEq)
[eqInv10, eqCur10] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 10, false, pollEq)
[eqInv11, eqCur11] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 11, false, pollEq)
[eqInv12, eqCur12] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 12, false, pollEq)
[eqInv13, eqCur13] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 13, false, pollEq)
[eqInv14, eqCur14] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 14, false, pollEq)
[eqInv15, eqCur15] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 15, false, pollEq)
[eqInv16, eqCur16] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 16, false, pollEq)
[eqInv17, eqCur17] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 17, false, pollEq)
[eqInv18, eqCur18] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 18, false, pollEq)
[eqInv19, eqCur19] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 19, false, pollEq)
[eqInv20, eqCur20] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 20, false, pollEq)
[eqInv21, eqCur21] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 21, false, pollEq)
[eqInv22, eqCur22] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 22, false, pollEq)
[eqInv23, eqCur23] = f_evalSlot(eqTkrs, eqQtys, eqPrices, 23, false, pollEq)
 
float eqBucketInv = eqInv0 + eqInv1 + eqInv2 + eqInv3 + eqInv4 + eqInv5 + eqInv6 + eqInv7 + eqInv8 + eqInv9 + eqInv10 + eqInv11 + eqInv12 + eqInv13 + eqInv14 + eqInv15 + eqInv16 + eqInv17 + eqInv18 + eqInv19 + eqInv20 + eqInv21 + eqInv22 + eqInv23
float eqBucketCur = eqCur0 + eqCur1 + eqCur2 + eqCur3 + eqCur4 + eqCur5 + eqCur6 + eqCur7 + eqCur8 + eqCur9 + eqCur10 + eqCur11 + eqCur12 + eqCur13 + eqCur14 + eqCur15 + eqCur16 + eqCur17 + eqCur18 + eqCur19 + eqCur20 + eqCur21 + eqCur22 + eqCur23
float eqBucketPnl = eqBucketCur - eqBucketInv
float eqBucketPct = eqBucketInv > 0 ? (eqBucketPnl / eqBucketInv) * 100.0 : 0.0
 
// Group B: 14 multiplexed slots (Crypto 14 OR REITs 7 + InvITs 7)
bool pollRI = showBucketTot and isReitOrInvit
bool pollCr = showCryptoTot and not isINR
 
[mInv0,  mCur0]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 0, pollCr, pollCr or pollRI)
[mInv1,  mCur1]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 1, pollCr, pollCr or pollRI)
[mInv2,  mCur2]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 2, pollCr, pollCr or pollRI)
[mInv3,  mCur3]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 3, pollCr, pollCr or pollRI)
[mInv4,  mCur4]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 4, pollCr, pollCr or pollRI)
[mInv5,  mCur5]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 5, pollCr, pollCr or pollRI)
[mInv6,  mCur6]  = f_evalSlot(pollCr ? cTkrs : rTkrs, pollCr ? cQtys : rQtys, pollCr ? cPrices : rPrices, 6, pollCr, pollCr or pollRI)
 
[mInv7,  mCur7]  = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 7  : 0, pollCr, pollCr or pollRI)
[mInv8,  mCur8]  = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 8  : 1, pollCr, pollCr or pollRI)
[mInv9,  mCur9]  = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 9  : 2, pollCr, pollCr or pollRI)
[mInv10, mCur10] = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 10 : 3, pollCr, pollCr or pollRI)
[mInv11, mCur11] = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 11 : 4, pollCr, pollCr or pollRI)
[mInv12, mCur12] = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 12 : 5, pollCr, pollCr or pollRI)
[mInv13, mCur13] = f_evalSlot(pollCr ? cTkrs : iTkrs, pollCr ? cQtys : iQtys, pollCr ? cPrices : iPrices, pollCr ? 13 : 6, pollCr, pollCr or pollRI)
 
// Separate REITs Totals
float reitInv = mInv0 + mInv1 + mInv2 + mInv3 + mInv4 + mInv5 + mInv6
float reitCur = mCur0 + mCur1 + mCur2 + mCur3 + mCur4 + mCur5 + mCur6
float reitPnl = reitCur - reitInv
float reitPct = reitInv > 0 ? (reitPnl / reitInv) * 100.0 : 0.0
 
// Separate InvITs Totals
float invitInv = mInv7 + mInv8 + mInv9 + mInv10 + mInv11 + mInv12 + mInv13
float invitCur = mCur7 + mCur8 + mCur9 + mCur10 + mCur11 + mCur12 + mCur13
float invitPnl = invitCur - invitInv
float invitPct = invitInv > 0 ? (invitPnl / invitInv) * 100.0 : 0.0
 
// Combined REITs + InvITs Totals
float combRIInv = reitInv + invitInv
float combRICur = reitCur + invitCur
float combRIPnl = combRICur - combRIInv
float combRIPct = combRIInv > 0 ? (combRIPnl / combRIInv) * 100.0 : 0.0
 
// Crypto Totals
float portCryptoInvUSD = reitInv + invitInv
float portCryptoCurUSD = reitCur + invitCur
float portCryptoPnlUSD = portCryptoCurUSD - portCryptoInvUSD
float portCryptoPctUSD = portCryptoInvUSD > 0 ? (portCryptoPnlUSD / portCryptoInvUSD) * 100.0 : 0.0
 
float portCryptoInvINR = portCryptoInvUSD * buyFxRate
float portCryptoCurINR = portCryptoCurUSD * activeCurFx
float portCryptoPnlINR = portCryptoCurINR - portCryptoInvINR
float portCryptoPctINR = portCryptoInvINR > 0 ? (portCryptoPnlINR / portCryptoInvINR) * 100.0 : 0.0
 
// ==============================================================================
// 6. TIME-ANCHORED CANDLE MATCHING & CLEAN LINES
// ==============================================================================
var int   entryTimeMs = na
var box   holdBox     = na
var line  avgLine     = na
 
bool isBuyCandle = hasHolding and na(entryTimeMs) and not na(targetBuyTime) and time >= targetBuyTime
 
if isBuyCandle
    entryTimeMs := time
    if showBuyMark
        label.new(x=time, y=low, text="▲ BUY\n" + str.tostring(avgBuyPrice, format.mintick), xloc=xloc.bar_time, color=markerBgCol, textcolor=markerTxtCol, style=label.style_label_up, size=size.small)
 
string lStyle = buyLineStyle == "Solid" ? line.style_solid : buyLineStyle == "Dotted" ? line.style_dotted : line.style_dashed
 
if hasHolding and not na(entryTimeMs) and barstate.islast
    float topVal = math.max(close, avgBuyPrice)
    float botVal = math.min(close, avgBuyPrice)
    if topVal == botVal
        topVal := avgBuyPrice + syminfo.mintick * 10
 
    int barStepMs = timeframe.in_seconds(timeframe.period) * 1000
    int rightTime = time + (barStepMs * 2)
 
    if showBgBox
        if na(holdBox)
            holdBox := box.new(left=entryTimeMs, top=topVal, right=rightTime, bottom=botVal, xloc=xloc.bar_time, border_color=color.new(#000000, 75), border_style=line.style_dotted, bgcolor=bgBoxColor)
        else
            box.set_lefttop(holdBox, entryTimeMs, topVal)
            box.set_rightbottom(holdBox, rightTime, botVal)
    else if not na(holdBox)
        box.delete(holdBox)
        holdBox := na
 
    if showBuyLine
        if na(avgLine)
            avgLine := line.new(x1=entryTimeMs, y1=avgBuyPrice, x2=rightTime, y2=avgBuyPrice, xloc=xloc.bar_time, color=buyLineCol, style=lStyle, width=buyLineWidth)
        else
            line.set_xy1(avgLine, entryTimeMs, avgBuyPrice)
            line.set_xy2(avgLine, rightTime, avgBuyPrice)
            line.set_color(avgLine, buyLineCol)
            line.set_style(avgLine, lStyle)
            line.set_width(avgLine, buyLineWidth)
    else if not na(avgLine)
        line.delete(avgLine)
        avgLine := na
 
// ==============================================================================
// 7. INDIVIDUAL HOLDING PNL & DURATION CALCULATIONS
// ==============================================================================
float investedBase = hasHolding ? (avgBuyPrice * holdQty) : 0.0
float currentBase  = hasHolding ? (close * holdQty) : 0.0
float pnlAmtBase   = currentBase - investedBase
float pnlPct       = investedBase > 0 ? (pnlAmtBase / investedBase) * 100.0 : 0.0
 
int msHeld   = hasHolding and not na(targetBuyTime) ? math.max(0, timenow - targetBuyTime) : 0
int daysHeld = int(math.floor(msHeld / 86400000))
 
float avgBuyINR   = isINR ? avgBuyPrice : avgBuyPrice * buyFxRate
float investedINR = isINR ? investedBase : investedBase * buyFxRate
float currentINR  = isINR ? currentBase  : currentBase * activeCurFx
float pnlAmtINR   = currentINR - investedINR
float pnlPctINR   = investedINR > 0 ? (pnlAmtINR / investedINR) * 100.0 : 0.0
 
// ==============================================================================
// 8. UNIFIED MONOCHROME TELEMETRY HUD
// ==============================================================================
f_getPos(string p) =>
    p == "Top Left" ? position.top_left : p == "Middle Left" ? position.middle_left : p == "Bottom Left" ? position.bottom_left : p == "Top Center" ? position.top_center : p == "Middle Center" ? position.middle_center : p == "Bottom Center" ? position.bottom_center : p == "Middle Right" ? position.middle_right : p == "Bottom Right" ? position.bottom_right : position.top_right
 
string txtSz = hudSizeIn == "Tiny" ? size.tiny : hudSizeIn == "Normal" ? size.normal : size.small
string hdrSz = hudHdrSizeIn == "Small" ? size.small : size.tiny
 
var table hud = table.new(f_getPos(hudPosIn), 2, 26, bgcolor=hudBgCol, border_width=1, border_color=hudBorderCol, frame_width=1, frame_color=hudBorderCol)
 
f_fmtSigned(float val, string prefix) =>
    (val >= 0 ? "+" : "-") + prefix + str.tostring(math.abs(val), "#,##0.00")
 
f_fmtPct(float pct) =>
    (pct >= 0 ? "+" : "-") + str.tostring(math.abs(pct), "0.00") + "%"
 
f_addBucketBlock(int startRow, string titleLeft, string titleRight, float invVal, float curVal, float pnlVal, float pctVal) =>
    color pCol = pnlVal >= 0 ? hudPosCol : hudNegCol
    table.cell(hud, 0, startRow, titleLeft, text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_left, text_formatting=text.format_bold)
    table.cell(hud, 1, startRow, titleRight, text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_right)
 
    table.cell(hud, 0, startRow + 1, "Invested", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, startRow + 1, "₹" + str.tostring(invVal, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, startRow + 2, "Current Value", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, startRow + 2, "₹" + str.tostring(curVal, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
 
    table.cell(hud, 0, startRow + 3, "Bucket PnL", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, startRow + 3, f_fmtSigned(pnlVal, "₹") + " (" + f_fmtPct(pctVal) + ")", text_color=pCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
    startRow + 4
 
if showHUD and hasHolding and barstate.islast
    string currPrefix = isINR ? "₹" : "$"
    color basePnlCol  = pnlAmtBase >= 0 ? hudPosCol : hudNegCol
 
    table.cell(hud, 0, 0, "Khajanchi Wealth Holdings  •  " + syminfo.ticker, text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_center, text_formatting=text.format_bold)
    table.merge_cells(hud, 0, 0, 1, 0)
 
    table.cell(hud, 0, 1, "Portfolio / Bucket", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 1, bucketLabel, text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
 
    table.cell(hud, 0, 2, "First Buy Date", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 2, buyDateStr, text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 3, "Days Holding", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 3, str.tostring(daysHeld) + " Days", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 4, "Quantity Held", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 4, str.tostring(holdQty), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 5, isINR ? "STATS INR" : "STATS USD", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_left, text_formatting=text.format_bold)
    table.cell(hud, 1, 5, isINR ? "SPOT INR" : "SPOT USD", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 6, "Avg Buy Price", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 6, currPrefix + str.tostring(avgBuyPrice, format.mintick), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 7, "Invested", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 7, currPrefix + str.tostring(investedBase, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 8, "Current", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 8, currPrefix + str.tostring(currentBase, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
    table.cell(hud, 0, 9, "Net PnL", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
    table.cell(hud, 1, 9, f_fmtSigned(pnlAmtBase, currPrefix) + " (" + f_fmtPct(pnlPct) + ")", text_color=basePnlCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
 
    int nextRow = 10
 
    // INR Bucket Valuation Sections (Primary Equity, Secondary Equity, Separate REITs, Separate InvITs, and Combined REITs + InvITs)
    if isINR and showBucketTot
        if isDhanChart and eqBucketInv > 0
            nextRow := f_addBucketBlock(nextRow, "PRIMARY EQUITY PORTFOLIO", str.tostring(array.size(dTkrs)) + " STOCKS", eqBucketInv, eqBucketCur, eqBucketPnl, eqBucketPct)
        else if isGrowwChart and eqBucketInv > 0
            nextRow := f_addBucketBlock(nextRow, "SECONDARY EQUITY PORTFOLIO", str.tostring(array.size(gTkrs)) + " STOCKS", eqBucketInv, eqBucketCur, eqBucketPnl, eqBucketPct)
        else if isReitOrInvit
            if reitInv > 0
                nextRow := f_addBucketBlock(nextRow, "LISTED REITS PORTFOLIO", str.tostring(array.size(rTkrs)) + " REITS", reitInv, reitCur, reitPnl, reitPct)
            if invitInv > 0
                nextRow := f_addBucketBlock(nextRow, "LISTED INVITS PORTFOLIO", str.tostring(array.size(iTkrs)) + " INVITS", invitInv, invitCur, invitPnl, invitPct)
            if combRIInv > 0
                nextRow := f_addBucketBlock(nextRow, "COMBINED REITS + INVITS", str.tostring(array.size(rTkrs) + array.size(iTkrs)) + " TOTAL", combRIInv, combRICur, combRIPnl, combRIPct)
 
    if not isINR
        color inrPnlCol = pnlAmtINR >= 0 ? hudPosCol : hudNegCol
 
        table.cell(hud, 0, 10, "STATS INR", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_left, text_formatting=text.format_bold)
        table.cell(hud, 1, 10, "₹" + str.tostring(buyFxRate, "0.00") + " → ₹" + str.tostring(activeCurFx, "0.00"), text_color=hudTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_right)
 
        table.cell(hud, 0, 11, "Avg Buy Price", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
        table.cell(hud, 1, 11, "₹" + str.tostring(avgBuyINR, format.mintick), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
        table.cell(hud, 0, 12, "Invested", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
        table.cell(hud, 1, 12, "₹" + str.tostring(investedINR, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
        table.cell(hud, 0, 13, "Current", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
        table.cell(hud, 1, 13, "₹" + str.tostring(currentINR, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
        table.cell(hud, 0, 14, "Net PnL", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
        table.cell(hud, 1, 14, f_fmtSigned(pnlAmtINR, "₹") + " (" + f_fmtPct(pnlPctINR) + ")", text_color=inrPnlCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
 
        if showCryptoTot and portCryptoInvUSD > 0
            color pUsdCol = portCryptoPnlUSD >= 0 ? hudPosCol : hudNegCol
            color pInrCol = portCryptoPnlINR >= 0 ? hudPosCol : hudNegCol
 
            table.cell(hud, 0, 15, "TOTAL PORTFOLIO USD", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_left, text_formatting=text.format_bold)
            table.cell(hud, 1, 15, str.tostring(array.size(cTkrs)) + " COINS", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 16, "Invested", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 16, "$" + str.tostring(portCryptoInvUSD, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 17, "Current", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 17, "$" + str.tostring(portCryptoCurUSD, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 18, "Portfolio PnL", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 18, f_fmtSigned(portCryptoPnlUSD, "$") + " (" + f_fmtPct(portCryptoPctUSD) + ")", text_color=pUsdCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)
 
            table.cell(hud, 0, 19, "TOTAL PORTFOLIO INR", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_left, text_formatting=text.format_bold)
            table.cell(hud, 1, 19, "COINDCX INR", text_color=hudSecTxtCol, bgcolor=hudSecBgCol, text_size=hdrSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 20, "Invested", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 20, "₹" + str.tostring(portCryptoInvINR, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 21, "Current", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 21, "₹" + str.tostring(portCryptoCurINR, "#,##0.00"), text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right)
 
            table.cell(hud, 0, 22, "Portfolio PnL", text_color=hudTxtCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_left)
            table.cell(hud, 1, 22, f_fmtSigned(portCryptoPnlINR, "₹") + " (" + f_fmtPct(portCryptoPctINR) + ")", text_color=pInrCol, bgcolor=hudBgCol, text_size=txtSz, text_halign=text.align_right, text_formatting=text.format_bold)

← 返回列表