4H RangeThis script visualizes certain key values based on a 4-hour timeframe of the selected market on the chart. These values include the High, Mid, and Low price levels during each 4-hour period.
These levels can be helpful to identify inside range price action, chop, and consolidation. They can sometimes act as pivots and can be a great reference for potential entries and exits if price continues to hold the same range. 
Here's a step-by-step overview of what this indicator does:
1. Inputs: At the beginning of the script, users are allowed to customize some inputs:
    Choose the color of lines and labels.
    Decide whether to show labels on the chart.
    Choose the size of labels ("tiny", "small", "normal", or "large").
    Choose whether to display price values in labels.
    Set the number of bars to offset the labels to the right.
    Set a threshold for the number of ticks that triggers a new calculation of high, mid, and low values.
    * Tick settings may need to be increased on equity charts as one tick is usually equal to one cent. 
       For example, if you want to clear the range when there is a close one point/one dollar above or below the range high/low then on ES
       that would be 4 ticks but one whole point on AAPL would be 100 ticks. 100 ticks on an equity chart may or may not be ideal due to 
       different % change of 100 ticks might be too excessive depending on the price per share. 
       So be aware that user preferred thresholds can vary greatly depending on which chart you're using. 
2. Retrieving Price Data: The script retrieves the high, low, and closing price for every 4-hour period for the current market. 
    The script also calculates the mid-price of each 4-hour period (the average of the high and low prices).
3. Line Drawing: At the start of the script (first run), it draws three lines (high, mid, and low) at the levels corresponding to the high, 
    mid, and low prices. Users can also change transparency settings on historical lines to view them. Default setting for historical lines 
    is for them to be hidden. 
4. Updating Lines and Labels: For each subsequent 4-hour period, the script checks whether the close price of the period has gone 
    beyond a certain threshold (set by user input) above the previous high or below the previous low. If it has, the script deletes the 
    previous lines and labels, draws new lines at the new high, mid, and low levels, and creates new labels (if the user has opted to 
    show labels).
5. Displaying Values in the Data Window: In addition to the visual representation on the chart, the script also plots the high, mid, and 
    low prices. These plotted values appear in the Data Window of TradingView, allowing users to see the exact price levels even when
    they're not directly labeled on the chart.
