本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Rocinante7
//@version=6
indicator("COT Quantitative Trading Framework", shorttitle="COT Engine", overlay=true, max_labels_count=500, max_lines_count=500)
// =============================================================================
// COT Engine v2
// Data comes through TradingView's official COT library, so no ticker strings
// are hand-built (the old "CFTC:..._F_L_ALL" symbols do not exist).
// Commodities -> Disaggregated report: Managed Money (momentum) vs Producer/Merchant (value)
// Financials -> TFF (Financial) report: Leveraged Funds (momentum) vs Asset Managers (value)
// =============================================================================
import TradingView/LibraryCOT/6 as cot
// =============================================================================
// 1. INPUTS
// =============================================================================
string G_ASSET = "1. CFTC Asset & Data Selection"
enum AssetPreset
preset_auto = "Auto-Detect"
gold = "Gold (GC / XAUUSD)"
silver = "Silver (SI / XAGUSD)"
copper = "Copper (HG)"
oil = "Crude Oil (CL / WTI)"
natgas = "Natural Gas (NG)"
euro = "Euro FX (6E / EURUSD)"
pound = "British Pound (6B)"
yen = "Japanese Yen (6J)"
aud = "Australian Dollar (6A)"
cad = "Canadian Dollar (6C)"
chf = "Swiss Franc (6S)"
sp500 = "S&P 500 (ES / SPX)"
nasdaq = "Nasdaq 100 (NQ / NDX)"
dow = "Dow Jones (YM / US30)"
bitcoin = "Bitcoin (BTC)"
ethereum = "Ethereum (ETH)"
notes10y = "10Y T-Notes (ZN)"
bonds30y = "30Y T-Bonds (ZB)"
corn = "Corn (ZC)"
wheat = "Wheat (ZW)"
soybeans = "Soybeans (ZS)"
custom = "Custom Input"
AssetPreset asset_choice = input.enum(AssetPreset.preset_auto, "Asset Preset", group=G_ASSET, tooltip="Auto-Detect maps the chart symbol (XAUUSD, EURUSD, USOIL, US500, BTCUSD ...) to the matching CFTC contract.")
bool use_options = input.bool(true, "Futures + Options Combined", group=G_ASSET, tooltip="Combined (delta-adjusted) is preferred. Turn off for futures-only data.")
string custom_code = input.string("088691", "Custom CFTC Code (6 chars)", group=G_ASSET, tooltip="Only used with the Custom preset.")
string custom_report = input.string("Disaggregated", "Custom Report Type", options=["Disaggregated", "Financial"], group=G_ASSET, tooltip="Only used with the Custom preset. Disaggregated = commodities, Financial = TFF.")
string G_NORM = "2. Normalization & Parameters"
int lookback_cot_index = input.int(156, "COT Index Lookback (Weeks)", minval=26, maxval=260, group=G_NORM)
int lookback_zscore = input.int(52, "Z-Score Lookback (Weeks)", minval=10, maxval=156, group=G_NORM)
float z_threshold = input.float(2.0, "Z-Score Extreme Threshold (+/-)", minval=1.0, maxval=3.5, step=0.1, group=G_NORM)
float cot_upper_thresh = input.float(95.0, "COT Index Overbought Bound", minval=80.0, maxval=99.0, group=G_NORM)
float cot_lower_thresh = input.float(5.0, "COT Index Oversold Bound", minval=1.0, maxval=20.0, group=G_NORM)
string G_EXEC = "3. Signal & Execution Rules"
bool enable_div = input.bool(true, "Enable Price-Positioning Divergence", group=G_EXEC)
bool enable_flips = input.bool(true, "Enable Structural Flip Signals", group=G_EXEC)
float flip_oi_pct = input.float(5.0, "Flip: Min Weekly OI Expansion (%)", minval=0.0, maxval=50.0, step=0.5, group=G_EXEC)
string trigger_mode = input.string("Either", "Price Trigger (after COT release)", options=["Weekly Break", "EMA Cross", "Either", "None"], group=G_EXEC, tooltip="COT data is Tuesday positioning published Friday. Use a price trigger so entries are not based on stale data alone.")
int ema_len = input.int(20, "Trigger EMA Length", minval=2, maxval=200, group=G_EXEC)
bool req_oi_confirm = input.bool(true, "Require OI Contraction on Extreme Signals", group=G_EXEC, tooltip="Reversal off an extreme should come with falling open interest (forced liquidation).")
int div_lookback_bars = input.int(20, "Divergence Lookback Window (Bars)", minval=5, maxval=100, group=G_EXEC)
string G_UI = "4. Dashboard & Display"
bool show_table = input.bool(true, "Show Dashboard", group=G_UI)
string table_pos = input.string(position.top_right, "Dashboard Position", options=[position.top_right, position.bottom_right, position.top_left, position.bottom_left], group=G_UI)
bool show_bg = input.bool(true, "Highlight Extreme Regime Background", group=G_UI)
bool show_ema = input.bool(true, "Plot Trigger EMA", group=G_UI)
// =============================================================================
// 2. ASSET DETECTION & CFTC CODE MAPPING
// =============================================================================
f_detect_asset_from_chart() =>
string sym = str.upper(syminfo.ticker)
string root = str.upper(syminfo.root)
AssetPreset detected = AssetPreset.gold
if str.contains(sym, "XAU") or str.contains(sym, "GOLD") or root == "GC" or root == "MGC"
detected := AssetPreset.gold
else if str.contains(sym, "XAG") or str.contains(sym, "SILVER") or root == "SI"
detected := AssetPreset.silver
else if str.contains(sym, "COPPER") or root == "HG"
detected := AssetPreset.copper
else if str.contains(sym, "USOIL") or str.contains(sym, "WTI") or str.contains(sym, "OIL") or root == "CL"
detected := AssetPreset.oil
else if str.contains(sym, "NGAS") or str.contains(sym, "NATGAS") or root == "NG"
detected := AssetPreset.natgas
else if str.contains(sym, "EUR") or root == "6E"
detected := AssetPreset.euro
else if str.contains(sym, "GBP") or root == "6B"
detected := AssetPreset.pound
else if str.contains(sym, "JPY") or root == "6J"
detected := AssetPreset.yen
else if str.contains(sym, "AUD") or root == "6A"
detected := AssetPreset.aud
else if str.contains(sym, "CAD") or root == "6C"
detected := AssetPreset.cad
else if str.contains(sym, "CHF") or root == "6S"
detected := AssetPreset.chf
else if str.contains(sym, "SPX") or str.contains(sym, "US500") or str.contains(sym, "SP500") or root == "ES"
detected := AssetPreset.sp500
else if str.contains(sym, "NDX") or str.contains(sym, "US100") or str.contains(sym, "NAS100") or root == "NQ"
detected := AssetPreset.nasdaq
else if str.contains(sym, "US30Y") or root == "ZB"
detected := AssetPreset.bonds30y
else if str.contains(sym, "DJI") or str.contains(sym, "US30") or root == "YM"
detected := AssetPreset.dow
else if str.contains(sym, "BTC") or root == "BTC"
detected := AssetPreset.bitcoin
else if str.contains(sym, "ETH") or root == "ETH"
detected := AssetPreset.ethereum
else if str.contains(sym, "US10Y") or root == "ZN"
detected := AssetPreset.notes10y
else if str.contains(sym, "CORN") or root == "ZC"
detected := AssetPreset.corn
else if str.contains(sym, "WHEAT") or root == "ZW"
detected := AssetPreset.wheat
else if str.contains(sym, "SOY") or root == "ZS"
detected := AssetPreset.soybeans
detected
f_cftc_code(AssetPreset p) =>
string code = custom_code
switch p
AssetPreset.gold => code := "088691"
AssetPreset.silver => code := "084691"
AssetPreset.copper => code := "085692"
AssetPreset.oil => code := "067651"
AssetPreset.natgas => code := "023651"
AssetPreset.euro => code := "099741"
AssetPreset.pound => code := "096742"
AssetPreset.yen => code := "097741"
AssetPreset.aud => code := "232741"
AssetPreset.cad => code := "090741"
AssetPreset.chf => code := "092741"
AssetPreset.sp500 => code := "13874A"
AssetPreset.nasdaq => code := "209742"
AssetPreset.dow => code := "124603"
AssetPreset.bitcoin => code := "133741"
AssetPreset.ethereum => code := "146741"
AssetPreset.notes10y => code := "043602"
AssetPreset.bonds30y => code := "020601"
AssetPreset.corn => code := "002602"
AssetPreset.wheat => code := "001602"
AssetPreset.soybeans => code := "005602"
=> code := custom_code
code
f_report_type(AssetPreset p) =>
string rep = "Financial"
switch p
AssetPreset.gold => rep := "Disaggregated"
AssetPreset.silver => rep := "Disaggregated"
AssetPreset.copper => rep := "Disaggregated"
AssetPreset.oil => rep := "Disaggregated"
AssetPreset.natgas => rep := "Disaggregated"
AssetPreset.corn => rep := "Disaggregated"
AssetPreset.wheat => rep := "Disaggregated"
AssetPreset.soybeans => rep := "Disaggregated"
AssetPreset.custom => rep := custom_report
=> rep := "Financial"
rep
AssetPreset resolved_preset = asset_choice == AssetPreset.preset_auto ? f_detect_asset_from_chart() : asset_choice
string cftc_code = f_cftc_code(resolved_preset)
string report_type = f_report_type(resolved_preset)
bool is_disagg = report_type == "Disaggregated"
string spec_name = is_disagg ? "Managed Money Positions" : "Leveraged Funds Positions"
string comm_name = is_disagg ? "Producer Merchant Positions" : "Asset Manager Positions"
string spec_label = is_disagg ? "Managed Money" : "Leveraged Funds"
string comm_label = is_disagg ? "Producer/Merchant" : "Asset Managers"
// =============================================================================
// 3. COT DATA & NORMALIZATION ENGINE
// =============================================================================
float spec_long_w = cot.requestCommitmentOfTraders(report_type, cftc_code, use_options, spec_name, "Long", "All")
float spec_short_w = cot.requestCommitmentOfTraders(report_type, cftc_code, use_options, spec_name, "Short", "All")
float comm_long_w = cot.requestCommitmentOfTraders(report_type, cftc_code, use_options, comm_name, "Long", "All")
float comm_short_w = cot.requestCommitmentOfTraders(report_type, cftc_code, use_options, comm_name, "Short", "All")
float oi_w = cot.requestCommitmentOfTraders(report_type, cftc_code, use_options, "Open Interest", "No direction", "All")
float net_spec = spec_long_w - spec_short_w
float net_comm = comm_long_w - comm_short_w
// Weekly history buffers: one entry per new COT release, so lookbacks are in WEEKS on any chart timeframe.
var array<float> spec_hist = array.new<float>()
var array<float> comm_hist = array.new<float>()
var float oi_last = na
var float oi_prev = na
bool new_cot = not na(net_spec) and not na(net_comm) and not na(oi_w) and (net_spec != net_spec[1] or net_comm != net_comm[1] or oi_w != oi_w[1])
if new_cot
array.push(spec_hist, net_spec)
array.push(comm_hist, net_comm)
oi_prev := oi_last
oi_last := oi_w
if array.size(spec_hist) > 400
array.shift(spec_hist)
array.shift(comm_hist)
f_cot_index(array<float> hist, float cur, int weeks) =>
int sz = array.size(hist)
int cnt = math.min(sz, weeks)
float result = 50.0
if not na(cur) and cnt >= 2
array<float> win = array.slice(hist, sz - cnt, sz)
float lo = math.min(array.min(win), cur)
float hi = math.max(array.max(win), cur)
result := hi != lo ? (cur - lo) / (hi - lo) * 100.0 : 50.0
result
f_zscore(array<float> hist, float cur, int weeks) =>
int sz = array.size(hist)
int cnt = math.min(sz, weeks)
float result = 0.0
if not na(cur) and cnt >= 2
array<float> win = array.slice(hist, sz - cnt, sz)
float mean_net = array.avg(win)
float stdev_net = array.stdev(win)
result := stdev_net != 0 ? (cur - mean_net) / stdev_net : 0.0
result
float spec_cot_index = f_cot_index(spec_hist, net_spec, lookback_cot_index)
float comm_cot_index = f_cot_index(comm_hist, net_comm, lookback_cot_index)
float spec_zscore = f_zscore(spec_hist, net_spec, lookback_zscore)
float comm_zscore = f_zscore(comm_hist, net_comm, lookback_zscore)
float net_spec_pct_oi = not na(oi_w) and oi_w != 0 ? (net_spec / oi_w) * 100.0 : 0.0
// =============================================================================
// 4. OPEN INTEREST KINETICS
// =============================================================================
float oi_chg_abs = nz(oi_last - oi_prev)
float oi_chg_pct = not na(oi_prev) and oi_prev != 0 ? (oi_last - oi_prev) / oi_prev * 100.0 : 0.0
float price_change_w = request.security(syminfo.tickerid, "W", close - close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
string oi_kinetic_regime = "Neutral"
color oi_regime_color = color.gray
if price_change_w > 0 and oi_chg_abs > 0
oi_kinetic_regime := "Bullish Accumulation"
oi_regime_color := color.green
else if price_change_w < 0 and oi_chg_abs > 0
oi_kinetic_regime := "Bearish Accumulation"
oi_regime_color := color.red
else if price_change_w > 0 and oi_chg_abs < 0
oi_kinetic_regime := "Short Covering Squeeze"
oi_regime_color := color.orange
else if price_change_w < 0 and oi_chg_abs < 0
oi_kinetic_regime := "Long Liquidation"
oi_regime_color := color.maroon
// =============================================================================
// 5. SETUPS & TRIGGERS
// =============================================================================
// Setup A: Dual-Extreme Trend Exhaustion
bool setup_bearish_extreme = (spec_cot_index >= cot_upper_thresh and comm_cot_index <= cot_lower_thresh) or (spec_zscore >= z_threshold and comm_zscore <= -z_threshold)
bool setup_bullish_extreme = (spec_cot_index <= cot_lower_thresh and comm_cot_index >= cot_upper_thresh) or (spec_zscore <= -z_threshold and comm_zscore >= z_threshold)
// Setup B: Price vs Positioning Divergence
float hh_level = ta.highest(high, div_lookback_bars)
float ll_level = ta.lowest(low, div_lookback_bars)
float prev_hh = nz(hh_level[1], high)
float prev_ll = nz(ll_level[1], low)
bool price_hh = high > prev_hh
bool price_ll = low < prev_ll
float zs_at_prev_high = ta.valuewhen(high == hh_level, spec_zscore, 1)
float zs_at_prev_low = ta.valuewhen(low == ll_level, spec_zscore, 1)
bool setup_bearish_div = enable_div and price_hh and spec_zscore < zs_at_prev_high and spec_zscore > 1.0
bool setup_bullish_div = enable_div and price_ll and spec_zscore > zs_at_prev_low and spec_zscore < -1.0
// Setup C: Structural Flip with OI expansion
bool net_spec_cross_up = ta.crossover(net_spec, 0)
bool net_spec_cross_down = ta.crossunder(net_spec, 0)
bool spec_flip_bullish = enable_flips and net_spec_cross_up and oi_chg_pct > flip_oi_pct
bool spec_flip_bearish = enable_flips and net_spec_cross_down and oi_chg_pct > flip_oi_pct
// Price triggers (handle the Tuesday -> Friday reporting lag)
float prev_week_high = request.security(syminfo.tickerid, "W", high[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
float prev_week_low = request.security(syminfo.tickerid, "W", low[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
float ema_trigger = ta.ema(close, ema_len)
bool ema_cross_dn = ta.crossunder(close, ema_trigger)
bool ema_cross_up = ta.crossover(close, ema_trigger)
bool ema_below = close < ema_trigger
bool ema_above = close > ema_trigger
bool wk_break_dn = close < prev_week_low
bool wk_break_up = close > prev_week_high
bool valid_short_trigger = trigger_mode == "Weekly Break" ? wk_break_dn : trigger_mode == "EMA Cross" ? ema_below : trigger_mode == "Either" ? (wk_break_dn or ema_below) : true
bool valid_long_trigger = trigger_mode == "Weekly Break" ? wk_break_up : trigger_mode == "EMA Cross" ? ema_above : trigger_mode == "Either" ? (wk_break_up or ema_above) : true
bool oi_ok = req_oi_confirm ? oi_chg_abs < 0 : true
bool trigger_short_extreme = setup_bearish_extreme and valid_short_trigger and oi_ok
bool trigger_long_extreme = setup_bullish_extreme and valid_long_trigger and oi_ok
bool trigger_short_div = setup_bearish_div and valid_short_trigger
bool trigger_long_div = setup_bullish_div and valid_long_trigger
bool short_signal = trigger_short_extreme and not trigger_short_extreme[1]
bool long_signal = trigger_long_extreme and not trigger_long_extreme[1]
bool short_div_signal = trigger_short_div and not trigger_short_div[1]
bool long_div_signal = trigger_long_div and not trigger_long_div[1]
// Invalidation: new extreme in the trend direction on EXPANDING open interest
bool inval_bear = setup_bearish_extreme and high > prev_week_high and oi_chg_abs > 0 and not (setup_bearish_extreme[1] and high[1] > prev_week_high[1] and oi_chg_abs[1] > 0)
bool inval_bull = setup_bullish_extreme and low < prev_week_low and oi_chg_abs > 0 and not (setup_bullish_extreme[1] and low[1] < prev_week_low[1] and oi_chg_abs[1] > 0)
// =============================================================================
// 6. VISUALS
// =============================================================================
color bg_color = color.new(color.white, 100)
if show_bg
if setup_bearish_extreme
bg_color := color.new(color.red, 88)
else if setup_bullish_extreme
bg_color := color.new(color.green, 88)
bgcolor(bg_color)
plot(show_ema ? ema_trigger : na, "Trigger EMA", color=color.new(color.aqua, 30), linewidth=1)
plotshape(short_signal, title="Bearish Extreme Trigger", style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white, text="COT BEAR", size=size.small)
plotshape(long_signal, title="Bullish Extreme Trigger", style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white, text="COT BULL", size=size.small)
plotshape(short_div_signal, title="Bearish Divergence", style=shape.triangledown, location=location.abovebar, color=color.orange, textcolor=color.orange, text="DIV", size=size.tiny)
plotshape(long_div_signal, title="Bullish Divergence", style=shape.triangleup, location=location.belowbar, color=color.teal, textcolor=color.teal, text="DIV", size=size.tiny)
plotshape(spec_flip_bullish, title="Speculator Bullish Flip", style=shape.diamond, location=location.belowbar, color=color.lime, size=size.tiny)
plotshape(spec_flip_bearish, title="Speculator Bearish Flip", style=shape.diamond, location=location.abovebar, color=color.maroon, size=size.tiny)
plotshape(inval_bear, title="Bear Setup Invalidated", style=shape.xcross, location=location.abovebar, color=color.yellow, size=size.tiny)
plotshape(inval_bull, title="Bull Setup Invalidated", style=shape.xcross, location=location.belowbar, color=color.yellow, size=size.tiny)
alertcondition(short_signal, "COT Bear Extreme", "COT bearish extreme trigger")
alertcondition(long_signal, "COT Bull Extreme", "COT bullish extreme trigger")
alertcondition(short_div_signal, "COT Bear Divergence", "COT bearish divergence trigger")
alertcondition(long_div_signal, "COT Bull Divergence", "COT bullish divergence trigger")
alertcondition(inval_bear, "COT Bear Invalidated", "Bearish COT setup invalidated on expanding OI")
alertcondition(inval_bull, "COT Bull Invalidated", "Bullish COT setup invalidated on expanding OI")
// =============================================================================
// 7. DASHBOARD
// =============================================================================
var table cot_dash = table.new(table_pos, 2, 9, bgcolor=color.new(color.black, 15), border_color=color.gray, border_width=1)
if show_table and barstate.islast
table.cell(cot_dash, 0, 0, "COT QUANT ENGINE", bgcolor=color.navy, text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 0, str.tostring(resolved_preset) + " | " + report_type, bgcolor=color.navy, text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 1, spec_label + " COT Index (" + str.tostring(lookback_cot_index) + "w)", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 1, str.tostring(spec_cot_index, "#.0") + "%",
bgcolor=spec_cot_index >= cot_upper_thresh ? color.red : spec_cot_index <= cot_lower_thresh ? color.green : color.gray,
text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 2, spec_label + " Z-Score (" + str.tostring(lookback_zscore) + "w)", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 2, str.tostring(spec_zscore, "#.00") + " σ",
bgcolor=spec_zscore >= z_threshold ? color.red : spec_zscore <= -z_threshold ? color.green : color.gray,
text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 3, comm_label + " COT Index (" + str.tostring(lookback_cot_index) + "w)", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 3, str.tostring(comm_cot_index, "#.0") + "%",
bgcolor=comm_cot_index <= cot_lower_thresh ? color.red : comm_cot_index >= cot_upper_thresh ? color.green : color.gray,
text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 4, comm_label + " Z-Score (" + str.tostring(lookback_zscore) + "w)", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 4, str.tostring(comm_zscore, "#.00") + " σ",
bgcolor=comm_zscore <= -z_threshold ? color.red : comm_zscore >= z_threshold ? color.green : color.gray,
text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 5, "Spec Net % Open Interest", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 5, str.tostring(net_spec_pct_oi, "#.0") + "%", bgcolor=color.gray, text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 6, "OI Change (w/w)", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 6, str.tostring(oi_chg_pct, "#.0") + "%", bgcolor=oi_chg_abs >= 0 ? color.green : color.maroon, text_color=color.white, text_size=size.small)
table.cell(cot_dash, 0, 7, "Open Interest Regime", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 7, oi_kinetic_regime, bgcolor=oi_regime_color, text_color=color.white, text_size=size.small)
string macro_state = "NEUTRAL"
color state_bg = color.gray
if setup_bearish_extreme
macro_state := "BEARISH EXHAUSTION"
state_bg := color.red
else if setup_bullish_extreme
macro_state := "BULLISH EXHAUSTION"
state_bg := color.green
else if setup_bearish_div
macro_state := "BEAR DIVERGENCE"
state_bg := color.orange
else if setup_bullish_div
macro_state := "BULL DIVERGENCE"
state_bg := color.teal
table.cell(cot_dash, 0, 8, "Macro Regime Setup", text_color=color.white, text_size=size.small)
table.cell(cot_dash, 1, 8, macro_state, bgcolor=state_bg, text_color=color.white, text_size=size.small)