Indicator · Pine Script v6 · Own pane

COT Legacy

by ivansoft· code credited to TradingView

An indicator in a separate pane that plots Commitment of Traders legacy report metrics for the chart symbol, such as open interest, noncommercial, commercial and nonreportable positions and trader counts.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code201
Settings6inputs
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

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

cot_legacy.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: Legacy Metrics", "COT Legacy", format = format.volume)

// "Commitment of Traders: Legacy 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/



// +-----------------------------------+------------------------+
// |  Legacy (COT) Metric Names        |       Directions       |
// +-----------------------------------+------------------------+
// | Open Interest                     | No direction           |
// | Noncommercial Positions           | Long, Short, Spreading |
// | Commercial Positions              | Long, Short            |
// | Total Reportable Positions        | Long, Short            |
// | Nonreportable Positions           | Long, Short            |
// | Traders Total                     | No direction           |
// | Traders Noncommercial             | Long, Short, Spreading |
// | Traders Commercial                | Long, Short            |
// | Traders Total Reportable          | Long, Short            |
// | Concentration Gross LT 4 TDR      | Long, Short            |
// | Concentration Gross LT 8 TDR      | Long, Short            |
// | Concentration Net LT 4 TDR        | Long, Short            |
// | Concentration Net LT 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 information types
string IO01 = "Futures"
string IO02 = "Options"
string IO03 = "Futures + Options"

// Metric names
string MB01 = "Open Interest"
string MB02 = "Noncommercial Positions"
string MB03 = "Commercial Positions"
string MB04 = "Total Reportable Positions"
string MB05 = "Nonreportable Positions"
string MB06 = "Traders Total"
string MB07 = "Traders Noncommercial"
string MB08 = "Traders Commercial"
string MB09 = "Traders Total Reportable"
string MB10 = "Concentration Gross LT 4 TDR"
string MB11 = "Concentration Gross LT 8 TDR"
string MB12 = "Concentration Net LT 4 TDR"
string MB13 = "Concentration Net LT 8 TDR"

// "Metric" input options
string M01 = MB01 + ND
string M02 = MB02 + LSS
string M03 = MB03 + LS
string M04 = MB04 + LS
string M05 = MB05 + LS
string M06 = MB06 + ND
string M07 = MB07 + LSS
string M08 = MB08 + LS
string M09 = MB09 + LS
string M10 = MB10 + LS
string M11 = MB11 + LS
string M12 = MB12 + LS
string M13 = MB13 + 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_TYPE = "Qualifies the retrieved metric data. See the 'Old and Other Futures' section of the CFTC's
     Explanatory Notes for details on types."
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], tooltip = TT_METRIC)
string metricDirectionInput = input.string("No direction", "Direction",          options = ["No direction", "Long", "Short", "Spreading"], tooltip = TT_DIR)
string metricTypeInput      = input.string("All",          "Type",               options = ["All", "Old", "Other"], tooltip = TT_TYPE)
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 `M13`), 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
        => ""
//#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 Legacy metrics. 
string typeCOT = "Legacy"
// @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, metricTypeInput
 )
// @variable The COT ticker ID that specifies futures and options information. 
var string futuresWithOptionsTicker = cot.COTTickerid(
     typeCOT, cftcCode, true, metricName, metricDirectionInput, metricTypeInput
 )

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

// @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 symbol and 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, direction, data type, a selection mode that maps the symbol to COT data, futures or options data, and an optional CFTC code override. It uses the LibraryCOT library and raises an error when no data matches 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

Oil & commodities, 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
TypestringAllmetricTypeInput
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