COT+ (M1D)

mayb1dayy · study · 367 行 · 点赞 45 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mayb1dayy
 
//@version=6
indicator("COT+ (M1D)", "COT+", overlay = false, format = format.volume, max_boxes_count = 10, max_lines_count = 10)
 
// COT+ (M1D) - one Commitment of Traders pane for every layout.
// DEFAULT = ICT's read of the commercials (the hedging program):
//   Legacy report, NET positions (long - short): commercials red, large specs blue; black step = the commercials' midline.
//   The range box = the commercials' highest and lowest net over the lookback (12 months by default).
//   Its midline is ICT's "new zero line": net above it = commercials BUYING (bullish, upper half blue),
//   below it = SELLING (bearish, lower half red). The printed zero is not the signal.
//   The table reads the same test over 3 months, 6 months, 12 months, 2 years and 3 years: BUY or SELL.
//   OI 4W row = ICT open interest confirmation: OI down 10%+ while commercial net rises = short covering (bullish);
//   OI up 10%+ while commercial net falls = bearish; anything else = no confirmation.
//   Same method as the barchart-cot-chart-capture skill, so the pane and the captured read agree.
// Optional: Report = Auto switches to the newer reports by market:
// Picks the right CFTC report from the symbol, so one indicator slot covers every market:
//   index / rates / FX / crypto futures (NQ, ES, ZN, 6E, BTC ...) -> Financial (TFF):
//       Dealers (the banks, smart money) vs Leveraged Funds (hedge funds, the specs) + Asset Managers
//   commodities (GC, CL, SI, ZC ...) -> Disaggregated:
//       Producers / Merchants (hedgers, smart money) vs Managed Money (specs) + Swap Dealers
//   anything else -> Legacy: Commercials vs Large Speculators + Small Traders
// Each line is that group's NET position (long - short). The COT Index mode scales the net into
// 0-100 over the lookback in weeks (the ICT / Williams reading: 80+ = extreme long, 20- = extreme short).
// Data is WEEKLY (positions as of Tuesday, published Friday). It refreshes on its own every week.
// Built on TradingView/LibraryCOT/6 (17 Oct 2026). If TradingView publishes /7, bump the import.
// COT exists only for CFTC-reported FUTURES. On a CFD chart (NAS100, XAUUSD ...) set "Futures symbol".
 
 
 
import TradingView/LibraryCOT/6 as cot
 
 
 
//#region ———————————————————— Constants and inputs
 
 
const color INK       = #000000
const color GREY      = #787B86
const color SPEC_BLUE = #1d4ed8
const color COMM_RED    = #f23645
const color SMALL_GREEN = #089981
 
string GRP_DATA  = "Data"
string GRP_STYLE = "Style"
 
string reportInput = input.string("Legacy", "Report", ["Legacy", "Auto", "Financial", "Disaggregated"], group = GRP_DATA,
     tooltip = "Legacy = the classic Barchart COT view: Commercials, Large Specs, Small Traders (ICT's read uses this).\n"
     + "Auto = Financial for index, rate, FX and crypto futures, Disaggregated for commodities.")
string symInput = input.symbol("", "Futures symbol", group = GRP_DATA,
     tooltip = "Blank = the chart's symbol. On a CFD chart (NAS100, US100, XAUUSD) set the futures contract here: CME_MINI:NQ1!, COMEX:GC1!.")
bool   optInput = input.bool(false, "Include options", group = GRP_DATA,
     tooltip = "Off = futures only. On = futures and options combined.")
string modeInput = input.string("Net", "Display", ["Net", "COT Index"], group = GRP_DATA,
     tooltip = "Net = long minus short contracts per group. COT Index = that net scaled 0-100 over the lookback.")
int    idxWeeksInput = input.int(52, "Range lookback (weeks)", minval = 8, maxval = 260, group = GRP_DATA,
     tooltip = "52 weeks = ICT's 12-month range. Sets the midline, the % of range and the COT Index.")
bool   showMidInput  = input.bool(true, "Midline history", group = GRP_DATA,
     tooltip = "ICT's new zero line through time: (highest + lowest commercial net over the lookback) / 2 on every week. The range box already draws today's.")
int    hiBandInput = input.int(80, "Extreme bands", minval = 50, maxval = 100, inline = "bands", group = GRP_DATA)
int    loBandInput = input.int(20, "",              minval = 0,  maxval = 50,  inline = "bands", group = GRP_DATA)
bool   showOiInput = input.bool(false, "Open interest row", group = GRP_DATA,
     tooltip = "Daily open interest against the daily price change (last closed day, no repaint).\n"
     + "Price up + OI up = new longs (strong). Price up + OI down = short covering (weak).\n"
     + "Price down + OI up = new shorts (strong). Price down + OI down = long liquidation (weak).")
 