6. Updating Lines and Labels Position: At the end of each period, the script moves the lines and labels (if they're shown) to the right, 
    keeping them aligned with the current period.
Please note: This script operates based on a 4-hour timeframe, regardless of the timeframe selected on the chart. If a shorter timeframe is selected on the chart, the lines and labels will appear to extend across multiple bars because they represent 4-hour price levels. If a longer timeframe is selected, the lines and labels may not accurately represent high, mid, and low levels within that longer timeframe.
Cari dalam skrip untuk "文华财经tick价格"
Multi Yield CurveAn inversion between the 2 year and 10 year US treasury yield generally means a recession within 2 years. But the yield curve has more to it than that. This script helps analysis of the current and past yield curve (not limited to US treasury) and is very configurable.
"A yield curve is a line that plots yields (interest rates) of bonds having equal credit quality but differing maturity dates. The slope of the yield curve gives an idea of future interest rate changes and economic activity." (Investopedia)
When the slope is upward (longer maturity bonds have a higher interest rate than shorter maturity bonds), it generally means the economy is doing well and is expanding. When the slope is downward it generally means that there is more downside risk in the future.
The more inverted the curve is, and the more the inversion moves to the front, the more market participants are hedging against downside risk in the future.
The script draws up to 4 moments of a yield curve, which makes it easy to compare the current yield curve with past yield curves. It also draws lines in red when that part of the curve is inverted.
The script draws the lines with proper length between maturity (which most scripts do not) in order to make it more representative of the real maturity duration. The width cannot be scaled because TradingView does not allow drawing based on pixels.
This script is the only free script at time of writing with proper lengths, showing multiple yield curves, and being able to show yield curves other than the US treasury.
█  CONFIGURATION 
(The following can be configured by clicking "Settings" when the script is added to a chart)
By default the script is configured to show the US treasury (government bond) yields of all maturities, but it can be configured for any yield curve.
A ticker represents yield data for a specific maturity of a bond.
To configure different tickers, go to the "TICKERS" section. Tickers in this section must be ordered from low maturity to high maturity.
 • Enable: draw the ticker on the chart.
 • Ticker: ticker symbol on TradingView to fetch data for.
 • Months: amount of months of bond maturity the ticker represents.
To configure general settings, go to the "GENERAL" section.
 • Period: used for calculating how far back to look for data for past yield curve lines. See "Times back" further in this description for more info.
 • Min spacing: minimum amount of spacing between labels. Depending on the size of the screen, value labels can overlap. This setting sets how much empty space there must be between labels.
 • Value format: how the value at that part of the line should be written on the label. For example, 0.000 means the value will have 3 digits precision.
To configure line settings per yield curve, each has its own "LINE" section with the line number after it.
 • Enable: whether to enable drawing of this line.
 • Times back: how many times period to go back in time. When period is D, and times value is 2, the line will be of data from 2 days ago.
 • Color: color of the line when not inverted.
 • Style: style of the line. Possible values: sol, dsh, dot
 • Inversion color: color of the line when the curve inverses between the two maturities at that part of the curve.
 • Thickness: thickness of the line in pixels.
 • Labels: whether to draw value labels above the line. By default, this is only enabled for the first line.
 • Label text color: text color of value label.
 • Label background color: background color of value label.
To configure the durations axis at the bottom of the chart, go to the "DURATIONS" section.
 • Durations: whether to show maturity term duration labels below the chart.
 • Offset: amount to offset durations label to be below chart.
█  MISC 
Script originally inspired by the US Treasury Yield Curve script by @longfiat but has been completely rewritten and changed.
Multi Asset + Correlation OverlayFrom time to time, you may want to overlay multiple assets on the same chart instead of using multi-chart views. This can be a much cleaner way of viewing and comparing multiple assets. There is some functionality built into TradingView that lets you do this to a certain extent, but I wanted additional options, correlation labeling and ways to adjust the overlay location. So, today I am releasing to the community my Multi-Asset + Correlation Overlay script / indicator. 
 What is does:  This script allows you to overlay the price of any ticker onto your chart. It also labels the line with the ticker name, and calculates / labels the correlation coefficient of your newly overlayed asset. 
 How to use it:  Add the indicator to your chart. Then, go into the indicator settings to set the ticker of the asset you want to pull in along with how you want to "offset" it. Your 2 tickers may not be priced near each-other, so the offset setting allows you to pull the ticker you added up/down to better visually align with your chart's price range/layout. For instance, if the asset you added is priced $400 higher than the underlying chart price, you may want to set the offset to -400.
If you would like to add multiple tickers and multiple overlays, you can do that by just adding the indicator to your chart more than once. The color is adjustable, and the ticker of the asset will print to the right of the line representing the asset price. The script also calculates the correlation coefficient between the ticker overlay and the underlying chart asset. The correlation coefficient prints to the right of the ticker. 
Crypto Volume/Strength ComparatorHello Traders,
Here is an attempt to perform comparative analysis between top cryptos based on strength (oscillator) and volume. Methodology used here is similar to Magic Number formula described in the post :  Enhanced Magic Formula for fundamental analysis . But, instead of using fundamentals, we are making use of few technicals to derive similar outcome. Usage of the available stats will not be same as Magic number since we are using technicals.
 ⬜ Process 
▶ Get crypto exchange based on prefix of instrument being used.
▶ For the given exchange, get data for all the tickers available in input fields.
▶ Calculate Oscillator, Momentum based on price for each tickers.
▶ Calculate Oscillator, Momentum based on volume for each tickers.
▶ Calculate Volatility for each tickers.
▶ Rank Price-Oscillator, Price-Momentum, Volume-Oscillator, Volume-Momentum, Volatility for each tickers.
▶ Calculate combined rank by adding up individual ranks.
▶ Calculate movement of rankings from bar to bar
▶ Sort tickers based on rank and populate them on table. Display direction of rankings.
 ⬜ Components 
Display components are as follows:
  
 ⬜ Settings 
Settings are pretty simple and straightforward
  
 ⬜ Calculations 
▶  Oscillators  : High values of oscillators are considered as ideal as the process is intended towards finding trend.
▶  Momentum  : Momentum is calculated on the basis of  Squeeze Momentum Indicator  by @LazyBear.
▶  Volatility  : Volatility is calculated on the basis of  Williams Vix Fix  by @ChrisMoody. Here too since we are in trend following mode, lower vix fix is considered ideal.
 ⬜ Few Notes 
 
  Tickers will show data only if selected exchange has them. Some tickers are not available in all exchanges. In that case, it will show NAN. This is kind of unavoidable as we need to have fixed size arrays for any calculations.
  Indicator works only on crypto tickers which has valid exchange.
  Tickers move through the rankings in real time. Background of all stats are based on gradient from green to red.
  Tickers on top may not always have better long opportunity or tickers at bottom may not always be optimal for shorting. We need to consider how long the instrument may stay in the position or how fast it is moving in opposite direction. Hence, directions of the ranking movement are also shown on the table.
NASDAQ VWAP Distance Histogram (Multi-Symbol)📊 VWAP Distance Histogram (Multi-Symbol)
This custom indicator plots a histogram of price strength relative to the VWAP (Volume-Weighted Average Price).
The zero line is VWAP.
Histogram bars above zero = price trading above VWAP (strength).
Histogram bars below zero = price trading below VWAP (weakness).
Unlike a standard VWAP overlay, this tool lets you monitor multiple symbols at once and aggregates them into a single, easy-to-read histogram.
🔑 Features
Multi-Symbol Support → Track up to 10 different tickers plus the chart symbol.
Aggregation Options → Choose between average or median deviation across enabled symbols.
Percent or Raw Values → Display distance from VWAP as % of price or raw price points.
Smoothing → Apply EMA smoothing to calm intraday noise.
Color-Coded Histogram → Green above VWAP, red below.
Alerts → Trigger when the aggregate crosses above/below VWAP.
Heads-Up Table → Shows number of symbols tracked and current aggregate reading.
⚡ Use Cases
Market Breadth via VWAP → Monitor whether your basket of stocks is trading above or below VWAP.
Index Substitution → Create your own “mini index” by tracking a hand-picked set of tickers.
Intraday Confirmation → Use aggregate VWAP strength/weakness to confirm entries and exits.
Relative Strength Spotting → Switch on/off specific tickers to see who’s holding above VWAP vs. breaking down.
🛠️ Settings
Include Chart Symbol → Toggle to include the current chart’s ticker.
Smoothing → EMA length (set to 0 to disable).
Percent Mode → Show results as % of price vs. raw difference.
Aggregate Mode → Average or median across all active symbols.
Symbol Slots (S1–S10) → Enter tickers to track alongside the chart.
⚠️ Notes
Works best on intraday charts since VWAP is session-based.
Designed for confirmation, not as a standalone entry/exit signal.
Ensure correct symbol format (e.g., NASDAQ:AAPL if needed).
✅ Tip: Combine this with your regular price action strategy. For example, if your setup triggers long and the histogram is well above zero, that’s added confirmation. If it’s below zero, caution — the basket shows weakness.
Yelober - Market Internal direction+ Key levelsYelober – Market Internals + Key Levels is a focused intraday trading tool that helps you spot high-probability price direction by anchoring decisions to structure that matters: yesterday’s RTH High/Low, today’s pre-market High/Low, and a fast Value Area/POC from the prior session. Paired with a compact market internals dashboard (NYSE/NASDAQ UVOL vs. DVOL ratios, VOLD slopes, TICK/TICKQ momentum, and optional VIX trend), it gives you a real-time read on breadth so you can choose which direction to trade, when to enter (breaks, retests, or fades at PMH/PML/VAH/VAL/POC), and how to plan exits as internals confirm or deteriorate. On top of these intraday decision benefits, it also allows traders—in a very subtle but powerful way—to keep an eye on the VIX and immediately recognize significant spikes or sharp decreases that should be factored in before entering a trade, or used as a quick signal to modify an existing position. In short: clear levels for the chart, live internals for the context, and a smarter, rules-based path to execution.
# Yelober – Market Internals + Key Levels
*A TradingView indicator for session key levels + real‑time market internals (NYSE/NASDAQ TICK, UVOL/DVOL/VOLD, and VIX).*
**Script name in Pine:** `Yelober - Market Internal direction+ Key levels` (Pine v6)
---
## 1) What this indicator does
**Purpose:** Help intraday traders quickly find high‑probability reaction zones and read market internals momentum without switching charts. It overlays yesterday/today’s **automatic price levels** on your active chart and shows a **market breadth table** that summarizes NYSE/NASDAQ buying pressure and TICK direction, with an optional VIX trend read.
### Key features at a glance
* **Automatic Price Levels (overlay on chart)**
  * Yesterday’s High/Low of Day (**yHoD**, **yLoD**)
  * Extended Hours High/Low (**yEHH**, **yEHL**) across yesterday AH + today pre‑market
  * Today’s Pre‑Market High/Low (**PMH**, **PML**)
  * Yesterday’s **Value Area High/Low** (**VAH/VAL**) and **Point of Control (POC)** computed from a volume profile of yesterday’s **regular session**
  * Smart de‑duplication:
    * Shows **only the higher** of (yEHH vs PMH) and **only the lower** of (yEHL vs PML) to avoid redundant bands
* **Market Breadth Table (on‑chart table)**
  * **NYSE ratio** = UVOL/DVOL (signed) with **VOLD slope** from session open
  * **NASDAQ ratio** = UVOLQ/DVOLQ (signed) with **VOLDQ slope** from session open
  * **TICK** and **TICKQ**: live cumulative ratio and short‑term slope
  * **VIX** (optional): current value + slope over a configurable lookback/timeframe
  * Color‑coded trends with sensible thresholds and optional normalization
---
## 2) How to use it (trader workflow)
1. **Mark your reaction zones**
   * Watch **yHoD/yLoD**, **PMH/PML**, and **VAH/VAL/POC** for first touches, break/retest, and failure tests.
   * Expect increased responsiveness when multiple levels cluster (e.g., PMH ≈ VAH ≈ daily pivot).
2. **Read the breadth panel for context**
   * **NYSE/NASDAQ ratio** (>1 = more up‑volume than down‑volume; <−1 = down‑dominant). Strong green across both favors long setups; red favors short setups.
   * **VOLD slopes** (NYSE & NASDAQ): positive and accelerating → broadening participation; negative → persistent pressure.
   * **TICK/TICKQ**: cumulative ratio and **slope arrows** (↗ / ↘ / →). Use the slope to gauge **near‑term thrust or fade**.
   * **VIX slope**: rising VIX (red) often coincides with risk‑off; falling VIX (green) with risk‑on.
3. **Confluence = higher confidence**
   * Example: Price reclaims **PMH** while **NYSE/NASDAQ ratios** print green and **TICK slopes** point ↗ — consider break‑and‑go; if VIX slope is ↘, that adds risk‑on confidence.
   * Example: Price rejects **VAH** while **VOLD slopes** roll negative and VIX ↗ — consider fade/reversal.
4. **Risk management**
   * Place stops just beyond key levels tested; if breadth flips, tighten or exit.
> **Timeframes:** Works best on 1–15m charts for intraday. Value Area is computed from **yesterday’s RTH**; choose a smaller calculation timeframe (e.g., 5–15m) for stable profiles.
---
## 3) Inputs & settings (what each option controls)
### Global Style
* **Enable all automatic price levels**: master toggle for yHoD/yLoD, yEHH/yEHL, PMH/PML, VAH/VAL/POC.
* **Line style/width**: applies to all drawn levels.
* **Label size/style** and **label color linking**: use the same color as the line or override with a global label color.
* **Maximum bars lookback**: how far the script scans to build yesterday metrics (performance‑sensitive).
### Value Area / Volume Profile
* **Enable Value Area calculations** *(on by default)*: computes yesterday’s **POC**, **VAH**, **VAL** from a simplified intraday volume profile built from yesterday’s **regular session bars**.
* **Max Volume Profile Points** *(default 50)*: lower values = faster; higher = more precise.
* **Value Area Calculation Timeframe** *(default 15)*: the security timeframe used when collecting yesterday’s highs/lows/volumes.
### Individual Level Toggles & Colors
* **yHoD / yLoD** (yesterday high/low)
* **yEHH / yEHL** (yesterday AH + today pre‑market extremes)
* **PMH / PML** (today pre‑market extremes)
* **VAH / VAL / POC** (yesterday RTH value area + point of control)
### Market Breadth Panel
* **Show NYSE / NASDAQ / VIX**: choose which series to display in the table.
* **Table Position / Size / Background Color**: UI placement and legibility.
* **Slope Averaging Periods** *(default 5)*: number of recent TICK/TICKQ ratio points used in slope calculation.
* **Candles for Rate** *(default 10)* & **Normalize Rate**: VIX slope calculation as % change between `now` and `n` candles ago; normalize divides by `n`.
* **VIX Timeframe**: optionally compute VIX on a higher TF (e.g., 15, 30, 60) for a smoother regime read.
* **Volume Normalization** (NYSE & NASDAQ): display VOLD slopes scaled to `tens/thousands/millions/10th millions` for readable magnitudes; color thresholds adapt to your choice.
---
## 4) Data sources & definitions
* **UVOL/VOLD (NYSE)** and **UVOLQ/DVOLQ/VOLDQ (NASDAQ)** via `request.security()`
  * **Ratio** = `UVOL/DVOL` (signed; negative when down‑volume dominates)
  * **VOLD slope** ≈ `(VOLD_now − VOLD_open) / bars_since_open`, then normalized per your setting
* **TICK/TICKQ**: cumulative sum of prints this session with **positives vs negatives ratio**, plus a simple linear regression **slope** of the last `N` ratio values
* **VIX**: value and slope across a user‑selected timeframe and lookback
* **Sessions (EST/EDT)**
  * **Regular:** 09:30–16:00
  * **Pre‑Market:** 04:00–09:30
  * **After Hours:** 16:00–20:00
* **Extended‑hours extremes** combine **yesterday AH** + **today PM**
> **Note:** All session checks are done with TradingView’s `time(…,"America/New_York")` context. If your broker’s RTH differs (e.g., futures), adjust expectations accordingly.
---
## 5) How the algorithms work (plain English)
### A) Key Levels
* **Yesterday’s RTH High/Low**: scans yesterday’s bars within 09:30–16:00 and records the extremes + bar indices.
* **Extended Hours**: scans yesterday AH and today PM to get **yEHH/yEHL**. Script shows **either yEHH or PMH** (whichever is **higher**) and **either yEHL or PML** (whichever is **lower**) to avoid duplicate bands stacked together.
* **Value Area & POC (RTH only)**
  * Build a coarse volume profile with `Max Volume Profile Points` buckets across the price range formed by yesterday’s RTH bars.
  * Distribute each bar’s volume uniformly across the buckets it spans (fast approximation to keep Pine within execution limits).
  * **POC** = bucket with max volume. **VA** expands from POC outward until **70%** of cumulative volume is enclosed → yields **VAH/VAL**.
### B) Market Breadth Table
* **NYSE/NASDAQ Ratio**: signed UVOL/DVOL with basic coloring.
* **VOLD Slopes**: from session open to current, normalized to human‑readable units; colors flip green/red based on thresholds that map to your normalization setting (e.g., ±2M for NYSE, ±3.5×10M for NASDAQ).
* **TICK/TICKQ Slope**: linear regression over the last `N` ratio points → **↗ / → / ↘** with the rounded slope value.
* **VIX Slope**: % change between now and `n` candles ago (optionally divided by `n`). Red when rising beyond threshold; green when falling.
---
## 6) Recommended presets
* **Stocks (liquid, intraday)**
  * Value Area **ON**, `Max Volume Points` = **40–60**, **Timeframe** = **5–15**
  * Breadth: show **NYSE & NASDAQ & VIX**, `Slope periods` = **5–8**, `Candles for rate` = **10–20**, **Normalize VIX** = **ON**
* **Index futures / very high‑volume symbols**
  * If you see Pine timeouts, set `Max Volume Points` = **20–40** or temporarily **disable Value Area**.
  * Keep breadth panel **ON** (it’s light). Consider **VIX timeframe = 15/30** for regime clarity.
---
## 7) Tips, edge cases & performance
* **Performance:** The volume profile is capped (`maxBarsToProcess ≤ 500` and bucketed) to keep it responsive. If you experience slowdowns, reduce `Max Volume Points`, `Maximum bars lookback`, or disable Value Area.
* **Redundant lines:** The script **intentionally suppresses** PMH/PML when yEHH/yEHL are more extreme, and vice‑versa.
* **Label visibility:** Use `Label style = none` if you only want clean lines and read values from the right‑end labels.
* **Futures/RTH differences:** Value Area is from **yesterday’s RTH** only; for 24h instruments the RTH period may not reflect overnight structure.
* **Session transitions:** PMH/PML tracking stops as soon as RTH starts; values persist as static levels for the session.
---
## 8) Known limitations
* Uses public TradingView symbols: `UVOL`, `VOLD`, `UVOLQ`, `DVOLQ`, `VOLDQ`, `TICK`, `TICKQ`, `VIX`. If your data plan or region limits any symbol, the corresponding table rows may show `na`.
* The VA/POC approximation assumes uniform distribution of each bar’s volume across its high–low. That’s fast but not a tick‑level profile.
* Works best on US equities with standard NY session; alternative sessions may need code changes.
---
## 9) Troubleshooting
* **“Script is too slow / timed out”** → Lower `Max Volume Points`, lower `Maximum bars lookback`, or toggle **OFF** `Enable Value Area calculations` for that instrument.
* **Missing breadth values** → Ensure the symbols above load on your account; try reloading chart or switching timeframes once.
* **Overlapping labels** → Set `Label style = none` or reduce label size.
---
## 10) Version / license / contribution
* **Version:** Initial public release (Pine v6).
* **Author:** © yelober 
* **License:** Free for community use and enhancement. Please keep author credit.
* **Contributing:** Open PRs/ideas: presets, alert conditions, multi‑day VA composites, optional mid‑value (`(VAH+VAL)/2`), session filter for futures, and alertable state machine for breadth regime transitions.
---
## 11) Quick start (TL;DR)
1. Add the indicator and **keep default settings**.
2. Trade **reactions** at yHoD/yLoD/PMH/PML/VAH/VAL/POC.
3. Use the **breadth table**: look for **green ratios + ↗ slopes** (risk‑on) or **red ratios + ↘ slopes** (risk‑off). Check **VIX** slope for confirmation.
4. Manage risk around levels; when breadth flips against you, tighten or exit.
---
### Changelog (public)
* **v1.0:** First community release with automatic RTH levels, VA/POC approximation, breadth dashboard (NYSE/NASDAQ/TICK/TICKQ/VIX) with normalization and adaptive color thresholds.
Open Interest Footprint IQ [TradingIQ]Hello Traders!
Th e Open Interest Footprint IQ indicator is an advanced visualization tool designed for cryptocurrency markets. It provides a granular, real-time breakdown of open interest changes across different price levels, allowing traders to see how aggressive market participation is distributed within each bar.
Unlike standard footprint charts that rely solely on volume, this indicator offers unique insights by focusing on the interaction between price action and changes in open interest (OI) — a leading metric often used to infer trader intent and positioning.
 How it works 
The Open Interest Footprint IQ processes lower timeframe price and open interest data to build a footprint-style chart that shows how traders are positioning themselves within each candle.
Here’s a breakdown of the process:
1. Granular OI & Price Sampling
The script retrieves lower-timeframe data (1-minute, 1-second, or 1-tick, based on your setting).
For each candle, it captures:
 
 High and low prices
 Price change direction
 Change in open interest (OI)
 
2. Classifying Trader Behavior
For each lower-timeframe segment, the indicator determines the type of positioning occurring based on price movement and OI change:
 
 If price is moving up and open interest is increasing, it suggests that long positions are being opened. This is considered a "Longs Opening" event, labeled as UU (Up/Up).
 If price is moving up but open interest is decreasing, it indicates that short positions are being closed. This is referred to as UD (Up/Down), or "Shorts Closing."
 If price is moving down and open interest is increasing, it signals that short positions are being opened. This is known as DU (Down/Up), or "Shorts Opening."
 If price is moving down while open interest is also decreasing, it means that long positions are being closed. This is labeled as DD (Down/Down), or "Longs Closing."
 
These are stored in separate arrays and displayed at specific price levels.
It is particularly useful for identifying:
 
 Where longs or shorts are opening/closing positions
 Stacked imbalances (indicative of potential absorption or exhaustion)
 Value area zones and POC (Point of Control) based on OI, not volume
 
This footprint runs on your choice of sub-bar granularity and is ideal for high-frequency trading, scalping, and entries based on order flow dynamics.
 Key Features 
 Footprint Visualization 
At each price level within a candle:
 
 Long/short opening and closing behavior is broken down.
 Delta (net open interest change) is displayed both numerically and color-coded.
 Optional gradient coloring shows intensity and type of flow (longs/shorts opened/closed).
 Cumulative or per-bar reset modes allow you to track OI evolution over time.
 
  
The image above explains the information that each Footprint box shows across a candlestick!
Each footprint box shows:
 
 OI Delta 
 OI Delta %
 Longs Opened (LO)
 Longs Closed (LC)
 Shorts Opened (SO) 
 Shorts Closed (SC)
 
  
The image above explains the color-coding feature of the indicator.
Boxes are color coded to show which position action 
dominated at the price area.
For this example:
 
 Green boxes = Long positions being opened dominated
 Purple boxes = Long positions being closed dominated
 Red boxes = Short positions being opened dominated
 Yellow boxes = Short positions being closed dominated
 
All colors are customizable.
Additionally, for traders who are only interested in whether OI increased/decreased, a "two-color" option is available in the settings.
  
For the two-color option, footprint boxes can be one of two colors. Showing whether OI increased or decreased at the level.
 Cumulative Levels 
Open Interest Footprint IQ contains a "Cumulative Levels" feature that tracks/stores open interest change at tick levels over time, rather than resetting per bar.
  
With the "Cumulative Levels" feature enabled, traders can see open interest changes persist across all candlesticks. This feature is useful for determining whether longs opening, longs closing, shorts opening, or shorts closing are dominating at particular price areas over time rather than on a single bar. 
A useful feature to see if shorts/longs are favoring certain price throughout the day, week, month, etc.
 Input Settings Explained 
 Granularity (Dropdown: Granularity) 
Options: 1-Minute, 1-Second, 1-Tick
Determines how finely the script samples the lower timeframe data to construct the footprint.
For precision:
1-Tick = Highest accuracy, but more resource-intensive.
1-Second/1-Minute = Suitable for broader or more zoomed-out analysis.
 Tick Level Distance (Tick Level Distance (0 = Auto)) 
Defines the vertical spacing between levels in the footprint chart.
If 0, the script uses an automatic calculation based on ATR to adapt to volatility.
Set a manual value (e.g., 5) to control the height granularity of each level in ticks.
 Cumulative Levels (Toggle) 
If enabled, the footprint builds cumulatively over time, rather than resetting per candle.
Use case: Visualize ongoing buildup of OI activity across a session or day.
 Cumulative Levels Reset TF (Timeframe) 
Sets the reset interval for the cumulative view (e.g., reset daily, hourly, etc.)
Works only when Cumulative Levels is enabled.
 Delta Box Display Settings 
 Show Delta Percentage 
Toggles the display of the percentage change in OI across the footprint level.
Helpful to gauge how aggressive positioning is relative to total OI at that level.
 Show Longs/Shorts (Opened/Closed) 
Show Longs Opened: Displays OI increase in up candles (price ↑, OI ↑).
Show Longs Closed: Displays OI decrease in down candles (price ↓, OI ↓).
Show Shorts Opened: OI increase in down candles (price ↓, OI ↑).
Show Shorts Closed: OI decrease in up candles (price ↑, OI ↓).
These behaviors are color-coded to give traders instant context:
Blue-green for longs opening.
Purple for longs closing.
Red for shorts opening.
Yellow for shorts closing.
 Value Area & POC 
Value Area % (Value Area %)
Controls how much cumulative open interest is used to define the value area.
Example: 70% means the smallest range of prices that contains 70% of total OI in that bar will be marked.
Helps identify zones of interest, support/resistance, and institutional levels.
  
The image above explains how to identify the VAH/VAL/POC shown by Open Interest Footprint IQ.
 
 VAH = Upper 🞂
 POC = ●
 VAL = Lower 🞂
 
 Imbalances 
 Imbalance Percentage 
Defines the minimum delta % required at a level to be marked as an imbalance.
If the net open interest change at a level exceeds this threshold, a visual marker appears.
  
 Stacked Imbalance Count 
If the number of consecutive imbalance levels meets this count, a “Stacked Imbalance” alert will trigger.
This can signal aggressive buying or selling pressure, potential breakout zones, or institutional absorption.
  
 Color Settings 
Longs Opened / Closed, Shorts Opened / Closed
Customize the color palette for each order flow behavior.
These colors appear in the background gradient of the footprint boxes.
 Up/Down Only Mode 
Toggle to override all behavior-based colors with a single Up Color and Down Color.
Useful if you prefer a simple bull/bear view.
Up Color / Down Color
If "Up/Down Only" is enabled, these two colors are used to represent all net positive or negative deltas.
Special Notes
Crypto only: This script works only with crypto tickers on TradingView.
For other assets (stocks, futures), a warning message will appear instead.
OI data must be available from the exchange (many perpetual pairs support this).
If the footprint is too small or invisible, increase your tick level spacing in the settings.
 Alerts 
When a stacked imbalance is detected, an alert is fired ("Stacked Imbalance").
This feature is useful for automated systems, bots, or simply staying informed of potential trade setups.
And that's all for now!
If you have any questions or features you'd like to see feel free to share them in the comments below! 
Thank you traders!
ICT Opening Range Projections (tristanlee85)ICT Opening Range Projections 
This indicator visualizes key price levels based on ICT's (Inner Circle Trader) "Opening Range" concept. This 30-minute time interval establishes price levels that the algorithm will refer to throughout the session. The indicator displays these levels, including standard deviation projections, internal subdivisions (quadrants), and the opening price.
  
 🟪 What It Does 
The Opening Range is a crucial 30-minute window where market algorithms establish significant price levels. ICT theory suggests this range forms the basis for daily price movement.
This script helps you:
 
  Mark the  high, low, and opening price  of each session.
  Divide the range into  quadrants  (premium, discount, and midpoint/Consequent Encroachment).
  Project potential price targets beyond the range using  configurable standard deviation multiples .
 
 🟪 How to Use It 
This tool aids in time-based technical analysis rooted in ICT's Opening Range model, helping you observe price interaction with algorithmic levels.
Example uses include:
 
  Identifying early structural boundaries.
  Observing price behavior within premium/discount zones.
  Visualizing initial displacement from the range to anticipate future moves.
  Comparing price reactions at projected standard deviation levels.
  Aligning price action with significant times like London or NY Open.
 
 Note:  This indicator provides a visual framework; it does  not  offer trade signals or interpretations.
 🟪 Key Information 
 
   Time Zone:   New York time (ET)  is required on your chart.
   Sessions:  Supports multiple sessions, including NY midnight, NY AM, NY PM, and three custom timeframes.
   Time Interval:  Supports multi-timeframe up to 15 minutes. Best used on a  1-minute chart  for accuracy.
 
 🟪 Session Options 
The Opening Range interval is configurable for up to 6 sessions:
 Pre-defined ICT Sessions: 
 
   NY Midnight:  12:00 AM – 12:30 AM ET
   NY AM:  9:30 AM – 10:00 AM ET
   NY PM:  1:30 PM – 2:00 PM ET
 
 Custom Sessions: 
 
  Three user-defined start/end time pairs.
 
This example shows a custom session from 03:30 - 04:00:
  
 🟪 Understanding the Levels 
The  Opening Price  is the open of the first 1-minute candle within the chosen session.
At session close, the  Opening Range  is calculated using its  High  and  Low . An optional  swing-based mode  uses swing highs/lows for range boundaries.
The range is divided into  quadrants  by its midpoint ( Consequent Encroachment  or CE):
 
   Upper Quadrant:  CE to high (premium).
   Lower Quadrant:  Low to CE (discount).
 
These subdivisions help visualize internal range dynamics, where price often reacts during algorithmic delivery.
 🟪 Working with Ranges 
By default, the range is determined by the highest high and lowest low of the 30-minute session:
  
A range can also be determined by the highest/lowest swing points:
  
Quadrants outline the premium and discount of a range that price will reference:
  
Small ranges still follow the same algorithmic logic, but may be deemed insignificant for one's trading. These can be filtered in the settings by specifying a minimum ticks limit. In this example, the range is 42 ticks (10.5 points) but the indicator is configured for 80 ticks (20 points). We can select which levels will plot if the range is below the limit. Here, only the 00:00 opening price is plotted:
  
You may opt to include the range high/low, quadrants, and projections as well. This will plot a red (configurable) range bracket to indicate it is below the limit while plotting the levels:
  
 🟪 Price Projections 
 Projections  extend beyond the Opening Range using standard deviations, framing the market beyond the initial session and identifying potential targets. You define the standard deviation multiples (e.g., 1.0, 1.5, 2.0).
Both  positive and negative extensions  are displayed, symmetrically projected from the range's high and low.
The  Dynamic Levels  option plots only the next projection level once price crosses the previous extreme. For example, only the 0.5 STDEV level plots until price reaches it, then the 1.0 level appears, and so on. This continues up to your defined maximum projections, or indefinitely if standard deviations are set to 0.
This example shows dynamic levels for a total of 6 sessions, only 1 of which meet a configured minimum limit of 50 ticks:
  
Small ranges followed by significant displacement are impacted the most with the number of levels plotted. You may hide projections when configuring the minimum ticks.
A fixed standard deviation will plot levels in both directions, regardless of the price range. Here, we plot up to 3.0 which hiding projections for small ranges:
  
 🟪 Legal Disclaimer 
This indicator is provided for informational and educational purposes only. It is not financial advice, and should not be construed as a recommendation to buy or sell any financial instrument. Trading involves substantial risk, and you could lose a significant amount of money. Past performance is not indicative of future results. Always consult with a qualified financial professional before making any trading or investment decisions. The creators and distributors of this indicator assume no responsibility for your trading outcomes.
Correlation Heatmap█ OVERVIEW 
This indicator creates a correlation matrix for a user-specified list of symbols based on their time-aligned weekly or monthly price returns. It calculates the  Pearson correlation coefficient  for each possible symbol pair, and it displays the results in a symmetric table with heatmap-colored cells. This format provides an intuitive view of the linear relationships between various symbols' price movements over a specific time range.
 █ CONCEPTS 
 Correlation 
 Correlation  typically refers to an observable statistical relationship between two datasets. In a financial time series context, it usually represents the extent to which sampled values from a pair of datasets, such as two series of price returns, vary jointly over time. More specifically, in this context, correlation describes the  strength  and  direction  of the relationship between the samples from both series. 
If two separate time series tend to rise and fall together proportionally, they might be highly correlated. Likewise, if the series often vary in opposite directions, they might have a strong  anticorrelation . If the two series do not exhibit a clear relationship, they might be  uncorrelated . 
Traders frequently analyze asset correlations to help optimize portfolios, assess market behaviors, identify potential risks, and support trading decisions. For instance, correlation often plays a key role in  diversification . When two instruments exhibit a strong correlation in their returns, it might indicate that buying or selling both carries elevated  unsystematic risk . Therefore, traders often aim to create balanced portfolios of relatively uncorrelated or anticorrelated assets to help promote investment diversity and potentially offset some of the risks.
When using correlation analysis to support investment decisions, it is crucial to understand the following caveats:
 •  Correlation does not imply causation . Two assets might vary jointly over an analyzed range, resulting in high correlation or anticorrelation in their returns, but that  does not  indicate that either instrument directly influences the other. Joint variability between assets might occur because of shared sensitivities to external factors, such as interest rates or global sentiment, or it might be entirely coincidental. In other words, correlation does not provide sufficient information to identify  cause-and-effect  relationships. 
 • Correlation  does not  predict the future relationship between two assets. It only reflects the estimated strength and direction of the relationship between the current analyzed samples. Financial time series are ever-changing. A strong trend between two assets can weaken or reverse in the future. 
 Correlation coefficient 
A  correlation coefficient  is a numeric measure of correlation. Several coefficients exist, each quantifying  different types  of relationships between two datasets. The most common and widely known measure is the  Pearson product-moment correlation coefficient , also known as the  Pearson correlation coefficient  or  Pearson's r . Usually, when the term "correlation coefficient" is used without context, it refers to this correlation measure. 
The Pearson correlation coefficient quantifies the strength and direction of the  linear relationship  between two variables. In other words, it indicates how consistently variables' values move together or in opposite directions in a proportional, linear manner. Its formula is as follows:
𝑟(𝑥, 𝑦) = cov(𝑥, 𝑦) / (𝜎𝑥 * 𝜎𝑦)
Where:
 • 𝑥 is the first variable, and 𝑦 is the second variable.
 • cov(𝑥, 𝑦) is the  covariance  between 𝑥 and 𝑦.
 • 𝜎𝑥 is the  standard deviation  of 𝑥.
 • 𝜎𝑦 is the standard deviation of 𝑦.
In essence, the correlation coefficient measures the covariance between two variables,  normalized  by the product of their standard deviations. The coefficient's value ranges from -1 to 1, allowing a more straightforward interpretation of the relationship between two datasets than what covariance alone provides:
 • A value of 1 indicates a perfect positive correlation over the analyzed sample. As one variable's value changes, the other variable's value changes proportionally in the  same direction .
 • A value of -1 indicates a perfect negative correlation (anticorrelation). As one variable's value increases, the other variable's value  decreases  proportionally. 
 • A value of 0 indicates  no linear relationship  between the variables over the analyzed sample. 
 Aligning returns across instruments 
In a financial time series, each data point (i.e., bar) in a sample represents information collected in periodic intervals. For instance, on a "1D" chart, bars form at specific times as successive days elapse. 
However, the times of the data points for a symbol's standard dataset depend on its active  sessions , and sessions vary across instrument types. For example, the daily session for NYSE stocks is 09:30 - 16:00 UTC-4/-5 on weekdays, Forex instruments have 24-hour sessions that span from 17:00 UTC-4/-5 on one weekday to 17:00 on the next, and new daily sessions for cryptocurrencies start at 00:00 UTC every day because crypto markets are consistently open. 
Therefore, comparing the standard datasets for different asset types to identify correlations presents a challenge. If two symbols' datasets have bars that form at unaligned times, their correlation coefficient  does not  accurately describe their relationship. When calculating correlations between the returns for two assets, both datasets must maintain consistent time alignment in their values and cover identical ranges for meaningful results.
To address the issue of time alignment across instruments, this indicator requests confirmed  weekly  or  monthly  data from  spread tickers  constructed from the chart's ticker and another specified ticker. The datasets for spreads are derived from lower-timeframe data to ensure the values from all symbols come from aligned points in time, allowing a fair comparison between different instrument types. Additionally, each spread ticker ID includes necessary modifiers, such as extended hours and adjustments. 
In this indicator, we use the following process to retrieve time-aligned returns for correlation calculations:
 1. Request the current and previous prices from a spread representing the  sum  of the chart symbol and another symbol ( "chartSymbol + anotherSymbol" ).
 2. Request the prices from another spread representing the  difference  between the two symbols ( "chartSymbol - anotherSymbol" ).
 3. Calculate half of the difference between the values from both spreads ( 0.5 * (requestedSum - requestedDifference) ). The results represent the symbol's prices at times aligned with the sample points on the current chart.
 4. Calculate the arithmetic return of the retrieved prices:  (currentPrice - previousPrice) / previousPrice 
 5. Repeat steps 1-4 for each symbol requiring analysis. 
It's crucial to note that because this process retrieves prices for a symbol at times consistent with periodic points on the current chart, the values can represent prices from  before or after  the closing time of the symbol's usual session.
Additionally, note that the maximum number of weeks or months in the correlation calculations depends on the chart's range and the largest time range common to all the requested symbols. To maximize the amount of data available for the calculations, we recommend setting the chart to use a daily or higher timeframe and specifying a chart symbol that covers a sufficient time range for your needs.
 █ FEATURES 
This indicator analyzes the correlations between several pairs of user-specified symbols to provide a structured, intuitive view of the relationships in their returns. Below are the indicator's key features:
 Requesting a list of securities 
The "Symbol list" text box in the indicator's "Settings/Inputs" tab accepts a  comma-separated  list of symbols or ticker identifiers with optional spaces (e.g., "XOM, MSFT, BITSTAMP:BTCUSD"). The indicator dynamically requests returns for each symbol in the list, then calculates the correlation between each pair of return series for its heatmap display. 
Each item in the list must represent a valid symbol or ticker ID. If the list includes an invalid symbol, the script raises a runtime error. 
To specify a broker/exchange for a symbol, include its name as a prefix with a colon in the "EXCHANGE:SYMBOL" format. If a symbol in the list does not specify an exchange prefix, the indicator selects the most commonly used exchange when requesting the data.
Note that the number of symbols allowed in the list depends on the user's plan. Users with non-professional plans can compare up to 20 symbols with this indicator, and users with professional plans can compare up to 32 symbols. 
 Timeframe and data length selection 
The "Returns timeframe" input specifies whether the indicator uses weekly or monthly returns in its calculations. By default, its value is "1M", meaning the indicator analyzes monthly returns. Note that this script requires a chart timeframe lower than or equal to "1M". If the chart uses a higher timeframe, it causes a runtime error.  
To customize the length of the data used in the correlation calculations, use the "Max periods" input. When enabled, the indicator limits the calculation window to the number of periods specified in the input field. Otherwise, it uses the chart's time range as the limit. The top-left corner of the table shows the number of confirmed weeks or months used in the calculations. 
It's important to note that the number of confirmed periods in the correlation calculations is limited to the largest time range common to  all  the requested datasets, because a meaningful correlation matrix requires analyzing each symbol's returns under the  same  market conditions. Therefore, the correlation matrix can show different results for the same symbol pair if another listed symbol restricts the aligned data to a shorter time range. 
 Heatmap display 
This indicator displays the correlations for each symbol pair in a heatmap-styled table representing a symmetric correlation matrix. Each row and column corresponds to a specific symbol, and the cells at their intersections correspond to  symbol pairs . For example, the cell at the "AAPL" row and "MSFT" column shows the weekly or monthly correlation between those two symbols' returns. Likewise, the cell at the "MSFT" row and "AAPL" column shows the same value. 
Note that the  main diagonal  cells in the display, where the row and column refer to the same symbol, all show a value of 1 because any series of non-na data is always perfectly correlated with itself. 
The background of each correlation cell uses a gradient color based on the correlation value. By default, the gradient uses blue hues for positive correlation, orange hues for negative correlation, and white for no correlation. The intensity of each blue or orange hue corresponds to the strength of the measured correlation or anticorrelation. Users can customize the gradient's base colors using the inputs in the "Color gradient" section of the "Settings/Inputs" tab. 
 █ FOR Pine Script® CODERS 
  • This script uses the `getArrayFromString()` function from our  ValueAtTime  library to process the input list of symbols. The function splits the "string" value by its commas, then constructs an  array  of non-empty strings without leading or trailing whitespaces. Additionally, it uses the  str.upper()  function to convert each symbol's characters to uppercase. 
  • The script's `getAlignedReturns()` function requests time-aligned prices with two  request.security()  calls that use spread tickers based on the chart's symbol and another symbol. Then, it calculates the arithmetic return using the `changePercent()` function from the  ta  library. The `collectReturns()` function uses `getAlignedReturns()` within a loop and stores the data from each call within a  matrix . The script calls the `arrayCorrelation()` function on pairs of rows from the returned matrix to calculate the correlation values. 
  • For consistency, the `getAlignedReturns()` function includes extended hours and dividend adjustment modifiers in its data requests. Additionally, it includes other settings inherited from the chart's context, such as "settlement-as-close" preferences.
  • A Pine script can execute up to 40 or 64 unique `request.*()` function calls, depending on the user's plan. The maximum number of symbols this script compares is  half  the plan's limit, because `getAlignedReturns()` uses two  request.security()  calls. 
  • This script can use the  request.security()  function within a loop because all scripts in Pine v6 enable  dynamic requests  by default. Refer to the  Dynamic requests  section of the  Other timeframes and data  page to learn more about this feature, and see our  v6 migration guide  to learn what's new in Pine v6.
  • The script's  table  uses two distinct  color.from_gradient()  calls in a  switch  structure to determine the cell colors for positive and negative correlation values. One call calculates the color for values from -1 to 0 based on the first and second input colors, and the other calculates the colors for values from 0 to 1 based on the second and third input colors. 
 Look first. Then leap. 
RSI Overlay Table with Pivot-Based Divergence and SortingThis script offers an advanced RSI-based overlay table designed to identify and highlight divergences across multiple timeframes (Daily, Weekly, Monthly) for up to 13 tickers. It employs a  pivot-based detection mechanism  that spots positive and negative divergences, helping traders identify potential trend reversals or continuations.
 Key Features 
 1. Pivot-Based Divergence Detection: 
 
 The script uses pivot points to identify both positive and negative divergences using the RSI indicator and price movements.
 User-adjustable pivot settings enhance detection sensitivity, providing traders with an opportunity to fine-tune divergence signals for different market conditions.
 
 2. Multi-Timeframe Analysis: 
 
 Displays RSI values along with divergence signals for daily, weekly, and monthly timeframes.
 Enables traders to monitor short-term, swing, and long-term trends on a single table, providing a comprehensive view.
 
 3. Customizable Alerts and Visual Cues: 
 
 The script generates alerts whenever a divergence is detected, ensuring timely notifications.
 Overbought and oversold levels are color-coded based on user-defined thresholds, with the "P-" and "N-" prefixes indicating positive and negative divergences, respectively.
 
 4. User-Friendly Interface: 
 
 An intuitive table design allows for easy comparison of RSI levels and divergence signals across multiple tickers.
 Offers customizable table positioning options (bottom left, center, right, or middle right) for convenient chart integration.
 
 How to Use 
 
 Input Your Tickers:  Add up to 13 tickers that you wish to monitor.
 Adjust Pivot Settings:  Fine-tune the 'Pivot Left Bars' and 'Pivot Right Bars' to optimize the pivot detection process.
 Set Overbought/Oversold Levels:  Define the RSI thresholds according to your trading strategy.
 Enable Alerts:  Receive notifications for divergence signals detected on any timeframe.
 
 Concepts Underlying the Calculations 
The script leverages the RSI (Relative Strength Index), a popular momentum indicator, to measure the velocity and magnitude of price changes. By comparing RSI values with pivot points, the script identifies divergences that suggest potential reversals. This method ensures more reliable signals than simple bar comparisons, as it accounts for broader market movements over time.
 Why This Script Is Unique 
This RSI overlay script stands out due to its multi-ticker, multi-timeframe divergence analysis and the use of pivot-based detection for higher accuracy. The integration of an alert system, combined with color-coded visual cues, makes it an actionable and comprehensive tool for traders.
 Turkish Translation 
 RSI Overlay Tablosu - Pivot Tabanlı Uyumsuzluk ve Sıralama ile 
Bu script, birden fazla zaman diliminde (Günlük, Haftalık, Aylık) 13 adede kadar seçilen hisse senetleri veya varlıklar için RSI tabanlı ayrışmaları belirleyen ve vurgulayan gelişmiş bir overlay tablosu sunar. Pivot tabanlı tespit mekanizması, trend dönüşlerini veya devamlarını belirlemeye yardımcı olacak şekilde pozitif ve negatif ayrışmaları tespit eder.
 Özellikler 
 1. Pivot Tabanlı Uyumsuzluk Tespiti: 
 
 Pivot noktalarını kullanarak RSI göstergesi ve fiyat hareketleri arasındaki pozitif ve negatif uyumsuzlukları tespit eder.
 Kullanıcı ayarlı pivot ayarları, uyumsuzluk sinyallerinin hassasiyetini artırır ve farklı piyasa koşullarına uygun hale getirir.
 
 2. Çoklu Zaman Dilimi Analizi: 
 
 Günlük, haftalık ve aylık zaman dilimlerinde RSI değerlerini ve ayrışma sinyallerini gösterir.
 Kısa vadeli, orta vadeli ve uzun vadeli trendleri tek bir tabloda izlemenize olanak tanır.
 
 3. Kullanıcı Dostu Arayüz ve Uyarılar: 
 
 Pozitif ve negatif ayrışmaları tespit ettiğinde uyarılar oluşturur.
 Kullanıcı tanımlı eşiklere göre aşırı alım ve aşırı satım seviyelerini renk kodlarıyla gösterir.
 
 Nasıl Kullanılır 
 
 İzlemek istediğiniz varlıkları ekleyin (en fazla 13 adet).
 Pivot ayarlarını yapılandırarak tespit işlemini optimize edin.
 RSI eşik seviyelerini belirleyin ve uyarıları etkinleştirin.
LibraryCOT_NZLibrary   "LibraryCOT_NZ" 
This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
 rootToCFTCCode(root) 
  Accepts a futures root and returns the relevant CFTC code.
  Parameters:
     root (simple string) : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
  Returns: The  part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
 currencyToCFTCCode(currency) 
  Converts a currency string to its corresponding CFTC code.
  Parameters:
     currency (simple string) 
  Returns: The  corresponding to the currency, if one exists.
 optionsToTicker(includeOptions) 
  Returns the  part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
  Parameters:
     includeOptions (simple bool) : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
  Returns: The  part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
 metricNameAndDirectionToTicker(metricName, metricDirection) 
  Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
  Parameters:
     metricName (simple string) : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
     metricDirection (simple string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
  Returns: The  part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
 typeToTicker(metricType) 
  Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
  Parameters:
     metricType (simple string) : Metric type. Accepted values are: "All", "Old", "Other".
  Returns: The  part of a COT ticker.
 convertRootToCOTCode(mode, convertToCOT) 
  Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
  Parameters:
     mode (simple string) : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
     convertToCOT (simple bool) : "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
  Returns: If `convertToCOT` is `true`, the  part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
 COTTickerid(COTType, CFTCCode, includeOptions, metricName, metricDirection, metricType) 
  Returns a valid TradingView ticker for the COT symbol with specified parameters.
  Parameters:
     COTType (simple string) : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
     CFTCCode (simple string) 
     includeOptions (simple bool) : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
     metricName (simple string) : One of the metric names listed in this library's chart.
     metricDirection (simple string) : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
     metricType (simple string) : Type of the metric. Possible values: "All", "Old", and "Other".
  Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
Delta ZigZag [LuxAlgo]The  Delta ZigZag  indicator is focused on volume analysis during the development of ZigZag lines. Volume data can be retrieved from a Lower timeframe (LTF) or real-time Tick data.
Our Delta ZigZag publication can be helpful in detecting indications of a trend reversal or potential weakening/strengthening of the trend.
This indicator by its very nature backpaints, meaning that the displayed components are offset in the past.
🔶  USAGE 
  
The  ZigZag line  is formed by connecting  Swings , which can be set by adjusting the  Left  and  Right  settings.
 
 Left  is the number of bars for evaluation at the left of the evaluated point.
 Right  is the number of bars for evaluation at the right of the evaluated point.
 
A valid  Swing  is a value higher or lower than the bars at the  left/right .
A higher  Left  or  Right  set number will generally create broader ZigZag ( ZZ ) lines, while the drawing of the  ZZ line  will be delayed (especially when  Right  is set higher). On the other hand, when  Right  is set at 0,  ZZ line  are drawn quickly. However, this results in a hyperactive switching of the  ZZ  direction.
To ensure maximum visibility of values, we recommend using " Bars " from the " Bar's style " menu.
🔹  Volume examination 
The script provides two options for  Volume examination :
 
 Examination per ZigZag line 
 Examination per bar 
 
 Bullish Volume  is volume associated with a green bar ( close > open )
 Bearish Volume  is volume associated with a red bar ( close < open )
 Neutral Volume  (volume on a " close == open"  bar) is not included in this publication.
🔹  Examination per ZigZag line 
As long as the price moves in the same direction, the present  ZZ line  will continue. When the direction of the price changes, the bull/bear volume of the previous  ZZ line  is evaluated and drawn on the chart.
 
 The ZZ line is divided into two parts: a bullish green line and a bearish red line.
 The intercept of these two lines will depend on the ratio of bullish/bearish volume
 This ratio is displayed at the intercept as % bullish volume (Settings -> Show % Bullish Volume)
 
 * Note that we cannot draw between 2 bars. Therefore, if a ZZ line is only 1 bar long, the intercept will be at one of those 2 bars and not in between. The percentage can be helpful in interpreting bull/bear volume. 
  
In the example above (2 most right labels), you can see that an overlap of 2 labels is prevented, ensuring the ability to evaluate the bullish % volume of the  ZZ line .
The percentage will be colored green when more than 50%, red otherwise. The color will fade when the direction is contradictory; for example, 40% when the  ZZ line  goes up or 70% when the  ZZ line  falls.
More details can be visualized by enabling " Show " and choosing 1 of 3 options:
 
 Average Volume Delta/bar 
 Average Volume/bar 
 Normalised Volume Delta 
 
For both 'averages', the sum of " Volume "/" Volume Delta " of every bar on the  ZZ line  is divided by the number of bars (per  ZZ line ).
The " Normalised Volume Delta " is calculated by dividing the sum of " Delta Volume " by the sum of " Volume " (neutral volume not included), which is displayed as a percentage.
All three options will display a label at the last point of the  ZZ line  and be coloured similarly: green when the ratio bullish/bearish volume of the  ZZ line  is bullish and red otherwise. Here, the colour also fades when it is bullish, but the  ZZ line  falls or when it is bearish with a rising  ZZ line .
A tooltip at each label hints at the chosen option.
  
You can pick one of the options or combine them together.
  
  
🔹  Examination per bar 
Besides information about what's happening during the  ZZ line , information per bar can be visualized by enabling " Show Details " in  Settings .
  
 
 Split Volume per bar : show the sum of bullish (upV) and bearish (dnV) volume per bar
 Volume (bar) : Total Volume per bar (bullish + bearish volume, neutral volume not included)
 Δ Volume (bar) : Show Delta Volume (bullish - bearish volume)
 
🔹  Using Lower Timeframe Data 
  
The ZigZag lines using LTF data are colored brighter. Also note the  vertical line  where the LTF data starts and the gap between  ZZ lines  with LTF data and without.
When " LTF " is chosen for the " Data from: " option in  Settings , data is retrieved from Lower Timeframe bars (default 1 minute). When the LTF setting is higher than the current chart timeframe, the LTF period will automatically be adjusted to the current timeframe to prevent errors. 
  
As there is a 100K limit to the number of  LTF intrabars  that can be analyzed by a script, this implies the higher the difference between LTF and current TF; the fewer  ZZ lines  will be seen.
🔹  Using real-time tick data 
  
The principles are mostly the same as those of LTF data. However, in contrast with LTF data, where you already have LTF  ZZ lines  when loading the script, real-time tick data-based  ZZ lines  will only start after loading the chart. 
  
Changing the settings of a ticker will reset everything. However, returning to the same settings/ticker would show the cached data again.
  
Here, you can see that changing settings reset everything, but returning after 2 minutes to the initial settings shows the cached data. Don't expect it to be cached for hours or days, though.
🔶  DETAILS 
The timeframe used for LTF data should always be the same or lower than the current TF; otherwise, an error occurs. This snippet prevents the error and adjusts the LTF to the current TF when LTF is too high:
 
res  = input.timeframe('1')
res := timeframe.from_seconds(  math.min( timeframe.in_seconds(timeframe.period), timeframe.in_seconds(res) )  )
 
🔶  SETTINGS 
 
 Data from:  LTF  (Lower TimeFrame) or  Ticks  (Real-time ticks)
 Res: Lower TimeFrame (only applicable when choosing  LTF )
 Option: choose " high/low " or " close " for Swing detection
 
🔹  ZigZag 
 
 Left: Lookback period for Swings
 Right: Confirmation period after potential Swing
 
🔹  ZigZag Delta 
 
 Show % Bullish Volume : % bullish volume against total volume during the ZZ line
 Show: 
 
 
 Average Volume Delta/bar
 Average Volume/bar
 Normalised Volume Delta
 
See  USAGE  for more information 
🔹  Bar Data 
 
 Split Volume per bar: shows the sum of bullish ( upV ) and bearish ( dnV ) volume per bar
 Volume (bar): Total Volume per bar (bullish + bearish volume, neutral volume not included)
 Δ Volume (bar): Show  Volume Delta  (bullish - bearish volume)
ETFHoldingsLibLibrary   "ETFHoldingsLib" 
 spy_get() 
  : pulls SPY ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 qqq_get() 
  : pulls QQQ ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 arkk_get() 
  : pulls ARKK ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 xle_get() 
  : pulls XLE ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 brk_get() 
  : pulls BRK ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 ita_get() 
  : pulls ITA ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 iwm_get() 
  : pulls IWM ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 xlf_get() 
  : pulls XLF ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 xlv_get() 
  : pulls XLV ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vnq_get() 
  : pulls VNQ ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 xbi_get() 
  : pulls XBI ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 blcr_get() 
  : pulls BLCR ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vgt_get() 
  : pulls VGT ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vwo_get() 
  : pulls VWO ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vig_get() 
  : pulls VIG ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vug_get() 
  : pulls VUG ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vtv_get() 
  : pulls VTV ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
 vea_get() 
  : pulls VEA ETF data
  Returns: : tickers held (string array), percent ticker holding (float array), sectors (string array), percent secture positioning (float array)
LibraryCOTLibrary   "LibraryCOT" 
This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
 rootToCFTCCode(root) 
  Accepts a futures root and returns the relevant CFTC code.
  Parameters:
     root : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
  Returns: The  part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
 currencyToCFTCCode(curr) 
  Converts a currency string to its corresponding CFTC code.
  Parameters:
     curr : Currency code, e.g., "USD" for US Dollar.
  Returns: The  corresponding to the currency, if one exists.
 optionsToTicker(includeOptions) 
  Returns the  part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
  Parameters:
     includeOptions : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
  Returns: The  part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
 metricNameAndDirectionToTicker(metricName, metricDirection) 
  Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
  Parameters:
     metricName : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
     metricDirection : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
  Returns: The  part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
 typeToTicker(metricType) 
  Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
  Parameters:
     metricType : Metric type. Accepted values are: "All", "Old", "Other".
  Returns: The  part of a COT ticker.
 convertRootToCOTCode(mode, convertToCOT) 
  Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
  Parameters:
     mode : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
     convertToCOT : "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
  Returns: If `convertToCOT` is `true`, the  part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
 COTTickerid(COTType, CTFCCode, includeOptions, metricName, metricDirection, metricType) 
  Returns a valid TradingView ticker for the COT symbol with specified parameters.
  Parameters:
     COTType : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
     CTFCCode : The  for the asset, e.g., wheat futures (root "ZW") have the code "001602".
     includeOptions : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
     metricName : One of the metric names listed in this library's chart.
     metricDirection : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction". 
     metricType : Type of the metric. Possible values: "All", "Old", and "Other".
  Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
LibraryCOT█  OVERVIEW 
This library is a Pine programmer's tool that provides functions to access Commitment of Traders (COT) data for futures. Four of our scripts use it:
 •  Commitment of Traders: Legacy Metrics 
 •  Commitment of Traders: Disaggregated Metrics 
 •  Commitment of Traders: Financial Metrics 
 •  Commitment of Traders: Total 
If you do not program in Pine and want to use COT data, please see the indicators linked above.
█  CONCEPTS 
 Commitment of Traders (COT) data  is tallied by the  Commodity Futures Trading Commission (CFTC) , a US federal agency that oversees the trading of derivative markets such as futures in the US. It is weekly data that provides traders with information about  open interest  for an asset. The CFTC oversees derivative markets traded on different exchanges, so COT data is available for assets that can be traded on CBOT, CME, NYMEX, COMEX, and ICEUS.
Accessing COT data from a Pine script requires the generation of a ticker ID string for use with  request.security() . The ticker string must be encoded in a special format that includes both CFTC and TradingView-specific content. The format of the ticker IDs is somewhat complex; this library's functions make their generation easier. Note that if you know the COT ticker ID string for specific data, you can enter it from the chart's "Symbol Search" dialog box.
A ticker for COT data in Pine has the following structure:
 COT:__<_metricDirection><_metricType> 
where an underscore prefixing a component name inside <> is only included if the component is not a null string, and:
   
    Is a digit representing the type of the COT report the data comes from: "" for legacy COT data, "2" for disaggregated data and "3" for financial data.
   
    Is a six digit code that represents a commodity. Example: wheat futures (root "ZW") have the code "001602".
   
    Is either "F" if the report data should exclude Options data, or "FO" if such data is included.
   
    Is the TradingView code of the metric. This library's `metricNameAndDirectionToTicker()` function creates both 
    the  and  components of a COT ticker from the metric names and directions listed in the above chart.
    The different metrics are explained in the CFTC's  Explanatory Notes .
   
    Is the direction of the metric: "Long", "Short", "Spreading" or "No direction". 
    Not all directions are applicable to all metrics. The valid ones are listed next to each metric in the above chart.
   
    Is the type of the metric, possible values are "All", "Old" and "Other". 
    The difference between the types is explained in the "Old and Other Futures" section of the CFTC's  Explanatory Notes .
As an example, the Legacy report Open Interest data for ZW futures (options included) in the old standard has the ticker "COT:001602_FO_OI_OLD". The same data using the current standard without futures has the ticker "COT:001602_F_OI".
█  USING THE LIBRARY 
The first functions in the library are helper functions that generate components of a COT ticker ID. The last function, `COTTickerid()`, is the one that generates the full ticker ID string by calling some of the helper functions. We use it like this in our example:
 exampleTicker = COTTickerid(
                     COTType = "Legacy",
                     CFTCCode = convertRootToCOTCode("Auto"),
                     includeOptions = false, 
                     metricName = "Open Interest",
                     metricDirection = "No direction",
                     metricType = "All")
 
This library's chart displays the valid values for the `metricName` and `metricDirection` arguments. They vary for each of the three types of COT data (the `COTType` argument). The chart also displays the COT ticker ID string in the `exampleTicker` variable.
 Look first. Then leap.  
The library's functions are:
 rootToCFTCCode(root)  
  Accepts a futures root and returns the relevant CFTC code.
  Parameters:
     root : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
  Returns: The  part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
 currencyToCFTCCode(curr)  
  Converts a currency string to its corresponding CFTC code.
  Parameters:
     curr : Currency code, e.g., "USD" for US Dollar.
  Returns: The  corresponding to the currency, if one exists.
 optionsToTicker(includeOptions)  
  Returns the  part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
  Parameters:
     includeOptions : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
  Returns: The  part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
 metricNameAndDirectionToTicker(metricName, metricDirection)  
  Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
  Parameters:
     metricName : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
     metricDirection : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction".
      Valid values vary with metrics. Invalid values will cause a runtime error.
  Returns: The  part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", 
    or "TC_L" for "Traders Commercial" and "Long".
 typeToTicker(metricType)  
  Converts a metric type into one component required to build a valid COT ticker ID. 
  See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
  Parameters:
     metricType : Metric type. Accepted values are: "All", "Old", "Other".
  Returns: The  part of a COT ticker.
 convertRootToCOTCode(mode, convertToCOT)  
  Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. 
  Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
  Parameters:
     mode : A string determining how the function will work. Valid values are:
      "Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
      "Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
      "Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
      "Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
     convertToCOT : "bool" value that, when `true`, causes the function to return a CFTC code. 
      Otherwise, the root or currency information is returned. Optional. The default is `true`.
  Returns: If `convertToCOT` is `true`, the  part of a COT ticker ID string. 
    If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
 COTTickerid(COTType, CTFCCode, includeOptions, metricName, metricDirection, metricType)  
  Returns a valid TradingView ticker for the COT symbol with specified parameters.
  Parameters:
     COTType : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
     CTFCCode : The  for the asset, e.g., wheat futures (root "ZW") have the code "001602".
     includeOptions : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
     metricName : One of the metric names listed in this library's chart.
     metricDirection : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction". 
     metricType : Type of the metric. Possible values: "All", "Old", and "Other".
  Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
█ AVAILABLE METRICS
Different COT types provide different metrics. The table of all metrics available for each of the types can be found below.
 
+------------------------------+------------------------+
|  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            |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names |       Directions       |
+-----------------------------------+------------------------+
| Open Interest                     | No Direction           |
| Producer Merchant Positions       | Long, Short            |
| Swap Positions                    | Long, Short, Spreading |
| Managed Money Positions           | Long, Short, Spreading |
| Other Reportable Positions        | Long, Short, Spreading |
| Total Reportable Positions        | Long, Short            |
| Nonreportable Positions           | Long, Short            |
| Traders Total                     | No Direction           |
| Traders Producer Merchant         | Long, Short            |
| Traders Swap                      | Long, Short, Spreading |
| Traders Managed Money             | 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            |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| 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            |
+-------------------------------+------------------------+
 
Delay Estimatorthis script can be used to adjust one of the free realtime tickers (such as SPX500, NAS100) to "look" like one of the delayed futures tickers (such as ES1!, NQ1!). This basically allows us to get an estimate of the realtime futures ticker price.
it uses bollinger bands to adjust the volatility and offset of the realtime ticker
it also provides a decimator to reduce the price into ticks, since futures often use 4 ticks per point
Buy And Hold Performance Screener - [JTCAPITAL]Buy And Hold Performance Screener –   is a script designed to track and display multi-asset “buy and hold” performance curves and performance statistics over defined timeframes for selected symbols. It doesn’t attempt to time entries or exits; rather, it shows what would happen if one simply bought the asset at the defined start date and held it.
 The indicator works by calculating in the following steps: 
 
   Start Date Definition 
The script begins by reading an input for the start date. This defines the bar from which the equity curves begin.
   Symbol Definitions & Close Price Retrieval 
The script allows the user to specify up to ten tickers. For each ticker it uses request.security() on the “1D” timeframe to retrieve the daily close price of that symbol.
   Plot Enable Inputs 
For each ticker there is an input boolean controlling whether the equity curve for that ticker should be plotted.
   Asset Name Cleaning 
The helper function clean_name(string asset) => … takes the asset string (e.g., “CRYPTO:SOLUSD”) and manipulates it (via string splitting and replacements) to derive a cleaned short name (e.g., “SOL”). This name is used for visuals (labels, table headers).
   Equity Curve Calculation (“HODL”) 
The helper function f_HODL(closez) defines a variable equity that assumes a starting equity of 1 unit at the start date and then multiplies by the ratio of each bar’s close to the prior bar’s close: i.e. daily compounding of returns.
   Performance Metrics Calculation 
The helper function f_performance(closez) calculates, for each symbol’s close series, the percentage change of the current close relative to its close 30 days ago, 90 days ago, 180 days ago, 1 year ago (365 days), 2 years ago (730 days) and 3 years ago (1095 days).
   Equity Curve Plots 
For each ticker, if the corresponding plot input is true, the script assigns a plotted variable equal to the equity curve value. Its then drawing each selected equity curve on the chart, each in a distinct color.
   Table Construction 
If the plottable input is true, the script constructs a table and populates it with rows and column corresponding to the assigned tickers and the set 6 timeframes used for display.
 Buy and Sell Conditions: 
Since this is strictly a “buy-and-hold” performance screener, there are no explicit buy or sell signals generated or plotted. The script assumes: buy at the defined start_date, hold continuously to present. There are no filters, no exit logic, no take-profit or stop-loss. The benefit of this approach is to provide a clean benchmark of how selected assets would have performed if one simply adopted a passive “buy & hold” approach from a given start date.
 Features and Parameters: 
 start_date (input.time) : Defines the date from which performance and equity curves begin.
 ticker1 … ticker10 (input.symbol) : User-selectable asset symbols to include in the screener.
 plot1 … plot10 (input.bool) : Boolean flags to enable/disable plotting of each asset’s equity curve.
 plottable (input.bool) : Flag to enable/disable drawing the performance table.
 Colored plotting + Labels for identifying each asset curve on the chart. 
 Specifications: 
Here is a detailed breakdown of every calculation/variable/function used in the script and what each part means:
 start_date 
This is defined via input.time(timestamp("1 Jan 2025"), title = "Start Date"). It allows the user to pick a specific calendar date from which the equity curves and performance calculations will start.
 ticker1 … ticker10 
These inputs allow the user to select up to ten different assets (symbols) to monitor. The script uses each of these to fetch daily close prices.
 plot1 … plot10 
Boolean inputs controlling which of the ten asset equity curves are plotted. If plotX is true, the equity curve for ticker X will be visible; otherwise it will be not plotted. This gives the user flexibility to include or exclude specific assets on the chart.
Returns the cleaned asset short name.
This provides friendly text labels like “BTC”, “ETH”, “SOL”, etc., instead of full symbol codes.
The choice of distinct colours for each asset helps differentiate curves visually when multiple assets are overlaid.
 Colour definitions 
Variables color1…color10 are explicitly defined via color.rgb(r,g,b) to give each asset a unique colour (e.g., red, orange, yellow, green, cyan, blue, purple, pink, etc.).
 What are the benefits of combining these calculations? 
By computing equity curves for multiple assets from the same start date and overlaying them, you can visualise comparative performance of different assets under a uniform “buy & hold” assumption.
The performance table adds multi-horizon returns (30 D, 90 D, 180 D, 1 Y, 2 Y, 3 Y) which helps the user see both short-term and longer-term performance without having to manually compute returns.
The use of daily close data via request.security(..., "1D") removes dependency on the chart’s timeframe, thereby standardising the comparison across assets.
The equity curve and table together provide both visual (curve) and numerical (table) summaries of performance, making it easier to spot trends, divergences, and cross-asset comparisons at a glance.
Because it uses compounding (equity := equity * (closez / closez )), the curves reflect the real growth of a 1-unit investment held over time, rather than only simple returns.
The labelling of curves and the color-coding make the multi-asset overlay easier to interpret.
Using a clean start date ensures that all curves begin at the same point (1 unit at start_date), making relative performance intuitive.
Because of this, the script is useful as a benchmarking tool: rather than trying to pick entries or exit points, you can simply compare “what if I had held these assets since Jan 1 2025” (or your chosen date), and see which assets out-/under-performed in that period. It helps an investor or trader evaluate the long-term benefits of passive vs. active management, or of allocation decisions.
Please note:
The script assumes continuous daily data and does not account for dividends, fees, slippage, or tax implications.
It does not attempt to optimise timing or provide trading signals.
Returns prior to the start date are ignored (equity only begins once time >= start_date).
For newly listed assets with fewer than 365 or 730 or 1095 days of history, the longer-horizon returns may return na or misleading values.
Because it uses request.security() without specifying lookahead, and on “1D” timeframe, it complies with standard usage but you should verify there is no look-ahead bias in your particular setup.
 ENJOY!
Outside Candle Session Breakout [CHE]Outside Candle Session Breakout   
Session - anchored HTF levels for clear market-structure and precise breakout context
  Summary 
This indicator is a relevant market-structure tool. It anchors the session to the first higher-timeframe bar, then activates only when the second bar forms an outside condition. Price frequently reacts around these anchors, which provides precise breakout context and a clear overview on both lower and higher timeframes. Robustness comes from close-based validation, an adaptive volatility and tick buffer, first-touch enforcement, optional retest, one-signal-per-session, cooldown, and an optional trend filter.
Pine version: v6. Overlay: true.
  Motivation: Why this design? 
Short-term breakout tools often trigger during noise, duplicate within the same session, or drift when volatility shifts. The core idea is to gate signals behind a meaningful structure event: a first-bar anchor and a subsequent outside bar on the session timeframe. This narrows attention to structurally important breaks while adaptive buffering and debouncing reduce false or mid-run triggers.
  What’s different vs. standard approaches? 
 Baseline: Simple high-low breaks or fixed buffers without session context.
 Architecture: Session-anchored first-bar high/low; outside-bar gate; close-based confirmation with an adaptive ATR and tick buffer; first-touch enforcement; optional retest window; one-signal-per-session and cooldown; optional EMA trend and slope filter; higher-timeframe aggregation with lookahead disabled; themeable visuals and a range fill between levels.
 Practical effect: Cleaner timing at structurally relevant levels, fewer redundant or late triggers, and better multi-timeframe situational awareness.
  How it works (technical) 
 The chart timeframe is mapped to an analysis timeframe and a session timeframe.
 The first session bar defines the anchor high and low. The setup becomes active only after the next bar forms an outside range relative to that first bar.
 While active, the script tracks these anchors and checks for a breakout beyond a buffered threshold, using closing prices or wicks by preference.
 The buffer scales with volatility and is limited by a minimum tick floor. First-touch enforcement avoids mid-run confirmations.
 Optional retest requires a pullback to the raw anchor followed by a new close beyond the buffered level within a user window.
 Optional trend gating uses an EMA on the analysis timeframe, including an optional slope requirement and price-location check.
 Higher-timeframe data is requested with lookahead disabled. Values can update during a forming higher-timeframe bar; waiting and confirmation mitigate timing shifts.
  Parameter Guide 
Enable Long / Enable Short — Direction toggles. Default: true / true. Reduces unwanted side.
Wait Candles — Minimum bars after outside confirmation before entries. Default: five. More waiting increases stability.
Close-based Breakout — Confirm on candle close beyond buffer. Default: true. For wick sensitivity, disable.
ATR Buffer — Enables adaptive volatility buffer. Default: true.
ATR Multiplier — Buffer scaling. Default: zero point two. Increase to reduce noise.
Ticks Buffer — Minimum buffer in ticks. Default: two. Protects in quiet markets.
Cooldown Bars — Blocks new signals after a trigger. Default: three.
One Signal per Session — Prevents duplicates within a session. Default: true.
Require Retest — Pullback to raw anchor before confirming. Default: false.
Retest Window — Bars allowed for retest completion. Default: five.
HTF Trend Filter — EMA-based gating. Default: false.
EMA Length — EMA period. Default: two hundred.
Slope — Require EMA slope direction. Default: true.
Price Above/Below EMA — Require price location relative to EMA. Default: true.
Show Levels / Highlight Session / Show Signals — Visual controls. Default: true.
Color Theme — “Blue-Green” (default), “Monochrome”, “Earth Tones”, “Classic”, “Dark”.
Time Period Box — Visibility, size, position, and colors for the info box. (Optional)
  Reading & Interpretation 
 The two level lines represent the session’s first-bar high and low. The filled band illustrates the active session range.
 “OUT” marks that the outside condition is confirmed and the setup is live.
 “LONG” or “SHORT” appears only when the breakout clears buffer, debounce, and optional gates.
 Background tint indicates sessions where the setup is valid.
 Alerts fire on confirmed long or short breakout events.
  Practical Workflows & Combinations 
 Trend-following: Keep close-based validation, ATR buffer near the default, one-signal-per-session enabled; add EMA trend and slope for directional bias.
 Retest confirmation: Enable retest with a short window to prioritize cleaner continuation after a pullback.
 Lower-timeframe scalping: Reduce waiting and cooldown slightly; keep a small tick buffer to filter micro-whips.
 Swing and position context: Increase ATR multiplier and waiting; maintain once-per-session to limit duplicates.
  Timeframe Tiers and Trader Profiles 
The script adapts its internal mapping based on the chart timeframe:
 Under fifteen minutes → Analysis: one minute; Session: sixty minutes. Useful for scalpers and high-frequency intraday reads.
 Between fifteen and under sixty minutes → Analysis: fifteen minutes; Session: one day. Suits day traders who need intraday alignment to the daily session.
 Between sixty minutes and under one day → Analysis: sixty minutes; Session: one week. Serves intraday-to-swing transitions and end-of-day planning.
 Between one day and under one week → Analysis: two hundred forty minutes; Session: two weeks. Fits swing traders who monitor multi-day structure.
 Between one week and under thirty days → Analysis: one day; Session: three months. Supports position traders seeking quarterly context.
 Thirty days and above → Analysis: one day; Session: twelve months. Provides a broad annual anchor for macro context.
These tiers are designed to keep anchors meaningful across regimes while preserving responsiveness appropriate to the trader profile.
  Behavior, Constraints & Performance 
 Signals can be validated on closed bars through close-based logic; enabling this reduces intrabar flicker.
 Higher-timeframe values may evolve during a forming bar; waiting parameters and the outside-bar gate reduce, but do not remove, this effect.
 Resource footprint is light; the script uses standard indicators and a single higher-timeframe request per stream.
 Known limits: rare setups during very quiet periods, sensitivity to gaps, and reduced reliability on illiquid symbols.
  Sensible Defaults & Quick Tuning 
 Start with close-based validation on, ATR buffer on with a multiplier near zero point two, tick buffer two, cooldown three, once-per-session on.
 Too many flips: increase the ATR multiplier and cooldown; consider enabling the EMA filter and slope.
 Too sluggish: reduce the ATR multiplier and waiting; disable retest.
 Choppy conditions: keep close-based validation, increase tick buffer, shorten the retest window.
  What this indicator is—and isn’t 
This is a visualization and signal layer for session-anchored breakouts with stability gates. It is not a complete trading system, risk framework, or predictive engine. Combine it with structured analysis, position sizing, and disciplined risk controls.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino 
Free Stock ScreenerMissing great trade opportunities is annoying, and unless you have 12 screens or only trade one market, you are missing a lot of trades. To fix that, we created this free stock screener so you get notified instantly of potential great trading conditions in real time, right on your chart.
You get notified of trading benchmarks being met by the value being displayed on the scanner as well as a color change so that it grabs your attention and makes you aware that you should take a look at the other market and look for a potential trade. It also has built in alerts so you can have an alert notification go off when any of your trading conditions are met instead of needing to watch the scanner for color changes.
The screener will change the ticker symbol background color to red green when price is above or below the previous daily range and above or below both VWAPs. This signals that the ticker is trending, which typically means it is a great time to trade that market and follow the trend.
This free stock screener allows you to scan up to 10 different markets at the same time for various different conditions so you always know what is going on with your favorite trading symbols. If you want to scan more tickers, just add the indicator to your chart again and change the table position to the other side of the screen and update the tickers on the 2nd screener, allowing you to have 20 tickers at a time.
The scanner can be fully customized by changing the markets that it screens and turning on or off as many of them as you would like. You can also turn on or off any of the different data sets so that you only get information about trading conditions that matter to you.
The screener can provide data on any type of market, such as stocks, crypto, futures, forex and more. Each ticker can be adjusted to whatever market you would like it to scan for data in the settings panel, the only limitation is that it will not provide data for the VWAP and volume trend score if the ticker you are screening does not provide volume data.
 Screener Features 
The scanner will provide the following types of data for each ticker that is turned on:
 
 Volume  - Provides a volume score compared to the average volume and notifies you of higher than normal volume and volume spikes on individual bars by changing colors.
 Volatility  - Provides a volatility score compared to the average volatility and notifies you of higher than normal volatility by changing colors.
 Oscillator  - Choose between the RSI or CCI. The value of that oscillator will be displayed and will notify you when values are in extreme ranges such as overbought or oversold conditions according to the threshold values you enter in the settings panel. When those thresholds have been breached, you will be notified by it changing color.
 Big Candles  - Compares the current candle to average previous candle sizes, and changes color to notify you of big candles including a big top wick, big bottom wick, big candle body and big candle high to low range.
 Daily Level Touches & Trends  - Calculates and displays various daily candle and intraday open price levels that act as support and resistance. Notifies you when price is touching any of the daily levels that are turned on. The levels you can have on are as follows: previous day high, previous day low or previous day open. It also will notify you when price is touching the current day’s open, NY 930am open, Asia 8pm open, London 2am open and NY midnight 12am open. It will also say “Above” if price is above the previous day’s high or it will say “Below” if price is below the previous day’s low. The color of the cell will also change when a level touch is happening or price is above the previous day high or below the previous day low.
 VWAP  - Choose from 2 different VWAP lengths, default settings are daily and weekly VWAPs. You will get notified if price touches either of the VWAPs and they will also say “Above” or “Below” if price is currently above or below each VWAP.
 
 How To Use The Screener To Help You Trade 
The main purpose of the screener is to scan other markets and notify you of potential good trading opportunities such as price bouncing off of the daily levels or VWAPs. It can also be used to know when price is trending according to the VWAPs and daily levels. Lastly, you can use it to know how the volume and volatility trends are currently which gives you more confidence in taking a trade with this data when volume and volatility are present.
 Volume Score 
When volume is high, this represents a good time to trade because there are many market participants and price is likely to be volatile while there is high volume which can present a lot of good trade setups for you to take. 
The volume score shown on the screener measures the current volume trend compared to previous volume trends and calculates that into a score based on 100 being the same as the previous volume trend. So any value above 100 means it is high volume and any value less than 100 means it is lower volume than normal.
In the settings panel, you can adjust the volume threshold that needs to be met for a volume notification to show up. The default setting is at 120, so you will get notified when the current volume trend score is 120 or higher or you can adjust that threshold value to whatever value you prefer.
It also will notify you when there is a volume spike on the current bar. This is determined by calculating an average of the recent volume totals and then checking to see if the current bar is greater than or equal to that average multiplied by 3. So if a single bar has volume that is greater than 3 times what the average volume is, then you will get a notification that says “Spike” to make you aware of that volume spike.
The volume trend threshold, volume spike multiplier and lookback length for the average volume used in volume spike calculations can all be adjusted in the settings panel to fit your desired preferences.
 Volatility Score 
High volatility can mean it is a great time to trade because the market is moving quickly and providing large enough movements that you can get in and out in a short amount of time, while still accruing decent sized trade PnL. 
The volatility score will calculate the current volatility for each market compared to previous conditions and then divide the current volatility by the average volatility to give you a volatility score. Anything over 100 means the market is decently volatile and you should look at that market to find potential trade setups to execute on. Anything below 100 means the market is not very volatile and it is usually best to just wait until volatility returns before you start trading again.
The screener will notify you when the volatility score is above the threshold you set. The default value is set to 90, but can be adjusted to your preference. Pay attention to any market that shows an alert and take a look at that chart because the high volatility may present a good trade setup for you in the near future.
 Oscillator Score 
The oscillator data can be switched between Relative Strength Index(RSI) and Commodity Channel Index(CCI). 
The RSI provides a value between 0 and 100 that indicates the momentum and strength of the recent price action. Many traders use the extremes of the 0-100 range to signal overbought or oversold conditions and use that as a sign to look for price to reverse in the near future. The typical values used for this and the default settings to provide notifications are: 70 for overbought and 30 for oversold. The scanner will notify you when the RSI value is considered overbought or oversold so you know to take a look at the chart and analyze if it is ready for a trade to be taken.
The CCI provides a value that can be used to determine the trend strength of the underlying asset when the oscillator moves above 100 or below -100. These extreme values are outside of the normal accumulation range and signify that price is moving strongly in that direction so it may be a good time to take a trade in the direction of the trend. The scanner will show you the value of the CCI for each market and notify you if that value is above 100 or below -100.
Both RSI and CCI settings can be adjusted in the settings panel to your desired settings so you have the exact oscillator settings you prefer to use as well as the exact values that you want to use for being notified.
 Big Candles 
Big candles can mean that many traders are buying or selling at the same time and many times indicate a good signal to trade in that same direction. That is why we included this calculation in the screener, so you are always aware when a large candle prints. 
It calculates the average size of the recent candles and then uses that average as the benchmark to determine if the current candle is considered big and worthy of notifying you to take a look at that chart. 
You can adjust the multiplier used for the big candle threshold to whatever you desire, but the default setting is 3 which means the candle will be considered big and notify you if it is 3 times as large as an average candle.
The big candles data will track the following candle values and notify you with these labels:
 
 High to Low candle size = HL
 Candle Body from open to close candle size = OC
 Top Wick size = TW
 Bottom Wick size = BW
 
 Daily Level Touches & Trend 
Daily level touches are excellent levels to watch for price to bounce because they often act as support and resistance levels for intraday trading. The scanner will track each market and notify you when the current candle is touching any of the daily levels that you have turned on in the settings panel.
The main levels that are turned on by default and are useful for all markets and how they will be labeled on the scanner are as follows:
 
 Previous Day High = High
 Previous Day Low = Low
 Previous Day Open = < Open
 Previous Day Close = Close
 Current Day Open = Open
 
We also included some extra levels that are useful for futures traders. They are as follows:
 
 NY 930am Open = 930am
 NY 12am Midnight Open = 12am
 Asia Open at 8pm NY time = Asia
 London Open at 2am NY Time = London
 
Watch how price reacts to these levels and then trade the bounces off of these levels if the price action confirms that it is going to respect that level.
When price is currently above the previous day high, the scanner will say “Above” and show a green color, indicating a bullish trend and that price is above the previous daily candle’s high.
When price is currently below the previous day low, the scanner will say “Below” and show a red color, indicating a bearish trend and that price is below the previous daily candle’s low.
Pay attention to when price is trending above or below the previous daily candle as those trends can provide excellent trend trading opportunities.
The daily levels that you have turned on in the settings will also show as lines on the chart and include a label next to them, identifying each level so you know what each line represents. You can turn on or off all of the lines shown on the chart in the main settings or turn them off one by one in the style panel of the settings. Labels can also be turned on or off for all of the lines in the main settings panel. You can adjust the label positioning in the Label Offset section of the settings panel.
 VWAP Touches & Trend 
VWAP stands for volume weighted average price and is a very popular tool that traders use to determine trend direction based on volume as well as an excellent level to trade price bounces off of.
The typical VWAP time period used is Daily, which means the volume weighted average price will reset at the beginning of a new day. We set the first VWAP to be the daily VWAP by default and the second one to be the weekly VWAP. You can adjust both of the time periods to be any of the provided time lengths that you choose.
The screener will show “Above” with a green background color when price is above the VWAP, indicating a bullish trend. It will show “Below” with a red background color when price is below the VWAP, indicating a bearish trend. When both VWAPs are showing Above or Below, you can expect price to trend in that direction, so look for pullbacks you can trade in the direction of the trend. If the VWAPs are showing different directions, then you should expect to bounce back and forth between the VWAPs, but be careful and watch out for price to break beyond either one and start a trend.
When the current candle is touching the VWAP, the scanner will change colors and say VWAP to notify you that price is touching the VWAP and you should look at that chart and analyze the market for a potential bounce off of the VWAP to trade.
 Trending Market Signals 
Strong trends are excellent markets to trade and can many times provide excellent trading opportunities that don’t require expert price action reading skills to be able to take winning trades from. That is why we included a signal to notify you of a strong trending market. 
The strong trending market will show up as a green or red background color for the ticker name. If the color of the ticker name is green, it is notifying you that the price is above the previous daily high, above VWAP 1 and above VWAP 2 and is a good market to look for bullish trend trades. If the color of the ticker name is red, it is notifying you that the price is below the previous daily low, below VWAP 1 and below VWAP 2 and is a good market to look for bearish trend trades. 
 Changing The Tickers It Scans 
To change the tickers that the indicator scans, scroll near the bottom of the settings panel and select the ticker symbol you want to update and then search for the exact symbol you want to use. If you want to scan less tickers, then just turn some of the tickers off that you don’t need.
 Scanning More Than 10 Tickers 
If you want to scan more than 10 tickers, you can add the scanner to your chart again and then just change the table position to the other side of the screen. This will allow you to scan 10 more tickers that will show up separately. Then if you want even more, just add the indicator to your chart again and update the table position until you have as many markets as you want. The table position setting can be found at the bottom of the main settings panel.
 Alerts 
The screener has alerts that can be used to notify you when any of the data set thresholds have been met or if price is touching one of the levels. You can set alerts for the following events:
 
 Bullish Trend Alert  - Price is above the previous daily high and above both VWAPs.
 Bearish Trend Alert  - Price is below the previous daily low and below both VWAPs.
 High Volume Alert  - Volume is higher than the threshold or a volume spike is detected.
 High Volatility Alert  - Volatility is higher than the threshold.
 Oscillator Is Extended Alert  - Oscillator value has exceeded the upper or lower threshold.
 Big Candle Alert  - A big candle has been detected.
 Daily Level Touch Alert  - One of the daily levels that is turned on is being touched.
 VWAP Touch Alert  - One of the 2 VWAPs are being touched.
 
An alert will trigger when any one of tickers on your scanner meets the alert conditions, so when you see the alert, you will need to go to your chart and look at the scanner to see which ticker it was and then navigate to that chart to look for potential trade setups.
The alerts will use the exact same settings you have configured in the settings panel to send you alert notifications. With normal settings, this could give you a lot of alerts, so if you only want alerts to fire when abnormal conditions are being met, try setting up a second screener on your chart that has very high threshold values and only has the most important level touches on. Then turn the setting "Do Not Show The Screener On The Chart" to off so the calculations will still run and fire alerts, but won't clog up your charts. This way you can only get alert notifications when major events happen but still have your normal screener settings available on your chart.
 Markets This Can Be Used On 
This screener uses the price action and volume data so you can use it to scan any type of market you would like as long as the ticker you are scanning has price and volume data feeds. If a market does not have volume data, then it will just show NaN in the volume row and the VWAP rows will not show anything.
Ultra Trade JournalThe  Ultra Trade Journal  is a powerful TradingView indicator designed to help traders meticulously document and analyze their trades. Whether you're a novice or an experienced trader, this tool offers a clear and organized way to visualize your trading strategy, monitor performance, and make informed decisions based on detailed trade metrics.
 Detailed Description 
The  Ultra Trade Journal  indicator allows users to input and visualize critical trade information directly on their TradingView charts.
.........
 
 User Inputs 
 Traders can specify entry and  exit prices , stop loss levels, and up to four take profit targets. 
.....
 Dynamic Plotting 
 Once the input values are set, the indicator automatically plots horizontal lines for entry, exit, stop loss, and each take profit level on the chart. These lines are visually distinct, using different colors and styles (solid, dashed, dotted) to represent each element clearly. 
.....
 Live Position Tracking 
 If enabled, the indicator can adjust the exit price in real-time based on the current market price, allowing traders to monitor live positions effectively. 
.....
 Tick Calculations 
 The script calculates the number of ticks between the entry price and each exit point (stop loss and take profits). This helps in understanding the movement required for each target and assessing the potential risk and reward. 
.....
 Risk-Reward Ratios 
 For each take profit level, the indicator computes the risk-reward (RR) ratio by comparing the ticks at each target against the stop loss ticks. This provides a quick view of the potential profitability versus the risk taken. 
.....
 Comprehensive Table Display 
 A customizable table is displayed on the chart, summarizing all key trade details. This includes the entry and exit prices, stop loss and take profit levels, tick counts, and their respective RR ratios. 
 Users can adjust the table's Position and text color to suit their preferences. 
.....
 Visual Enhancements 
 The indicator uses adjustable background shading between entry and stop loss/take profit lines to visually represent potential trade outcomes. This shading adjusts based on whether the trade is long or short, providing an intuitive understanding of trade performance. 
 
.........
Overall, the  Ultra Trade Journal  combines visual clarity with detailed analytics, enabling traders to keep a well-organized record of their trades and enhance their trading strategies through insightful data.
US Sentiment Index [CryptoSea]The  US Sentiment Index  is an advanced analytical tool designed for traders seeking to uncover patterns, correlations, and potential leading signals across key market tickers. This indicator surpasses traditional sentiment measures, providing a data-driven approach that offers deeper insights compared to conventional indices like the Fear and Greed Index.
 Key Features  
  
 Multi-Ticker Analysis:  Integrates data from a diverse set of market indicators, including gold, S&P 500, U.S. Dollar Index, Volatility Index, and more, to create a comprehensive view of market sentiment. 
 Customisable Sensitivity Settings:  Allows users to adjust the moving average period to fine-tune the sensitivity of sentiment calculations, adapting the tool to various market conditions and trading strategies. 
 Detailed Sentiment Scaling:  Utilises a 0-100 scale to quantify sentiment strength, with colour gradients that visually represent bearish, neutral, and bullish conditions, aiding in quick decision-making.
 
Below is an example where the sentiment index can give leading signals. We see a first sign of wekaness in the index as it drops below its moving average. Shortly after we see it dip below our median 50 level, another sign of weakeness. We see the SPX price action to take a hit following the sentiment index decrease.
  
 Tickers Used and Their Impact on Sentiment 
The impact of each ticker on sentiment can be bullish or bearish, depending on their behaviour:
 
 Gold (USGD):  Typically seen as a safe-haven asset, rising gold prices often indicate increased market fear or bearish sentiment. Conversely, falling gold prices can signal reduced fear and a shift towards bullish sentiment in riskier assets.
 S&P 500 (SPX):  A rising S&P 500 is usually a sign of bullish sentiment, reflecting confidence in economic growth and market stability. A decline, however, suggests bearish sentiment and a potential move towards risk aversion.
 U.S. Dollar Index (DXY):  A strengthening U.S. Dollar can be a sign of fear as investors seek safety in the dollar, which is bearish for risk assets. A weakening dollar, on the other hand, can signal bullish sentiment as capital flows into riskier assets.
 Volatility Index (VIX):  Known as the "fear gauge," a rising VIX indicates increased market fear and bearish sentiment. A falling VIX suggests a calm, bullish market environment.
 Junk Bonds (JNK):  Rising junk bond prices often reflect bullish sentiment as investors take on more risk for higher returns. Conversely, falling junk bond prices signal increased fear and bearish sentiment.
 Long-Term Treasury Bonds (TLT):  Higher prices for long-term treasuries usually indicate a flight to safety, reflecting bearish sentiment. Lower prices suggest a shift towards riskier assets, indicating bullish sentiment.
 Financial Sector ETF (XLF):  Strength in the financial sector is typically bullish, indicating confidence in economic conditions. Weakness in this sector can reflect bearish sentiment and concerns about financial stability.
 Unemployment Rate (USUR):  A rising unemployment rate is a bearish signal, indicating economic weakness. A declining unemployment rate is bullish, reflecting economic strength and job growth.
 U.S. Interest Rates (USINTR, USIRYY):  Higher interest rates can be bearish, as they increase borrowing costs and reduce spending. Lower rates are generally bullish, promoting economic growth and risk-taking.
 
 How it Works  
  
 Sentiment Calculation:  The US Sentiment Index combines data from multiple tickers, calculating sentiment by scaling the distance from their respective moving averages. Each asset's behaviour is interpreted within the context of market fear or greed, providing a refined sentiment reading that adjusts dynamically.
 Market Strength Analysis:  When the index is above 50 and also above its moving average, it indicates particularly strong or bullish market conditions, driven by greed. Conversely, when the index is below 50 and under its moving average, it signals bearish or weak market conditions, associated with fear.
 Correlation and Pattern Detection:  The indicator analyses correlations among the included assets to detect patterns that might signal potential market movements, giving traders a leading edge over simpler sentiment measures.
 Adaptive Background Colouring:  Utilises a colour gradient that dynamically adjusts based on sentiment values, highlighting extreme fear, neutral, and extreme greed levels directly on the chart.
 Flexible Display Options:  Offers settings to toggle the moving average plot and adjust its period, giving users the ability to tailor the indicator's sensitivity and display to their specific needs. 
 
In this example below, we can see the Sentiment rise above the Moving Average (MA). Price action goes on to follow this, although there is an instance where it dips below the MA, it quickly rises back above again as a sign of strength. 
Another way you can use this index is by simply using the MA, if its trending up, we know the macro sentiment is bullish.
  
 Application  
  
 Data-Driven Insights:  Offers traders a detailed, data-driven approach to sentiment analysis, incorporating a broad spectrum of market indicators to deliver actionable insights. 
 Pattern Recognition:  Helps identify patterns and correlations that may lead to market reversals or continuations, providing a nuanced view that goes beyond simple sentiment gauges. 
 Enhanced Decision-Making:  Equips traders with a robust tool to validate trading strategies and make informed decisions based on comprehensive sentiment analysis. 
 
The  US Sentiment Index  by   is an essential addition to the toolkit of any trader looking to navigate market complexities with precision and confidence. Its advanced features and data-driven approach offer unparalleled insights into market sentiment, setting it apart from conventional sentiment indicators.
Z-Score Probability IndicatorThis is the Z-Score Probability indicator. As many people like my original Z-Score indicator and have expressed more interest in the powers of the Z, I decided to make this indicator which shows additional powers of the Z-Score. 
Z-Score is not only useful for measuring a ticker or any other variable’s distance from the mean, it is also useful to calculate general probability in a normal distribution set. Not only can it calculate probability in a dataset, but it can also calculate the variables within said dataset by using the Standard Deviation and the Mean of the dataset. 
Using these 2 aspects of the Z-Score, you can, In principle, have an indicator that operates similar to Fibonacci retracement levels with the added bonus of being able to actually ascertain the realistic probability of said retracement. 
Let’s take a look at an example: 
This is a chart showing SPY on the daily timeframe. If we look at the current Z-Score level, we can see that SPY is pushing into the 2 to 3 Z-Score range. We can see two things from this:
1.	We can see that a retracement to a Z-Score of 2 would correspond to a price of 425.26 based on the current dataset. And 
2.	We can see that the probability that SPY retraces to a Z-Score of 2 is around 0.9800 or 98%. 
To take it one step further, we can look at the various other variables in the distribution. If we were to bet on SPY retracing back to -1 SDs, that would correspond to a price of around 397.15, with a probability of around 0.1600 or 16% (see image below): 
Let’s say, we thought SPY would go to $440. Well, we can see that the probability SPY goes to 434.64 currently is pretty low. How do we know? Because the Z-Score table shows us the probability of values falling BELOW that Z-score level in the current distribution. So if we look at this example below:
We can see that 0.9998 or roughly 99% of values in the current SPY distribution will fall below 434.64. Thus, it may be unrealistic, at this point in time, to target said value.  
So what is a Z-Score Table? 
Well, I need to disclose/clarify that the Z-Score Table being displayed in this indicator does Z-Score probability a HUGE injustice. However, with the constraints what is realistic to fit into an indicator, I had to make it far more succinct. Let’s take a look at an actual Z-Score Table below:
Above is a look an the actual Z-Score table. How it works is you first identify you’re Z-Score and then find the corresponding value that relates to your score. The number displayed in the dataset represents the number of variables in the dataset/density distribution that fall BELOW that particular Z-score.
So, for example, if we have a Z-Score of -2.31, we can consult that table, go to the -2.3 then scroll across to the 0.01 to represent -2.31. We would see that this Z-Score corresponds to a 0.0104 probability zone (or essentially 1%) indicating that the majority of the variables in the distribution fall below that mean Z-score. In terms of tickers and stocks, that would mean it would theoretically be “overbought”. 
So what does the indicator Z-Table tell us?
I have averaged out the data for the purposes of this indicator. However, you can also reference a manual Z-Table to get the exact probability for the current precise Z-Score. However, the reality is it doesn’t necessarily matter to be exact when it comes to tickers. The reason being, ticker’s are in constant flux, and by the time you identify that probability, the ticker will already be at a different level. So generalizations are okay in these circumstances, you just need to get the “gist” of where the distribution lies. 
So how do I use the indicator? 
Using the indicator is pretty straightforward. Once launched, you will see the current Z-Score of the ticker, the current levels based on the distribution and the summarized Z-Table. 
The Z-Table will turn gray to indicate the zone the ticker is currently in. In this case, we can see that SPY currently is in the 2 SD Zone, meaning that 0.98 or 98% of the current dataset being shown falls below the price we are at:
When we launch the settings, we can see a few inputs. 
Lookback Length: This determines the number of candles back we want to calculate the distribution for. It is defaulted to 75, but you can adjust it to whichever length you want.
SMA Length: The SMA is optional but defaults to on. If you want to see the smoothed trend of the Z-Score, this will do the trick. It does not need to be set to the same 
length as the Z-Score lookback. Thus, if you want a more or less responsive SMA with, say, a larger dataset, then you can reduce the SMA length yourself. 
Distribution Probability Fills: This simply colour codes the distribution zones / probability zones on the indicator. 
Show Z-Table: This will display the summarized Z-Table.
Show SMA: As I indicated, the SMA is optional, you can toggle it on or off to see the overall Z-Score trend. 
Concluding Remarks: 
And that my friends is the Z-Score Probability Indicator.
I hope you all enjoy it and find it helpful. As always leave your comments, questions and suggestions below.
Safe trades to all and take care! 
Limit Order + ATR Stop-Loss [TANHEF]This indicator enables interactive placement of limit or stop-limit orders with a trailing ATR stop-loss and optional profit target (with alerts). Refer to the images below for further clarification.
 Why use a trailing stop-loss? 
A trailing stop-loss serves as an exit strategy when price moves against you, while also allowing you to adjust the exit point further into profit when price moves favorably. The ATR (Average True Range), a reliable measure of volatility, acts as an effective risk management tool, functioning as a trailing stop-loss.
 Indicator Explanation 
 
  Initial indicator placement: Select Long Limit or Long-Stop Limit order.
  Change Entry Type: Switch between Long and Short within settings.
  Modify entry price: Drag circle, adjust in settings, or re-add indicator to chart.
  Optional Profit Target: Use Risk/Reward ratio or specify price.
  Entry anticipation: Estimated ATR stop-loss and profit target as blue circles (fluctuates with volatility changes).
  Entry triggered: Actual ATR stop-loss and profit target plotted.
  Exit conditions: Stop-loss or profit target hit, exit entry.
  Update Frequency: Continuously, Bar Open, or Bar Open on entry then continuously.
  ATR Overlap: no entry occurs if the ATR overlaps with price (stop-loss 'hit' already on entry bar)
  Table: Displays input settings selected.
  Show Only On Ticker: Ability to hide indicator on other tickers.
 
 Long Limit 
 Long Stop-Limit 
 Short Limit 
 Short Stop-Limit 
 Alerts 
1. 'Check' alerts to use within indicator settings (entry, trailing stop hit, profit target hit, and failed entry).
2. Select 'Create Alert'
3. Set the condition to 'Limit Order + ATR Stop-Loss''
4. Select create.
 Additional details can be added to the alert message using these words in between Curly (Brace) Brackets: 
 
  {{trail}} = ATR trailing stop-loss (price)
  {{target}} = Price target (price)
  {{type}} = Long or Short stop-loss (word)
  {{traildistance}} = Trailing Distance (%)
  {{targetdistance}} = Target Distance (%)
  {{starttime}} = Start time of position (day:hr:min)
  {{maxdrawdown}} = max loss
  {{maxprofit}} = max profit
  {{update}} = stoploss update frequency
  {{entrysource}} = entry as 1st bar source (yes/no)
  {{triggerentry}} = Wick/Close Trigger entry input
  {{triggerexit}} = Wick/Close Trigger exit input
  {{triggertarget}} = Wick/Close Trigger target input
  {{atrlength}} = ATR length input
  {{atrmultiplier}} = ATR multiplier input
  {{atrtype}} = ATR type input
  {{ticker}} = Ticker of chart (word)
  {{exchange}} = Exchange of chart (word)
  {{description}} = Description of ticker (words)
  {{close}} = Bar close (price)
  {{open}} = Bar open (price)
  {{high}} = Bar high (price)
  {{low}} = Bar low (price)
  {{hl2}} = Bar HL2 (price)
  {{volume}} = Bar volume (value)
  {{time}} = Current time (day:hr:min)
  {{interval}} = Chart timeframe
  {{newline}} = New line for text






















