Indicator · Pine Script v6 · Own pane

COT Financial

by ivansoft· code credited to TradingView

An indicator in a separate pane that plots Commitment of Traders financial report metrics for the chart symbol, including open interest and dealer, asset manager, leveraged funds and other reportable positions.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code216
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago1 Mar 2025

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

216 lines of Pine Script v6 from edu_std/cot_financial.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

cot_financial.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView

//@version=6
indicator("Commitment of Traders: Financial Metrics", "COT Financial", format = format.volume)

// "Commitment of Traders: Financial Metrics"
// v4, 2024.11.26

// This code was written using the recommendations from the Pine Script™ User Manual's Style guide:
//    https://www.tradingview.com/pine-script-docs/writing/style-guide/



// +-----------------------------------+------------------------+
// | Financial (COT3) Metric Names     |       Directions       |
// +-----------------------------------+------------------------+
// | Open Interest                     | No direction           |
// | Dealer Positions                  | Long, Short, Spreading |
// | Asset Manager Positions           | Long, Short, Spreading |
// | Leveraged Funds Positions         | Long, Short, Spreading |
// | Other Reportable Positions        | Long, Short, Spreading |
// | Total Reportable Positions        | Long, Short            |
// | Nonreportable Positions           | Long, Short            |
// | Traders Total                     | No direction           |
// | Traders Dealer                    | Long, Short, Spreading |
// | Traders Asset Manager             | Long, Short, Spreading |
// | Traders Leveraged Funds           | Long, Short, Spreading |
// | Traders Other Reportable          | Long, Short, Spreading |
// | Traders Total Reportable          | Long, Short            |
// | Concentration Gross LE 4 TDR      | Long, Short            |
// | Concentration Gross LE 8 TDR      | Long, Short            |
// | Concentration Net LE 4 TDR        | Long, Short            |
// | Concentration Net LE 8 TDR        | Long, Short            |
// +-----------------------------------+------------------------+



import TradingView/LibraryCOT/4 as cot



//#region ———————————————————— Constants and inputs


// Allowed directions
string ND  = " [ND]"
string LS  = " [L|Sh]"
string LSS = " [L|Sh|Sp]"

// Metric types 
string IO01 = "Futures"
string IO02 = "Options"
string IO03 = "Futures + Options"

// Metric names
string MB01 = "Open Interest"
string MB02 = "Dealer Positions"
string MB03 = "Asset Manager Positions"
string MB04 = "Leveraged Funds Positions"
string MB05 = "Other Reportable Positions"
string MB06 = "Total Reportable Positions"
string MB07 = "Nonreportable Positions"
string MB08 = "Traders Total"
string MB09 = "Traders Dealer"
string MB10 = "Traders Asset Manager"
string MB11 = "Traders Leveraged Funds"
string MB12 = "Traders Other Reportable"
string MB13 = "Traders Total Reportable"
string MB14 = "Concentration Gross LE 4 TDR"
string MB15 = "Concentration Gross LE 8 TDR"
string MB16 = "Concentration Net LE 4 TDR"
string MB17 = "Concentration Net LE 8 TDR"

// "Metric" input options
string M01 = MB01 + ND
string M02 = MB02 + LSS
string M03 = MB03 + LSS
string M04 = MB04 + LSS
string M05 = MB05 + LSS
string M06 = MB06 + LS
string M07 = MB07 + LS
string M08 = MB08 + ND
string M09 = MB09 + LSS
string M10 = MB10 + LSS
string M11 = MB11 + LSS
string M12 = MB12 + LSS
string M13 = MB13 + LS
string M14 = MB14 + LS
string M15 = MB15 + LS
string M16 = MB16 + LS
string M17 = MB17 + LS

// Tooltips
string TT_METRIC = "Each metric option shows the allowed directions in square brackets:
     \n [ND] 🠆 No direction\n [L] 🠆 Long\n [Sh] 🠆 Short\n [Sp] 🠆 Spreading"
string TT_DIR = "The direction must apply to the selected metric. The above field's dropdown menu shows
     which direction options are valid for each metric." 
string TT_MODE = "Determines the type of information the indicator uses from the chart's symbol to request COT data:\n
     • 'Root' uses the root prefix of a futures symbol (e.g., 'ES' for 'ESH2020').\n
     • 'Base currency' uses the first currency from a currency pair (e.g., 'EUR' for 'EURUSD').\n
     • 'Currency' uses the currency of the symbol's quoted values (e.g., 'JPY' for 'TSE:9984' or 'USDJPY').\n
     • 'Auto' tries all the above modes in order.\n
     If no COT data is available for the specified mode, a runtime error occurs." 
string TT_OPTIONS = "Determines whether the data includes information from futures, options, or both."
string TT_OVERRIDE = "This field allows manual specification of the CFTC COT code. When the field is not empty, the
     indicator uses this code instead of determining the code based on the chart symbol's root or currency information.
     For example, if the field's value is '001602', the indicator requests wheat futures data, regardless of the
     current chart."

// Inputs.
string metricNameInput      = input.string(M01,            "Metric",             options = [M01, M02, M03, M04, M05, M06, M07, M08, M09, M10, M11, M12, M13, M14, M15, M16, M17], tooltip = TT_METRIC)
string metricDirectionInput = input.string("No direction", "Direction",          options = ["No direction", "Long", "Short", "Spreading"], tooltip = TT_DIR)
string selectionModeInput   = input.string("Auto",         "COT selection mode", options = ["Auto", "Root", "Base currency", "Currency"], tooltip = TT_MODE)
string includeOptionsInput  = input.string(IO01,           "Futures/Options",    options = [IO01, IO02, IO03], tooltip = TT_OPTIONS)
string userCFTCCodeInput    = input.string("",             "CFTC Code",          tooltip = TT_OVERRIDE)
//#endregion