bool   show1Input = input.bool(true, "Commercials (Dealers / Producers)", inline = "g1", group = GRP_STYLE)
color  col1Input  = input.color(COMM_RED, "", inline = "g1", group = GRP_STYLE)
bool   show2Input = input.bool(true, "Large Specs (Lev Funds / Managed Money)", inline = "g2", group = GRP_STYLE)
color  col2Input  = input.color(SPEC_BLUE, "", inline = "g2", group = GRP_STYLE)
bool   show3Input = input.bool(false, "Small Traders (Asset Mgrs / Swap)", inline = "g3", group = GRP_STYLE)
color  col3Input  = input.color(SMALL_GREEN, "", inline = "g3", group = GRP_STYLE)
bool   showTableInput = input.bool(true, "Table", group = GRP_STYLE)
string tablePosInput  = input.string("top_right", "Table position", ["top_left", "top_right", "bottom_left", "bottom_right"], group = GRP_STYLE)
string sizeInput      = input.string("small", "Text size", ["tiny", "small", "normal", "large"], group = GRP_STYLE)
bool   showBoxInput   = input.bool(true, "Range box", group = GRP_DATA,
     tooltip = "The commercials' highest and lowest net over the lookback, split at the midline: upper half = buying program, lower half = selling program.")
 
const color BUY_BLUE = #1d4ed8
// The windows the table reads, in weeks: 3 months, 6 months, 12 months, 2 years, 3 years.
var array<int>    WIN_WK = array.from(13, 26, 52, 104, 156)
var array<string> WIN_NM = array.from("3M", "6M", "12M", "2Y", "3Y")
var int KEEP_WK = math.max(156, idxWeeksInput)
 
bool isIndex = modeInput == "COT Index"
//#endregion
 
 
 
//#region ———————————————————— Functions
 
 
//@function Resolves a size name from input.string.
//@param s (string) "tiny", "small", "normal" or "large".
//@returns (string) The size constant.
f_size(string s) =>
    switch s
        "tiny"  => size.tiny
        "small" => size.small
        "large" => size.large
        =>         size.normal
 
//@function The futures root of a symbol: "CME_MINI:NQ1!" -> "NQ". Blank = the chart's root.
//@param sym (string) A symbol or ticker ID, or "".
//@returns (string) The root.
rootOf(string sym) =>
    string result = syminfo.root
    if sym != ""
        string t = str.contains(sym, ":") ? str.substring(sym, str.pos(sym, ":") + 1) : sym
        result := str.endswith(t, "!") ? str.substring(t, 0, str.length(t) - 2) : t
    result
 
//@function Net position (long - short) for one group.
//@param report (string) "Legacy", "Disaggregated" or "Financial".
//@param code   (string) The CFTC code.
//@param name   (string) The library's metric name, e.g. "Dealer Positions".
//@returns (float) Long minus short contracts.
netOf(string report, string code, string name) =>
    float l = cot.requestCommitmentOfTraders(report, code, optInput, name, "Long",  "All")
    float s = cot.requestCommitmentOfTraders(report, code, optInput, name, "Short", "All")
    l - s
 
//@function Stores one weekly sample, keeping the newest `n`.
//@param hist (array<float>) The store.
//@param v    (float) The sample.
//@param n    (int) Cap.
//@returns (bool) Always true.
pushWeek(array<float> hist, float v, int n) =>
    if not na(v)
        hist.push(v)
        while hist.size() > n
            hist.shift()
    true
 
//@function The highest and lowest net over the newest `n` weekly samples and the current net.
//@param hist (array<float>) Weekly net samples, oldest first.
//@param v    (float) The current net.
//@param n    (int) Weeks.
//@returns ([float, float]) High and low, na until two weeks are stored.
rangeOf(array<float> hist, float v, int n) =>
    float hi = na
    float lo = na
    int sz = hist.size()
    if sz >= 2 and not na(v)
        hi := v
        lo := v
        for i = math.max(0, sz - n) to sz - 1
            hi := math.max(hi, hist.get(i))
            lo := math.min(lo, hist.get(i))
    [hi, lo]
 
//@function COT Index: where `v` sits between the lookback's lowest and highest net, 0-100.
//@param hist (array<float>) Weekly net samples.
//@param v    (float) The current net.
//@param n    (int) Weeks.
//@returns (float) 0-100, or na until two weeks are stored.
cotIndex(array<float> hist, float v, int n) =>
    [hi, lo] = rangeOf(hist, v, n)
    na(hi) ? na : hi == lo ? 50.0 : (v - lo) / (hi - lo) * 100
 
//@function Signed volume-format string, e.g. "+12.3K".
//@param v (float) Value.
//@returns (string) Formatted.
fmtSigned(float v) =>
    na(v) ? "-" : (v >= 0 ? "+" : "") + str.tostring(v, format.volume)
 
//@function COT Index as a whole number, or "-" before two weeks are stored.
//@param v (float) Index value.
//@returns (string) Formatted.
fmtIdx(float v) =>
    na(v) ? "-" : str.tostring(v, "#")
//#endregion
 
 
 
//#region ———————————————————— Report, groups and data
 
 
var array<string> FIN_ROOTS = array.from(
     "NQ", "MNQ", "ES", "MES", "YM", "MYM", "RTY", "M2K", "EMD", "NKD",
     "ZN", "ZB", "ZF", "ZT", "TN", "UB", "SR3", "ZQ",
     "6E", "6J", "6B", "6A", "6C", "6S", "6N", "6M", "M6E", "M6A", "M6B", "DX",
     "VX", "BTC", "MBT", "ETH", "MET")
var array<string> COMM_ROOTS = array.from(
     "GC", "MGC", "SI", "SIL", "HG", "MHG", "PL", "PA",
     "CL", "MCL", "QM", "NG", "QG", "RB", "HO", "BZ",
     "ZC", "ZS", "ZW", "ZL", "ZM", "ZO", "KE", "LE", "HE", "GF", "CT", "KC", "SB", "CC", "OJ", "LBR")
 
var string ROOT   = rootOf(symInput)
var string REPORT = reportInput != "Auto" ? reportInput :
     FIN_ROOTS.includes(ROOT) ? "Financial" : COMM_ROOTS.includes(ROOT) ? "Disaggregated" : "Legacy"
 
var string M1 = REPORT == "Financial" ? "Dealer Positions"          : REPORT == "Disaggregated" ? "Producer Merchant Positions" : "Commercial Positions"
var string M2 = REPORT == "Financial" ? "Leveraged Funds Positions" : REPORT == "Disaggregated" ? "Managed Money Positions"     : "Noncommercial Positions"
var string M3 = REPORT == "Financial" ? "Asset Manager Positions"   : REPORT == "Disaggregated" ? "Swap Positions"              : "Nonreportable Positions"
var string N1 = REPORT == "Financial" ? "DEALERS"         : REPORT == "Disaggregated" ? "PRODUCERS"     : "COMMERCIALS"
var string N2 = REPORT == "Financial" ? "LEV FUNDS"       : REPORT == "Disaggregated" ? "MANAGED MONEY" : "LARGE SPECS"
var string N3 = REPORT == "Financial" ? "ASSET MANAGERS"  : REPORT == "Disaggregated" ? "SWAP DEALERS"  : "SMALL TRADERS"
 
var string CFTC = cot.getCFTCCode(symInput)
 
float net1 = netOf(REPORT, CFTC, M1)
float net2 = netOf(REPORT, CFTC, M2)
float net3 = netOf(REPORT, CFTC, M3)
float cotOi = cot.requestCommitmentOfTraders(REPORT, CFTC, optInput, "Open Interest", "No direction", "All")
 
// One sample per week for the index (the daily feed repeats the week's report).
var array<float> hist1 = array.new<float>()
var array<float> hist2 = array.new<float>()
var array<float> hist3 = array.new<float>()
var array<float> histOi = array.new<float>()
var array<int>   histT  = array.new<int>()
if timeframe.change("1W")
    if not na(net1[1])
        histT.push(time[1])
        while histT.size() > KEEP_WK
            histT.shift()
    pushWeek(hist1, net1[1], KEEP_WK)
    pushWeek(hist2, net2[1], KEEP_WK)
    pushWeek(hist3, net3[1], KEEP_WK)
    pushWeek(histOi, cotOi[1], KEEP_WK)
 
// ICT hedging program: the commercials' range midline over the lookback.
[rHi1, rLo1] = rangeOf(hist1, net1, idxWeeksInput)
float mid1 = na(rHi1) ? na : (rHi1 + rLo1) / 2
 