//#region ———————————————————— Functions


// @function                Retrieves the metric name associated with the user-specified "Metric" option. This function 
//                          maps the "Metric" options to the corresponding internal identifiers the script uses.
// @param userMetricName    (string) The user-selected "Metric" option. Its value should be one of the predefined 
//                          "Metric" options (`M01` to `M17`), which contains the metric name (e.g, "Open Interest") 
//                          and abbreviations for the allowed direction choices (e.g., "[ND]" for No direction, 
//                          "[L|Sh]" for Long or Short).
// @returns                 (string) The internal identifier the script uses to request the appropriate metric data. 
//                          The value corresponds to one of the `MB*` constants, or it is an empty "string" if the 
//                          `userMetricName` is not an available "Metric" option. 
getMetricName(simple string userMetricName) =>
    result = switch userMetricName
        M01 => MB01
        M02 => MB02
        M03 => MB03
        M04 => MB04
        M05 => MB05
        M06 => MB06
        M07 => MB07
        M08 => MB08
        M09 => MB09
        M10 => MB10
        M11 => MB11
        M12 => MB12
        M13 => MB13
        M14 => MB14
        M15 => MB15
        M16 => MB16
        M17 => MB17
        => ""
//#endregion



//#region ———————————————————— Calculations


// @variable The user-specified CFTC code if the "CFTC Code" input is not empty, a chart-based CFTC code otherwise.
var string cftcCode = userCFTCCodeInput != "" ? userCFTCCodeInput : cot.convertRootToCOTCode(selectionModeInput)
// @variable The "string" identifier for requesting Financial metrics. 
string typeCOT = "Financial"
// @variable The "string" identifier for the metric type.
string metricType = "All"
// @variable The "string" identifier for the metric name.
var string metricName = getMetricName(metricNameInput)

// @variable The COT ticker ID that specifies futures-only information. 
var string futuresOnlyTicker = cot.COTTickerid(
     typeCOT, cftcCode, false, metricName, metricDirectionInput, metricType
 )
// @variable The COT ticker ID that specifies futures and options information. 
var string futuresWithOptionsTicker = cot.COTTickerid(
     typeCOT, cftcCode, true, metricName, metricDirectionInput, metricType
 )

// @variable The requested Financial metric for futures data.
float futuresOnly = cot.requestCommitmentOfTraders(
     typeCOT, cftcCode, false, metricName, metricDirectionInput, metricType
 )
// @variable The requested Financial metric for futures and options data.
float futuresWithOptions = cot.requestCommitmentOfTraders(
     typeCOT, cftcCode, true, metricName, metricDirectionInput, metricType
 ) 

// @variable COT series for futures, options, or futures and options data, depending on the `includeOptionsInput`.
float COTSeries = switch includeOptionsInput
    IO01 => futuresOnly
    IO02 => futuresWithOptions - futuresOnly
    IO03 => futuresWithOptions
    => na
//#endregion



//#region ———————————————————— Display


// Plot the `COTSeries` as a step line with diamonds.
plot(COTSeries, "COT", style = plot.style_stepline_diamond)

// @variable A `table` displaying COT ticker ID information in the bottom-right corner. 
var table symbolDisplay = table.new(position.bottom_right, 1, 1)
// Populate the `symbolDisplay` on the first bar. 
if barstate.isfirst
    color  TEXT_COLOR = color.white
    color  BG_COLOR   = color.new(color.blue, 50)
    string dataCOT    = userCFTCCodeInput != "" ? userCFTCCodeInput : cot.convertRootToCOTCode(selectionModeInput, false)
    string tickerID   = switch includeOptionsInput
        IO01 => futuresOnlyTicker
        IO02 => futuresWithOptionsTicker + "-" + futuresOnlyTicker
        IO03 => futuresWithOptionsTicker
    string txt = str.format("COT data for {0} {1}\nRequested ticker: {2}", dataCOT, includeOptionsInput, tickerID)
    table.cell(symbolDisplay, 0, 0, txt, text_halign = text.align_left, text_color = TEXT_COLOR, bgcolor = BG_COLOR)
//#endregion

Overview

Settings pick the metric, the direction, a selection mode that decides how the symbol is mapped to COT data, futures or options data, and an optional CFTC code override. It uses the LibraryCOT library and needs COT data to exist for the symbol.

Details

Published by

ivansoft on GitHub

Code credit

TradingView, as written in the script's header

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Markets

Forex, Indices

Timeframes

H4 and above

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.

Topics

pinescripttradingvew

Settings

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

SettingTypeDefaultVariable
MetricstringM01metricNameInput
DirectionstringNo directionmetricDirectionInput
COT selection modestringAutoselectionModeInput
Futures/OptionsstringIO01includeOptionsInput
CFTC CodestringuserCFTCCodeInput
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

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 11 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
549 stars

Range Volume Change compares volume inside a chosen session window with the same window on the previous day and plots that change as a percentage. It accumulates volume during the window and, when enabled, volume outside it, drawing growing columns in a separa

Indicator v5 VolumeSessions & time Repaints
Updated 10 months ago · None stated GitHub repository of Range Volume Change

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

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