// Four weeks back (the newest stored sample is last week's).
float net1Ago = hist1.size() >= 4 ? hist1.get(hist1.size() - 4) : na
float oiAgo   = histOi.size() >= 4 ? histOi.get(histOi.size() - 4) : na
 
float idx1 = cotIndex(hist1, net1, idxWeeksInput)
float idx2 = cotIndex(hist2, net2, idxWeeksInput)
float idx3 = cotIndex(hist3, net3, idxWeeksInput)
 
// Daily open interest vs daily price change, both from the last CLOSED day (close[1] + lookahead_on).
var string FUT_TICKER = ticker.standard(symInput == "" ? syminfo.tickerid : symInput)
var string OI_TF      = timeframe.isintraday ? "1D" : timeframe.period
[oiNow, oiPrev] = request.security(FUT_TICKER + "_OI", OI_TF, [close[1], close[2]],
     lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
[pxNow, pxPrev] = request.security(FUT_TICKER, OI_TF, [close[1], close[2]],
     lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
 
// Week-on-week change: the net before the latest report.
var float prev1 = na
var float prev2 = na
var float prev3 = na
if net1 != net1[1] and not na(net1[1])
    prev1 := net1[1]
if net2 != net2[1] and not na(net2[1])
    prev2 := net2[1]
if net3 != net3[1] and not na(net3[1])
    prev3 := net3[1]
//#endregion
 
 
 
//#region ———————————————————— Plots
 
 
plot(show1Input ? (isIndex ? idx1 : net1) : na, "Commercials", col1Input, 1, plot.style_stepline)
plot(show2Input ? (isIndex ? idx2 : net2) : na, "Large Specs", col2Input, 1, plot.style_stepline)
plot(show3Input ? (isIndex ? idx3 : net3) : na, "Small Traders", col3Input, 1, plot.style_stepline)
plot(showMidInput and show1Input and not isIndex ? mid1 : na, "Commercial midline", INK, 2, plot.style_stepline)
 
hline(isIndex ? na : 0,                     "Zero",         GREY, hline.style_dotted)
hline(isIndex ? float(hiBandInput) : na,    "Extreme high", GREY, hline.style_dotted)
hline(isIndex ? 50 : na,                    "Midline",      GREY, hline.style_dotted)
hline(isIndex ? float(loBandInput) : na,    "Extreme low",  GREY, hline.style_dotted)
 
// The range box: the lookback's commercial range, split at the midline.
var box  bxUp  = na
var box  bxDn  = na
var line lnMid = na
if barstate.islast and showBoxInput and show1Input and not isIndex and not na(rHi1) and histT.size() > 0
    int t1 = histT.get(math.max(0, histT.size() - idxWeeksInput))
    int t2 = time
    if na(bxUp)
        bxUp  := box.new(t1, rHi1, t2, mid1, xloc = xloc.bar_time, border_color = color.new(BUY_BLUE, 100), bgcolor = color.new(BUY_BLUE, 88))
        bxDn  := box.new(t1, mid1, t2, rLo1, xloc = xloc.bar_time, border_color = color.new(COMM_RED, 100), bgcolor = color.new(COMM_RED, 88))
        lnMid := line.new(t1, mid1, t2, mid1, xloc = xloc.bar_time, color = GREY, width = 1)
    else
        box.set_lefttop(bxUp, t1, rHi1)
        box.set_rightbottom(bxUp, t2, mid1)
        box.set_lefttop(bxDn, t1, mid1)
        box.set_rightbottom(bxDn, t2, rLo1)
        line.set_xy1(lnMid, t1, mid1)
        line.set_xy2(lnMid, t2, mid1)
//#endregion
 
 
 
//#region ———————————————————— Table (§9 Intraday+ look)
 
 
var table dash          = na
var int   dashRowsDrawn = na
 
if showTableInput and barstate.islast
    string SZ = f_size(sizeInput)
 
    // The READ: smart money at a lookback extreme is the answer the pane exists for.
    bool   above   = net1 > mid1
    bool   crossed = not na(net1Ago) and not na(mid1) and (net1Ago > mid1) != above
    string read = na(mid1) ? "" : N1 + (above ? " BUYING" : " SELLING") + " · " + fmtIdx(idx1) + "% of range"
         + (crossed ? " · crossed midline <4 wks" : "")
 
    // ICT open interest confirmation over 4 weeks.
    float  oiChgPct  = na(oiAgo) or oiAgo == 0 ? na : (cotOi - oiAgo) / oiAgo * 100
    float  netChg4   = na(net1Ago) ? na : net1 - net1Ago
    string oiConfirm = na(oiChgPct) or na(netChg4) ? "" :
         oiChgPct <= -10 and netChg4 > 0 ? "BULLISH" :
         oiChgPct >= 10 and netChg4 < 0  ? "BEARISH" : "NONE"
 
    array<string> names = array.from("COT+", "INSTRUMENT")
    array<string> vals  = array.from(isIndex ? "INDEX" : "NET", ROOT)
    array<string> tips  = array.from(read, REPORT + (optInput ? " futures + options" : " futures") + ", CFTC code " + CFTC)
    // The same test over each window: BUY above that window's midline, SELL below. The box's window is marked.
    for w = 0 to WIN_WK.size() - 1
        int wk = WIN_WK.get(w)
        [wHi, wLo] = rangeOf(hist1, net1, wk)
        if not na(wHi) and hist1.size() >= wk
            float wMid = (wHi + wLo) / 2
            names.push(WIN_NM.get(w) + (wk == idxWeeksInput ? " ▪" : ""))
            vals.push(net1 > wMid ? "BUY" : "SELL")
            tips.push(N1 + " net " + str.tostring(net1, format.volume) + " vs the " + str.tostring(wk) + "-week midline "
                 + str.tostring(wMid, format.volume) + " (range " + str.tostring(wLo, format.volume) + " to " + str.tostring(wHi, format.volume)
                 + "). Above = BUY, below = SELL." + (wk == idxWeeksInput ? " This window is the range box." : ""))
    if oiConfirm != ""
        names.push("OI 4W")
        vals.push(oiConfirm)
        tips.push("COT open interest " + (oiChgPct >= 0 ? "+" : "") + str.tostring(oiChgPct, "#.#") + "% over 4 weeks: " + str.tostring(cotOi, format.volume) + " vs " + str.tostring(oiAgo, format.volume) + " four weeks ago; "
             + N1 + " net " + fmtSigned(netChg4) + " over the same weeks. ICT: OI down 10%+ with commercials adding = short covering (bullish); "
             + "OI up 10%+ with commercials selling = bearish.")
    if showOiInput and not na(oiNow) and not na(oiPrev) and not na(pxNow) and not na(pxPrev)
        float dOi = oiNow - oiPrev
        bool  pUp = pxNow >= pxPrev
        string oiRead = pUp ? (dOi >= 0 ? "new longs" : "short covering") : (dOi >= 0 ? "new shorts" : "long liquidation")
        names.push("OI DAILY")
        vals.push(str.tostring(oiNow, format.volume) + "  d " + fmtSigned(dOi) + "  " + oiRead)
        tips.push(FUT_TICKER + "_OI, last closed day. Price " + (pUp ? "up " : "down ") + str.tostring(pxNow - pxPrev, format.mintick)
             + ". New longs / new shorts = fresh money behind the move; short covering / long liquidation = the move is closing positions, weaker.")
    if show1Input and (show2Input or show3Input)
        names.push(N1)
        vals.push(str.tostring(net1, format.volume))
        tips.push(M1 + ": long - short. Week change " + fmtSigned(net1 - prev1) + ", COT Index " + fmtIdx(idx1) + ".")
    if show2Input
        names.push(N2)
        vals.push(str.tostring(net2, format.volume))
        tips.push(M2 + ": long - short. Week change " + fmtSigned(net2 - prev2) + ", COT Index " + fmtIdx(idx2) + ".")
    if show3Input
        names.push(N3)
        vals.push(str.tostring(net3, format.volume))
        tips.push(M3 + ": long - short. Week change " + fmtSigned(net3 - prev3) + ", COT Index " + fmtIdx(idx3) + ".")
 
    int wantRows = names.size()
    if na(dash) or dashRowsDrawn != wantRows
        if not na(dash)
            table.delete(dash)
        dash := table.new(tablePosInput, 2, wantRows, frame_color = INK, frame_width = 1, border_width = 0)
        dashRowsDrawn := wantRows
    for i = 0 to wantRows - 1
        table.cell(dash, 0, i, names.get(i), text_color = INK, text_size = SZ, text_halign = text.align_left,
             text_font_family = font.family_monospace)
        table.cell(dash, 1, i, vals.get(i), text_color = INK, text_size = SZ, text_halign = text.align_left,
             text_font_family = font.family_monospace, tooltip = tips.get(i))
//#endregion

← 返回列表