YM Confluence Panel - Dual SMA (fast/slow)This script displays a YM Confluence Panel for the mini Dow Jones (YM), using six correlated/inversely correlated assets (ES, NQ, RTY, ZN, GC, VIX) and two simple moving averages (fast: 9 / slow: 20).
The logic determines bullish or bearish conditions for each asset based on SMA relationships and price, generating arrows and an aggregated BUY / SELL / WAIT signal.
🔹 How it works:
• Correlated assets (ES, NQ, RTY): bullish when SMA(9) > SMA(20) and price above SMA(20).
• Inverse assets (ZN, GC, VIX): bullish when SMA(9) < SMA(20) and price below SMA(20).
• All bullish → BUY
• All bearish → SELL
• Otherwise → WAIT
✅ Customizable:
• Adjust assets and timeframes.
• Change SMA periods.
• Set panel position.
⚠️ Disclaimer: For educational purposes only. Not financial advice.
Penunjuk dan strategi
Stop-Loss Sentinel
Cutloss Swing Marker with Adjustable Trend Lines
This indicator identifies swing highs and lows using pivot points.
Swing Highs are marked with a green downward triangle and a "Cutloss" label above the bar.
Swing Lows are marked with a red upward triangle and a "Cutloss" label below the bar.
From each Cutloss point, a horizontal trend line is drawn forward for a set number of bars.
All colors (text, trend lines) and line length are fully adjustable in the settings.
Intended Use:
Helps traders visually mark potential stop-loss or reversal zones and track them over the next few bars. Works on any timeframe, but is designed for fast decision-making on lower timeframes like M1.
Marks key swing highs/lows with ‘Cutloss’ labels and triangles, then extends customizable trend lines for the next bars. Ideal for spotting stop-loss or reversal zones on any timeframe.
EMA Distance %# EMA Distance % - Daily Timeframe Analysis
## Overview
This indicator provides real-time analysis of price distance from key Exponential Moving Averages (EMA 10 and EMA 21) on the daily timeframe, regardless of your current chart timeframe. It displays both percentage and volatility-adjusted (ATR) distances in a clean, customizable table format.
## Key Features
- **Daily Timeframe Focus**: Always references daily EMA 10 and EMA 21 values, providing consistent analysis across all chart timeframes
- **Dual Distance Metrics**: Shows both percentage distance and ATR-normalized distance for comprehensive analysis
- **Customizable Table Position**: Position the data table anywhere on your chart (9 different locations available)
- **Color-Coded Results**: Green indicates price above EMA, red indicates price below EMA
- **Volatility Adjustment**: ATR distance provides context relative to the asset's typical price movements
## What It Shows
The indicator displays a table with the following information:
- **EMA Value**: Current daily EMA 10 and EMA 21 values
- **Distance %**: Percentage distance from each EMA (positive = above, negative = below)
- **ATR Distance**: How many Average True Range units the price is from each EMA
## Use Cases
- **Mean Reversion Trading**: Identify when price has moved significantly away from key EMAs
- **Trend Strength Analysis**: Gauge the strength of current trends relative to moving averages
- **Entry/Exit Timing**: Use ATR distances to identify potential reversal zones (typically 2-3+ ATR)
- **Multi-Timeframe Analysis**: View daily EMA relationships while analyzing shorter timeframes
- **Risk Management**: Understand volatility-adjusted distance for better position sizing
## Settings
- **Table Position**: Choose from 9 different table positions on your chart
- **ATR Period**: Customize the ATR calculation period (default: 14)
## Interpretation
- **Small distances (< 1% or < 1 ATR)**: Price near EMA support/resistance
- **Medium distances (1-3% or 1-2 ATR)**: Normal trending movement
- **Large distances (> 3% or > 2-3 ATR)**: Potential overextension, watch for mean reversion
Perfect for swing traders, position traders, and anyone using EMA-based strategies who wants quick access to daily timeframe EMA relationships without switching chart timeframes.
Kootch EMA MapKootch EMA overlays the 200 EMA from M1, M5, M15, M30, H1, H4, and D1 on any chart so you always see where higher and lower-timeframe trend gravity actually is. It also builds an optional Fib channel between the most extreme MTF 200 EMAs (min/max), giving you clean intrachannel targets and confluence zones.
What it does
• Plots seven 200 EMAs (M1 → D1) simultaneously via MTF pulls
• Color/weight hierarchy: thicker lines = higher timeframe (clear priority)
• Right-edge TF tags (M1, M5, … D1) so you know exactly what you’re looking at
• Optional Fib levels between min/max MTF 200 EMAs (0 → 1 band) for entries, adds, and take-profit scaling
Why traders use it
• Immediate read on trend alignment vs. chop across timeframes
• Mean-reversion & continuation cues when price stretches from/returns to key EMAs
• Level stacking: use M30/H1/H4/D1 as bias, trade entries around lower-TF reactions
Inputs
• EMA Length (default 200)
• Label offset (push tags off the last bar)
• Show Fib channel toggle + color control
How I use it
• Bias from D1/H4/H1; execution from M5/M15.
• Fade or follow at Fib 0.382 / 0.618 inside the EMA envelope; scale out near Fib 1.0 into HTF EMAs.
• Skip trades when EMAs are braided and distances are compressed.
Notes
• Works on any symbol/timeframe; all TF EMAs are requested explicitly.
• This is a map, not a crystal ball: combine with your playbook (structure breaks, FVGs, liquidity, volume).
Information-Geometric Market DynamicsInformation-Geometric Market Dynamics
The Information Field: A Geometric Approach to Market Dynamics
By: DskyzInvestments
Foreword: Beyond the Shadows on the Wall
If you have traded for any length of time, you know " the feeling ." It is the frustration of a perfect setup that fails, the whipsaw that stops you out just before the real move, the nagging sense that the chart is telling you only half the story. For decades, technical analysis has relied on interpreting the shadows—the patterns left behind by price. We draw lines on these shadows, apply indicators to them, and hope they reveal the future.
But what if we could stop looking at the shadows and, instead, analyze the object casting them?
This script introduces a new paradigm for market analysis: Information-Geometric Market Dynamics (IGMD) . The core premise of IGMD is that the price chart is merely a one-dimensional projection of a much richer, higher-dimensional reality—an " information field " generated by the collective actions and beliefs of all market participants.
This is not just another collection of indicators. It is a unified framework for measuring the geometry of the market's information field—its memory, its complexity, its uncertainty, its causal flows—and making high-probability decisions based on that deeper reality. By fusing advanced mathematical and informational concepts, IGMD provides a multi-faceted lens through which to view market behavior, moving beyond simple price action into the very structure of market information itself.
Prepare to move beyond the flatland of the price chart. Welcome to the information field.
The IGMD Framework: A Multi-Kernel Approach
What is a Kernel? The Heart of Transformation
In mathematics and data science, a kernel is a powerful and elegant concept. At its core, a kernel is a function that takes complex, often inscrutable data and transforms it into a more useful format. Think of it as a specialized lens or a mathematical "probe." You cannot directly measure abstract concepts like "market memory" or "trend quality" by looking at a price number. First, you must process the raw price data through a specific mathematical machine—a kernel—that is designed to output a measurement of that specific property. Kernels operate by performing a sort of "similarity test," projecting data into a higher-dimensional space where hidden patterns and relationships become visible and measurable.
Why do creators use them? We use kernels to extract features —meaningful pieces of information—that are not explicitly present in the raw data. They are the essential tools for moving beyond surface-level analysis into the very DNA of market behavior. A simple moving average can tell you the average price; a suite of well-chosen kernels can tell you about the character of the price action itself.
The Alchemist's Challenge: The Art of Fusion
Using a single kernel is a challenge. Using five distinct, computationally demanding mathematical engines in unison is an immense undertaking. The true difficulty—and artistry—lies not just in using one kernel, but in fusing the outputs of many . Each kernel provides a different perspective, and they can often give conflicting signals. One kernel might detect a strong trend, while another signals rising chaos and uncertainty. The IGMD script's greatest strength is its ability to act as this alchemist, synthesizing these disparate viewpoints through a weighted fusion process to produce a single, coherent picture of the market's state. It required countless hours of testing and calibration to balance the influence of these five distinct analytical engines so they work in harmony rather than cacophony.
The Five Kernels of Market Dynamics
The IGMD script is built upon a foundation of five distinct kernels, each chosen to probe a unique and critical dimension of the market's information field.
1. The Wavelet Kernel (The "Microscope")
What it is: The Wavelet Kernel is a signal processing function designed to decompose a signal into different frequency scales. Unlike a Fourier Transform that analyzes the entire signal at once, the wavelet slides across the data, providing information about both what frequencies are present and when they occurred.
The Kernels I Use:
Haar Kernel: The simplest wavelet, a square-wave shape defined by the coefficients . It excels at detecting sharp, sudden changes.
Daubechies 2 (db2) Kernel: A more complex and smoother wavelet shape that provides a better balance for analyzing the nuanced ebb and flow of typical market trends.
How it Works in the Script: This kernel is applied iteratively. It first separates the finest "noise" (detail d1) from the first level of trend (approximation a1). It then takes the trend a1 and repeats the process, extracting the next level of cycle (d2) and trend (a2), and so on. This hierarchical decomposition allows us to separate short-term noise from the long-term market "thesis."
2. The Hurst Exponent Kernel (The "Memory Gauge")
What it is: The Hurst Exponent is derived from a statistical analysis kernel that measures the "long-term memory" or persistence of a time series. It is the definitive measure of whether a series is trending (H > 0.5), mean-reverting (H < 0.5), or random (H = 0.5).
How it Works in the Script: The script employs a method based on Rescaled Range (R/S) analysis. It calculates the average range of price movements over increasingly larger time lags (m1, m2, m4, m8...). The slope of the line plotting log(range) vs. log(lag) is the Hurst Exponent. Applying this complex statistical analysis not to the raw price, but to the clean, wavelet-decomposed trend lines, is a key innovation of IGMD.
3. The Fractal Dimension Kernel (The "Complexity Compass")
What it is: This kernel measures the geometric complexity or "jaggedness" of a price path, based on the principles of fractal geometry. A straight line has a dimension of 1; a chaotic, space-filling line approaches a dimension of 2.
How it Works in the Script: We use a version based on Ehlers' Fractal Dimension Index (FDI). It calculates the rate of price change over a full lookback period (N3) and compares it to the sum of the rates of change over the two halves of that period (N1 + N2). The formula d = (log(N1 + N2) - log(N3)) / log(2) quantifies how much "longer" and more convoluted the price path was than a simple straight line. This kernel is our primary filter for tradeable (low complexity) vs. untradeable (high complexity) conditions.
4. The Shannon Entropy Kernel (The "Uncertainty Meter")
What it is: This kernel comes from Information Theory and provides the purest mathematical measure of information, surprise, or uncertainty within a system. It is not a measure of volatility; a market moving predictably up by 10 points every bar has high volatility but zero entropy .
How it Works in the Script: The script normalizes price returns by the ATR, categorizes them into a discrete number of "bins" over a lookback window, and forms a probability distribution. The Shannon Entropy H = -Σ(p_i * log(p_i)) is calculated from this distribution. A low H means returns are predictable. A high H means returns are chaotic. This kernel is our ultimate gauge of market conviction.
5. The Transfer Entropy Kernel (The "Causality Probe")
What it is: This is by far the most advanced and computationally intensive kernel in the script. Transfer Entropy is a non-parametric measure of directed information flow between two time series. It moves beyond correlation to ask: "Does knowing the past of Volume genuinely reduce our uncertainty about the future of Price?"
How it Works in the Script: To make this work, the script discretizes both price returns and the chosen "driver" (e.g., OBV) into three states: "up," "down," or "neutral." It then builds complex conditional probability tables to measure the flow of information in both directions. The Net Transfer Entropy (TE Driver→Price minus TE Price→Driver) gives us a direct measure of causality . A positive score means the driver is leading price, confirming the validity of the move. This is a profound leap beyond traditional indicator analysis.
Chapter 3: Fusion & Interpretation - The Field Score & Dashboard
Each kernel is a specialist providing a piece of the puzzle. The Field Score is where they are fused into a single, comprehensive reading. It's a weighted sum of the normalized scores from all five kernels, producing a single number from -1 (maximum bearish information field) to +1 (maximum bullish information field). This is the ultimate "at-a-glance" metric for the market's net state, and it is interpreted through the dashboard.
The Dashboard: Your Mission Control
Field Score & Regime: The master metric and its plain-English interpretation ("Uptrend Field", "Downtrend Field", "Transitional").
Kernel Readouts (Wave Align, H(w), FDI, etc.): The live scores of each individual kernel. This allows you to see why the Field Score is what it is. A high Field Score with all components in agreement (all green or red) is a state of High Coherence and represents a high-quality setup.
Market Context: Standard metrics like RSI and Volume for additional confluence.
Signals: The raw and adjusted confluence counts and the final, calculated probability scores for potential long and short entries.
Pattern: Shows the dominant candlestick pattern detected within the currently forming APEX range box and its calculated confidence percentage.
Chapter 4: Mastering the Controls - The Inputs Menu
Every parameter is a lever to fine-tune the IGMD engine.
📊 Wavelet Transform: Kernel ( Haar for sharp moves, db2 for smooth trends) and Scales (depth of analysis) let you tune the script's core microscope to your asset's personality.
📈 Hurst Exponent: The Window determines if you're assessing short-term or long-term market memory.
🔍 Fractal Dimension & ⚡ Entropy Volatility: Adjust the lookback windows to make these kernels more or less sensitive to recent price action. Always keep "Normalize by ATR" enabled for Entropy for consistent results.
🔄 Transfer Entropy: Driver lets you choose what causal force to measure (e.g., OBV, Volume, or even an external symbol like VIX). The throttle setting is a crucial performance tool, allowing you to balance precision with script speed.
⚡ Field Fusion • Weights: This is where you can customize the model's "brain." Increase the weights for the kernels that best align with your trading philosophy (e.g., w_hurst for trend followers, w_fdi for chop avoiders).
📊 Signal Engine: Mode offers presets from Conservative to Aggressive . Min Confluence sets your evidence threshold. Dynamic Confluence is a powerful feature that automatically adapts this threshold to the market regime.
🎨 Visuals & 📏 Support/Resistance: These inputs give you full control over the chart's appearance, allowing you to toggle every visual element for a setup that is as clean or as data-rich as you desire.
Chapter 5: Reading the Battlefield - On-Chart Visuals
Pattern Boxes (The Large Rectangles): These are not simple range boxes. They appear when the Field Score crosses a significance threshold, signaling a potential ignition point.
Color: The color reflects the dominant candlestick pattern that has occurred within that box's duration (e.g., green for Bull Engulf).
Label: Displays the dominant pattern, its duration in bars, and a calculated Confidence % based on field strength and pattern clarity.
Bar Pattern Boxes (The Small Boxes): If enabled, these highlight individual, significant candlestick patterns ( BE for Bull Engulf, H for Hammer) on a bar-by-bar basis.
Signal Markers (▲ and ▼): These appear only when the Signal Engine's criteria are all met. The number is the calculated Probability Score .
RR Rails (Dashed Lines): When a signal appears, these lines automatically plot the Entry, Stop Loss (based on ATR), and two Take Profit targets (based on Risk/Reward ratios). They dynamically break and disappear as price touches each level.
Support & Resistance Lines: Plots of the highest high ( Resistance ) and lowest low ( Support ) over a lookback, providing key structural levels.
Chapter 6: Development Philosophy & A Final Word
One single question: " What is the market really doing? " It represents a triumph of complexity, blending concepts from signal processing, chaos theory, and information theory into a cohesive framework. It is offered for educational and analytical purposes and does not constitute financial advice. Its goal is to elevate your analysis from interpreting flat shadows to measuring the rich, geometric reality of the market's information field.
As the great mathematician Benoit Mandelbrot , father of fractal geometry, noted:
"Clouds are not spheres, mountains are not cones, coastlines are not circles, and bark is not smooth, nor does lightning travel in a straight line."
Neither does the market. IGMD is a tool designed to navigate that beautiful, complex, and fractal reality.
— Dskyz, Trade with insight. Trade with anticipation.
Volume Rotor Clock [hapharmonic]🕰️ Volume Rotor Clock
The Volume Rotor Clock is an indicator that separates buy and sell volume, compiling these volumes over a recent number of bars or a specified past period, as defined by the user. This helps to reveal accumulation (buying) or distribution (selling) behavior, showing which side has superior volume. With its unique and beautiful display, the Volume Rotor Clock is more than just a timepiece; it's a dynamic dashboard that visualizes the buying and selling pressure of your favorite symbols, all wrapped in an elegant and fully customizable interface.
Instead of just tracking price, this indicator focuses on the engine behind the movement: volume. It helps you instantly identify which assets are under accumulation (buying) and which are under distribution (selling).
---
🎨 20 Pre-configured Templates
---
🧐 Interpreting the Clock Display
The interface is designed to give you multiple layers of information at a glance. Let's break down what each part represents.
1. The Main Clock Hands (Current Chart Symbol)
The clock hands—hour, minute, and second—are dedicated to the symbol on your current active chart .
Minute Hand: Displays the base currency of the current symbol (e.g., USDT, USD) at its tip.
Hour Hand: Displays the percentage of the winning volume side (buy vs. sell) at its tip.
Color Gauge: The color of the text characters at the tip of both the hour and minute hands acts as your primary volume gauge for the current symbol.
If buy volume is dominant , the text will be green .
If sell volume is dominant , the text will be red .
Tooltip: Hovering your mouse over the text at the tip of the hour or minute or other spherical elements hand will reveal a detailed tooltip with the precise Buy Volume, Sell Volume, Total Volume, Buy %, and Sell % for the current chart's symbol.
2. The Volume Scanner: Bulls & Bears (Symbols Inside the Clock) 🐂🐻
The circular symbols scattered inside the clock face are your multi-symbol volume scanner. They represent the assets you've selected in the indicator's settings.
Green Circles (Bulls - Upper Half): These represent symbols from your list where the total buy volume is greater than the total sell volume over the defined "Lookback" period. They are considered to be under bullish accumulation. The size of the circle and its text grows larger as the buy percentage becomes more dominant. The percentage shown within the circle represents the buy volume's share of the total volume, calculated over the 'Lookback (Bars)' you've set.
Red Circles (Bears - Lower Half): These represent symbols where the total sell volume is greater than the total buy volume. They are considered to be under bearish distribution or selling pressure. The size of the circle indicates the dominance of the sell-side volume. The percentage shown within the circle represents the sell volume's share of the total volume, calculated over the 'Lookback (Bars)' you've set.
3. The Bullish Watchlist (Symbols Above the Clock) ⭐
The symbols arranged neatly along the top edge of the clock are the "best of the bulls." They are symbols that are not only bullish but have also passed an additional, powerful strength filter.
What it Means: A symbol appears here when it shows signs of sustained, high-volume buying interest . It's a way to filter out noise and focus on assets with potentially significant accumulation phases.
The Filter Logic: For a bullish symbol (where total buy volume > total sell volume) to be promoted to the watchlist, its trading volume must meet specific criteria based on this formula:
ta.barssince(not(volume > ta.sma(volume, X))) >= Y
In plain English, this means: The indicator checks how many consecutive bars the `volume` has been greater than its `X`-bar Simple Moving Average (`ta.sma(volume, X)`). If this count is greater than or equal to `Y` bars, the condition is met.
(You can configure `X` (Volume MA Length) and `Y` (Consecutive Days Above MA) in the settings.)
Why it's Useful: This filter is powerful because it looks for consistency . A single spike in volume can be an anomaly. However, when an asset's volume remains consistently above its recent average for several consecutive days, it strongly suggests that larger players or a significant portion of the market are actively accumulating the asset. This sustained interest can often precede a significant upward price trend.
---
⚙️ Indicator Settings Explained
The Volume Rotor Clock is highly customizable. Here’s a detailed walkthrough of every setting available in the "Inputs" tab.
🎨 Color Scheme
This group allows you to control the entire aesthetic of the clock.
Template: Choose from a wide variety of professionally designed color themes.
Use Template: A simple checkbox to switch between using a pre-designed theme and creating your own.
`Checked`: You can select a theme from the dropdown menu, which offers 20 unique templates like "Cyberpunk Neon" or "Forest Green". All custom color settings below will be disabled (grayed out and unclickable).
`Unchecked`: The template dropdown is disabled, and you gain full control over every color element in the sections below.
🖌️ Custom Appearance & Colors
These settings are only active when "Use Template" is unchecked.
Flame Head / Tail: Sets the start and end colors for the dynamic flame effect that traces the clock's border, representing the second hand.
Numbers / Main Numbers: Customize the color of the regular hour numbers (1, 2, 4, 5...) and the main cardinal numbers (3, 6, 9, 12).
Sunburst Colors (1-6): Controls the six colors used in the gradient background for the "sunburst" effect inside the clock face.
Hands & Digital: Fine-tune the colors for the Hour/Minute Hand, Second Hand, central Pivot point, and the digital time display.
Chain Color / Width: Customize the appearance of the two chains holding the clock.
📡 Volume Scanner
Control the behavior of the multi-symbol scanner.
Show Scanner Labels: A master switch to show or hide all the bull/bear symbol circles inside the clock.
Lookback (Bars): A crucial setting that defines the calculation period for buy/sell volume for all scanned symbols. The calculation is a sum over the specified number of recent bars.
`0`: Calculates using the current bar only .
`7`: Calculates the sum of volume over the last 8 bars (the current bar + 7 historical bars).
Symbols List: Here you can enable/disable up to 20 slots and input the ticker for each symbol you want to scan (e.g., BINANCE:BTCUSDT , NASDAQ:AAPL ).
⭐ Bullish Watchlist Filter
Configure the criteria for the elite watchlist symbols displayed above the clock.
Enable Watchlist: A master switch to turn the entire watchlist feature on or off.
Volume MA Length: Sets the lookback period `(X)` for the Simple Moving Average of volume used in the filter.
Consecutive Days Above MA: Sets the minimum number of consecutive days `(Y)` that volume must close above its MA to qualify.
Symbols Per Row: Determines the maximum number of watchlist symbols that can fit in a single row before a new row is created above it.
Background / Text Color: When not using a template, you can set custom colors for the watchlist symbols' background and text.
📏 Position & Size
Adjust the clock's placement and dimensions on your chart.
Clock Timezone: Sets the timezone for the digital and analog time display. You can use standard formats like "America/New_York" or enter "Exchange" to sync with the chart's timezone.
Radius (Bars): Controls the overall size of the clock. The radius is measured in terms of the number of bars on the x-axis.
X Offset (Bars): Moves the entire clock horizontally. Positive values shift it to the right; negative values shift it to the left.
Y Offset (Price %): Moves the entire clock vertically as a percentage of your screen's price pane. Positive values move it up; negative values move it down.
FVG + Bank Level Targeting w/ Alert TriggerDescription:
FVG + Bank Level Targeting w/ Alert Trigger is an intraday trading tool that combines Fair Value Gap (FVG) detection with dynamic institutional targeting using prior-day, weekly, and monthly high/low "Bank Levels." When a Fair Value Gap is detected, the script projects a logical target using the closest bank level in price's direction, and visually extends that level on your chart.
This tool is designed to help traders anticipate where price is most likely to move after an FVG appears — and alert them when price breaks through key target zones.
How It Works:
* Bank Level Calculation:
The indicator calculates Daily, Weekly, and Monthly high and low levels from the previous bar of each respective timeframe.
These are optionally plotted on the chart with a slight tick offset to avoid overlap with price.
* FVG Detection:
Bullish FVGs are defined by a gap between the low of the current candle and the high two candles prior, with a confirming middle candle.
Bearish FVGs follow the reverse pattern.
Once detected, the script finds the nearest unbroken institutional level (Bank Level) in the direction of the FVG and anchors a target line at that price level.
* Target Line Projection:
The script draws a persistent horizontal line (not just a plotted value) at the selected bank level.
These lines automatically extend a set number of bars into the future for clarity and trade planning.
* Breakout Detection:
When price crosses above a Bull Target or below a Bear Target, the script triggers a breakout condition.
These breakouts are useful for trade continuation or reversal setups.
* Alerts:
Built-in alert conditions notify you in real time when price crosses above or below a target.
These can be used to set TradingView alerts for your preferred Futures symbols or intraday pairs.
Parameters:
Tick Offset Multiplier: Adds distance between price and plotted levels.
Show Daily/Weekly/Monthly Levels: Toggle for each institutional level group.
FVG Extend Right (bars): Controls how far the target lines extend into the future.
Color Controls: Customize colors for FVG fill and target lines.
Use Case:
This indicator is designed for traders who want to:
Trade continuation or reversal moves around institutional price zones
Integrate Fair Value Gap concepts with more logical, historically anchored price targets
Trigger alerts when market structure evolves around key levels
It is especially useful for intraday Futures traders on the 15-minute chart or lower, but adapts well to any instrument with strong reactionary behavior at prior session highs/lows.
Lot Size + Margin InfoThis indicator is designed to give Futures & Options traders instant access to lot size and estimated margin requirements for the instrument they are viewing — directly on their TradingView chart. It combines real-time symbol detection with a built-in, regularly updated margin lookup table (sourced from Kotak Securities’ published margin requirements), while also handling fallback logic for unknown or unsupported symbols.
---
### What It Does
* Automatically Detects the Instrument Type
Identifies whether the current chart’s symbol is a futures contract, option, or a cash/spot instrument.
* Shows Accurate Lot Size
For supported F\&O symbols, it fetches the correct lot size directly from exchange data.
For options, it retrieves the lot size from the option’s point value.
For cash/spot symbols with linked futures, it uses the futures lot size.
* Calculates Estimated Margin
* For futures: `Lot Size × Current Price × Margin%` (Margin% sourced from the internal lookup table).
* For options: `Lot Size × Current Price` (simple multiplication, as options margin ≈ premium cost).
* For unsupported or non-FnO symbols: Displays "No FnO".
* Fallback Margin Logic
If a symbol is missing from the margin lookup table, the script applies a user-defined default margin percentage and highlights the data in orange to indicate it’s using fallback values.
* Debug Mode for Transparency
A toggle to display the exact symbol string used for fetching lot size and margin, so traders can verify the data source.
---
### How It Works
1. Symbol Normalization
The script standardizes symbol names to match the margin table format (e.g., converting `"NIFTY1!"` to `"NIFTY"`).
2. Type-Based Handling
* Futures – Uses point value for lot size, applies specific margin % from the table.
* Options – Uses option point value for lot size, margin is simply premium × lot size.
* Cash Symbols with Linked Futures – Attempts to find and use the associated futures contract for lot/margin data.
* Unsupported Symbols – Displays `"No FnO"`.
3. Margin Table Integration
The margin % table is manually updated from a reliable broker’s margin sheet (Kotak Securities) — ensuring alignment with real trading conditions.
4. Customizable Display
* Position (Top Right / Bottom Left / Bottom Right)
* Table background color, text color, font size, border width
* Editable label text for lot size and margin display
* Toggleable lot size and margin sections
---
### How to Use
1. Add the Indicator to Your Chart – Works on any NSE Futures, Options, or Cash symbol with linked F\&O.
2. Configure Display Settings – Choose whether to show lot size, margin, or both, and place the info table where you prefer.
3. Adjust Fallback Margin % – If you trade less common contracts, set your default margin % to reflect your broker’s requirement.
4. Enable Debug Mode (Optional) – To see the exact symbol source the script is using.
---
### Best For
* Intraday & Positional F\&O Traders who need instant clarity on lot size and margin before entering trades.
* Options Sellers & Buyers who want quick cost estimates.
* Traders Switching Symbols Quickly — saves time by removing the need to check the broker’s margin sheet manually.
---
💡 Pro Tip: Since margin requirements can change, keep the script updated whenever your broker revises margin data. This version’s margin table is updated as of 13-08-2025.
Egg vs Tennis Ball — Drop/Rebound StrengthEgg vs Tennis Ball — Drop/Rebound Meter
What it does
Classifies selloffs as either:
Eggs — dead‑cat, no bounce
Tennis Balls — fast, decisive rebound
Core features
Detects swing drops from a Pivot High (PH) to a Pivot Low (PL)
Requires drops to be meaningful (volatility‑aware, ATR‑scaled)
Draws a bounce threshold line and a deadline
Decides outcome based on speed and extent of rebound
Tracks scores and win rates across multiple lookback windows
Includes a color‑coded meter and current streak display
Visuals at a glance
Gray diagonal — drop from PH to PL
Teal dotted horizontal — bounce threshold, from PH to the deadline
Solid green — Tennis Ball (bounce line broken before the deadline)
Solid red — Egg (deadline expired before the bounce)
Optional PH / PL labels for clarity
How the decision is made
1) Find pivots — symmetric pivots using Pivot Left / Right; PL confirms after Right bars.
2) Qualify the drop — Drop Size = PH − PL; must be ≥ (Drop Threshold × ATR at PL).
3) Define the bounce line — PL + (Bounce Multiple × Drop Size). 1.00× = full retrace to PH; up to 2.00× for overshoot.
4) Set the deadline — Drop Bars = PL index − PH index; Deadline = Drop Bars × Recovery Factor; timer starts from PH or PL.
5) Resolve — Tennis Ball if price hits the bounce line before the deadline; Egg if the deadline passes first.
Scoring system (−100 to +100)
+100 = perfect Tennis Ball (fastest possible + full overshoot)
−100 = perfect Egg (no recovery)
In between: scored by rebound speed and extent, shaped by your weight settings
Meter Table
Columns (toggle on/off)
All (off by default)
Last N1 (default 5)
Last N2 (default 10)
Last N3 (default 20)
Rows
Tennis / Eggs — counts
% Tennis — win rate
Avg Score — normalized quality from −100 to +100
Streak — overall (not windowed), e.g., +3 = 3 Tennis Balls in a row, −4 = 4 Eggs in a row
Alerts
Tennis Ball – Fast Rebound — triggers when the bounce line is broken in time
Egg – Window Expired — triggers when the deadline passes without a bounce
Inputs
① Drop Detection
Pivot Left / Right
ATR Length
Drop Threshold × ATR
② Bounce Requirement
Bounce Multiple × Drop Size (0.10–2.00×)
③ Timing
Timer Start — PH or PL
Recovery Factor × Drop Bars
Break Trigger — Close or High
④ Display
Show Pivot/Outcome Labels
Line Width
Table Position (corner)
⑤ Meter Columns
Show All (off by default)
Show N1 / N2 / N3 (5, 10, 20 by default)
⑥ Scoring Weights
Tennis — Base, Speed, Extent
Egg — Base, Strength
How to use it
Pick strictness — start with Drop Threshold = 2.0 ATR, Bounce Multiple = 1.0×, Recovery Factor = 3.0×; adjust to timeframe and volatility.
Watch the dotted line — it ends at the deadline; turns solid green (Tennis) if broken in time, solid red (Egg) if it expires.
Read the meter — short windows (5–10) show current behavior; Avg Score captures quality; Streak shows momentum.
Blend with your system — combine with trend filters, volume, or regime detection.
Tips
Close vs High trigger: Close is stricter; High is more responsive.
PH vs PL timer start: PH measures round‑trip; PL measures recovery only.
Increase pivot strength for fewer, more reliable signals.
Higher timeframes generally produce cleaner patterns.
Defaults
Pivot L/R: 5 / 5
ATR Length: 14
Drop Threshold: 2.0× ATR
Bounce Multiple: 1.00×
Recovery Factor: 3.0×
Break Trigger: Close
Windows: Last 5, 10, 20 (All off)
Interpreting results
Tennis‑y: Avg Score +30 to +70, %Tennis > 55%
Mixed: Avg Score near 0
Egg‑y: Avg Score −30 to −80, %Tennis < 45%
Ichimoku Cloud Signals [sgbpulse] Ichimoku Cloud Signals – Your Advanced Trading Tool
Meet Ichimoku Cloud Signals, the enhanced and interactive version of the classic Ichimoku Cloud indicator, designed specifically for TradingView traders seeking precision and flexibility in their trading decisions. This indicator allows you to maximize the Ichimoku's potential by customizing trend criteria, receiving clear visual signals for entering and exiting positions, and getting alerts to keep you informed.
Introduction to the Ichimoku Cloud
The Ichimoku Cloud, also known as Ichimoku Kinko Hyo, is a comprehensive technical analysis tool developed in Japan. It provides a broad view of the market: trend direction, momentum, and support and resistance levels. "Ichimoku Cloud Signals" takes this power and amplifies it with advanced features.
Key Components of the Ichimoku Cloud
The indicator displays all five familiar Ichimoku lines, along with the "Cloud" (Kumo):
Tenkan-sen (Conversion Line): Calculated as the average of the highest high and lowest low over the past 9 periods. A fast, short-term indicator used as a measure of immediate momentum.
Kijun-sen (Base Line): Calculated as the average of the highest high and lowest low over the past 26 periods. A medium-term reference line serving as a significant support/resistance level.
Senkou Span A (Leading Span A): The average of the Tenkan-sen and Kijun-sen, shifted 26 periods forward into the future.
Senkou Span B (Leading Span B): The average of the highest high and lowest low over the past 52 periods, also shifted 26 periods forward into the future.
Kumo (Cloud): The area between Senkou Span A and Senkou Span B. Its color changes: green for an uptrend (when Senkou Span A is above Senkou Span B) and red for a downtrend (when Senkou Span B is above Senkou Span A). The Cloud serves as a dynamic area of support/resistance and a tool for forecasting future trends.
Chikou Span (Lagging Span): The current closing price, shifted 26 periods backward into the past. It serves as a powerful trend confirmation tool.
How the Ichimoku Cloud Works and How to Interpret It
Trend Identification :
- Uptrend (Bullish): The price is above the Cloud. The higher the price is above the Cloud, the stronger the trend.
- Downtrend (Bearish): The price is below the Cloud. The lower the price is below the Cloud, the stronger the trend.
- Range/Consolidation: The price is within the Cloud. This indicates a market without a clear direction or one that is consolidating.
Support and Resistance:
- The Cloud itself acts as a dynamic area of support and resistance. In an uptrend, the Cloud serves as support. In a downtrend, it serves as resistance.
- A thick Cloud indicates stronger support/resistance levels, while a thin Cloud indicates weaker levels.
The Cloud as a Predictive Indicator:
The uniqueness of the Kumo (Cloud) lies in its ability to be shifted 26 periods forward. This part of the Cloud provides forecasts for future support and resistance levels and even suggests expected trend changes (like a "Kumo Twist" – a change in Cloud color), giving you a planning advantage.
Unique Advantages of Ichimoku Cloud Signals:
Ichimoku Cloud Signals takes the classic Ichimoku principles and gives you unprecedented control:
Focused Trend Selection:
Choose whether you want to analyze a bullish (uptrend) or bearish (downtrend) trend. The indicator will focus on the relevant criteria for your selection.
Customizable Trend Confirmation Criteria (8 Criteria):
The indicator relies on 8 key criteria for clear trend confirmation. You can enable or disable each criterion individually based on your trading strategy and desired risk level. Each criterion plays a vital role in confirming the strength of the trend:
- Price position relative to the Cloud (Kumo) (Default: true): Determines the main trend direction and whether it's bullish or bearish.
- Price position relative to Kijun-sen (Base Line) (Default: true): Indicates the medium-term trend and acts as a critical equilibrium level.
- Price position relative to Tenkan-sen (Conversion Line) (Default: false): Provides quick confirmation of current momentum and short-term market changes.
- Tenkan-sen (Conversion Line) / Kijun-sen (Base Line) Crossover (Default: true): A classic signal for momentum change, crucial for identifying entry points.
- Current Cloud trend (Kumo) (Default: false): Cloud color confirms the main trend direction in real-time.
- Projected Future Cloud trend (Kumo) (Default: true): Indicates an expected future change in the Cloud's trend, providing strong visual insight.
- Chikou Span (Lagging Span) position relative to the Cloud (Kumo) (Default: true): Confirms the current trend strength by comparing the price to the Ichimoku 26 periods ago.
- Chikou Span (Lagging Span) position relative to the Price (Default: false): Additional confirmation of trend strength, indicating buyer/seller dominance.
Full Customization of Ichimoku Parameters:
You can change the period lengths for each Ichimoku component, depending on your strategy:
- Conversion Line Length (Default: 9)
- Base Line Length (Default: 26)
- Leading Span Length (Default: 52)
- Cloud Lagging Length (Default: 26)
- Lagging Span Length (Default: 26)
Visual Criteria Table on the Chart:
Get immediate and clear feedback! A visual table is placed on the chart, showing in real-time which of the 8 criteria you have defined are met for your chosen trend. Criteria you have enabled will be highlighted with a blue color and a "➤" symbol, while disabled criteria will appear in a subtle gray shade. For each criterion, the table shows its real-time status with a "✔" symbol if the condition is met and an "✘" symbol if it is not met. This powerful visual tool provides a quick assessment, helps with learning, and allows for strategy optimization at the click of a button.
Precise Criteria Details in the Data Window:
Beyond the visual table, the indicator provides an additional critical layer of detail: for any point on the chart, you can hover over a candle and see in TradingView's Data Window the precise status and values of all eight criteria. For each criterion, you'll see a clear numerical value (1 or 0) indicating whether it's fully met (1) or not met (0). Additionally, you can inspect the exact numerical values of the Ichimoku lines (Tenkan-sen, Kijun-sen, etc.) at that specific moment. This comprehensive data supports in-depth analysis, strategy debugging, and long-term optimization, providing complete transparency regarding every component of the signal.
Smart and Customizable Alerts:
Ichimoku Cloud Signals provides a powerful alert system to keep you informed of key market movements, so you never miss an opportunity. There are eight unique alerts you can enable in TradingView's alert panel:
Uptrend Entry Alert: Triggers when all of your selected criteria for an uptrend are met on a new candle.
Uptrend Exit Alert: Triggers when one of your selected uptrend criteria is no longer met, signaling a potential exit point.
Downtrend Entry Alert: Triggers when all of your selected criteria for a downtrend are met on a new candle.
Downtrend Exit Alert: Triggers when one of your selected downtrend criteria is no longer met, signaling a potential exit point.
Bullish Crossover Alert: Triggers when the Conversion Line (Tenkan-sen) crosses above the Base Line (Kijun-sen), a classic signal for an upward momentum shift.
Bearish Crossover Alert: Triggers when the Conversion Line (Tenkan-sen) crosses below the Base Line (Kijun-sen), signaling a potential shift to downward momentum.
Bullish Cloud Breakout Alert: Triggers when the price closes above the Ichimoku Cloud (Kumo), indicating a strong bullish trend.
Bearish Cloud Breakout Alert: Triggers when the price closes below the Ichimoku Cloud (Kumo), indicating a strong bearish trend.
Each alert can be independently configured in TradingView's alert panel, allowing you to tailor your notifications to fit your exact trading strategy and risk management preferences.
Summary:
Ichimoku Cloud Signals is an essential tool for TradingView traders seeking control, clarity, and precision. It combines the power of the classic Ichimoku Cloud indicator with advanced customization capabilities, a convenient visual table, and clear signals, empowering you to make informed trading decisions and stay focused on managing your positions.
Important Note: Trading Risk
This indicator is intended for educational and informational purposes only and does not constitute investment advice or a recommendation for trading in any form whatsoever.
Trading in financial markets involves significant risk of capital loss. It is important to remember that past performance is not indicative of future results. All trading decisions are your sole responsibility. Never trade with money you cannot afford to lose.
Buy & Sell Volume (OWI)📊 Buy & Sell Volume (OWI) Indicator Guide
The Buy & Sell Volume (OWI) indicator is designed to provide a visual breakdown of buying and selling pressure in each candle, helping traders identify volume surges and potential market moves. It also includes a time filter to focus analysis during key trading hours.
⚙️ Setup & Inputs
When adding the indicator to your chart, you'll see several configurable inputs:
SMA Length : Sets the period for the Simple Moving Average (SMA) of total volume.
Enable Time Filter : Toggles whether to restrict analysis to US market hours (Eastern Time). |
Start Hour/Minute : Defines the beginning of the time filter window (default: 9:45 ET). |
End Hour/Minute : Defines the end of the time filter window (default: 16:15 ET). |
📈 How It Works
🔍 Volume Breakdown
Buy Volume: Estimated volume attributed to buyers, calculated based on candle position.
Sell Volume: Estimated volume attributed to sellers.
Total Volume SMA: A moving average of total volume to benchmark current activity.
⏰ Time Filter (Optional)
When enabled, the indicator only highlights volume spikes during the specified US market hours. This helps filter out noise from pre-market or after-hours trading.
🚨 Highlight Conditions
The indicator flags significant volume spikes with labels above the volume bars:
| Label | Condition |
| V+ | Volume is between 1.5× and 2× the SMA, during market hours (if enabled). |
| V++ | Volume exceeds 2× the SMA, during market hours (if enabled). |
💡 Tips
- Use shorter SMA lengths for more reactive volume analysis.
- Change the time filter if you're trading outside US market hours.
- Combine with candlestick patttern to confirm breakout or reversal signals.
Crypto Macro CockpitCrypto Macro Cockpit — Institutional Liquidity Regime Detection
🔍 Overview
This script introduces a modern macro framework for crypto market regime detection, leveraging newly added stablecoin market data on TradingView. It’s designed to guide traders through the evolving institutional era of crypto — where liquidity, not just price, is king.
🌐 Why This Matters
Historically, traditional proxies like M2 money supply or bond yields were referenced to infer macro liquidity shifts. But with the regulatory green light and institutional embrace of stablecoins, on-chain fiat liquidity is now directly observable.
Stablecoins = The new M2 for crypto.
This script utilizes real-time data from:
📊 CRYPTOCAP:STABLE.C (Total Stablecoin Market Cap)
📊 CRYPTOCAP:STABLE.C.D (Stablecoin Dominance)
to assess dry powder, risk appetite, and macro regime transitions.
📋 How to Read the Crypto Macro Cockpit
This dashboard updates every few bars and is organized into four actionable segments:
1️⃣ Macro Spreads
Metric --> Interpretation
Risk Flow --> Measures capital flow between stablecoins and total crypto market cap. → Green = risk deploying.
ETH vs BTC --> Shift in dominance between ETH and BTC → rotation gauge.
ETHBTC --> Price ratio movement → confirms leadership tilt.
ALTs (TOTAL3ES) --> Momentum in altcoin market, excluding BTC/ETH/stables → key for alt season timing.
2️⃣ Liquidity & Risk Appetite
Metric --> Interpretation
Liquidity --> Directional change in stablecoin cap → more stables = more dry powder.
Risk Appetite --> Inverse of stablecoin dominance → falling dominance = capital rotating into risk.
3️⃣ Stablecoin Context
Metric --> Interpretation
StableCap ROC --> Growth rate of stablecoin market cap → proxy for fiat inflows.
StableDom ROC --> Change in stablecoin dominance → reflects market caution or aggression.
4️⃣ Composite Labels
Label --> Interpretation
Rotation --> Sector tilt (BTC-led vs ETH/Alts)
Regime --> Synthesized macro environment → "Risk-ON", "Caution", "Waiting", or "Risk-OFF"
Background Color --> Optional tint reflecting regime for quick glance validation
All metrics are evaluated with directional arrows (▲/▼/•) and acceleration overlays, using user-defined thresholds scaled by timeframe for precision.
🔔 Built-in Alerts
Predefined, non-repainting alerts include:
Regime transitions
Sector rotations
Confirmed ETH/ALT rotations
Stablecoin market cap spikes
Risk Flow acceleration
You can use these alerts for discretionary trading or automated system triggers.
⚠️ Disclaimer
This script is for educational and informational purposes only. It does not constitute financial advice. Trading cryptocurrencies involves risk, and past performance does not guarantee future results. Always do your own research and manage risk responsibly.
✅ Ready to Use
No configuration needed — just load the script
Works on all timeframes (optimized for 1D)
Thresholds and smoothing are customizable
Table positioning and sizing is user-controlled
If you find this helpful, feel free to ⭐️ favorite or leave feedback. Questions welcome in the comments.
Let’s trade with macro awareness in this new era.
Prime NumbersPrime Numbers highlights prime numbers (no surprise there 😅), tokens and the recent "active" feature in "input".
🔸 CONCEPTS
🔹 What are Prime Numbers?
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.
Wikipedia: Prime number
🔹 Prime Factorization
The fundamental theorem of arithmetic states that every integer larger than 1 can be written as a product of one or more primes. More strongly, this product is unique in the sense that any two prime factorizations of the same number will have the same number of copies of the same primes, although their ordering may differ. So, although there are many different ways of finding a factorization using an integer factorization algorithm, they all must produce the same result. Primes can thus be considered the "basic building blocks" of the natural numbers.
Wikipedia: Fundamental theorem of arithmetic
Math Is Fun: Prime Factorization
We divide a given number by Prime Numbers until only Primes remain.
Example:
24 / 2 = 12 | 24 / 3 = 8
12 / 3 = 4 | 8 / 2 = 4
4 / 2 = 2 | 4 / 2 = 2
|
24 = 2 x 3 x 2 | 24 = 3 x 2 x 2
or | or
24 = 2² x 3 | 24 = 2² x 3
In other words, every natural/integer number above 1 has a unique representation as a product of prime numbers, no matter how the number is divided. Only the order can change, but the factors (the basic elements) are always the same.
🔸 USAGE
The Prime Numbers publication contains two use cases:
Prime Factorization: performed on "close" prices, or a manual chosen number.
List Prime Numbers: shows a list of Prime Numbers.
The other two options are discussed in the DETAILS chapter:
Prime Factorization Without Arrays
Find Prime Numbers
🔹 Prime Factorization
Users can choose to perform Prime Factorization on close prices or a manually given number.
❗️ Note that this option only applies to close prices above 1, which are also rounded since Prime Factorization can only be performed on natural (integer) numbers above 1.
In the image below, the left example shows Prime Factorization performed on each close price for the latest 50 bars (which is set with "Run script only on 'Last x Bars'" -> 50).
The right example shows Prime Factorization performed on a manually given number, in this case "1,340,011". This is done only on the last bar.
When the "Source" option "close price" is chosen, one can toggle "Also current price", where both the historical and the latest current price are factored. If disabled, only historical prices are factored.
Note that, depending on the chosen options, only applicable settings are available, due to a recent feature, namely the parameter "active" in settings.
Setting the "Source" option to "Manual - Limited" will factorize any given number between 1 and 1,340,011, the latter being the highest value in the available arrays with primes.
Setting to "Manual - Not Limited" enables the user to enter a higher number. If all factors of the manual entered number are in the 1 - 1,340,011 range, these factors will be shown; however, if a factor is higher than 1,340,011, the calculation will stop, after which a warning is shown:
The calculated factors are displayed as a label where identical factors are simplified with an exponent notation in superscript.
For example 2 x 2 x 2 x 5 x 7 x 7 will be noted as 2³ x 5 x 7²
🔹 List Prime Numbers
The "List Prime Numbers" option enables users to enter a number, where the first found Prime Number is shown, together with the next x Prime Numbers ("Amount", max. 200)
The highest shown Prime Number is 1,340,011.
One can set the number of shown columns to customize the displayed numbers ("Max. columns", max. 20).
🔸 DETAILS
The Prime Numbers publication consists out of 4 parts:
Prime Factorization Without Arrays
Prime Factorization
List Prime Numbers
Find Prime Numbers
The usage of "Prime Factorization" and "List Prime Numbers" is explained above.
🔹 Prime Factorization Without Arrays
This option is only there to highlight a hurdle while performing Prime Factorization.
The basic method of Prime Factorization is to divide the base number by 2, 3, ... until the result is an integer number. Continue until the remaining number and its factors are all primes.
The division should be done by primes, but then you need to know which one is a prime.
In practice, one performs a loop from 2 to the base number.
Example:
Base_number = input.int(24)
arr = array.new()
n = Base_number
go = true
while go
for i = 2 to n
if n % i == 0
if n / i == 1
go := false
arr.push(i)
label.new(bar_index, high, str.tostring(arr))
else
arr.push(i)
n /= i
break
Small numbers won't cause issues, but when performing the calculations on, for example, 124,001 and a timeframe of, for example, 1 hour, the script will struggle and finally give a runtime error.
How to solve this?
If we use an array with only primes, we need fewer calculations since if we divide by a non-prime number, we have to divide further until all factors are primes.
I've filled arrays with prime numbers and made libraries of them. (see chapter "Find Prime Numbers" to know how these primes were found).
🔹 Tokens
A hurdle was to fill the libraries with as many prime numbers as possible.
Initially, the maximum token limit of a library was 80K.
Very recently, that limit was lifted to 100K. Kudos to the TradingView developers!
What are tokens?
Tokens are the smallest elements of a program that are meaningful to the compiler. They are also known as the fundamental building blocks of the program.
I have included a code block below the publication code (// - - - Educational (2) - - - ) which, if copied and made to a library, will contain exactly 100K tokens.
Adding more exported functions will throw a "too many tokens" error when saving the library. Subtracting 100K from the shown amount of tokens gives you the amount of used tokens for that particular function.
In that way, one can experiment with the impact of each code addition in terms of tokens.
For example adding the following code in the library:
export a() => a = array.from(1) will result in a 100,041 tokens error, in other words (100,041 - 100,000) that functions contains 41 tokens.
Some more examples, some are straightforward, others are not )
// adding these lines in one of the arrays results in x tokens
, 1 // 2 tokens
, 111, 111, 111 // 12 tokens
, 1111 // 5 tokens
, 111111111 // 10 tokens
, 1111111111111111111 // 20 tokens
, 1234567890123456789 // 20 tokens
, 1111111111111111111 + 1 // 20 tokens
, 1111111111111111111 + 8 // 20 tokens
, 1111111111111111111 + 9 // 20 tokens
, 1111111111111111111 * 1 // 20 tokens
, 1111111111111111111 * 9 // 21 tokens
, 9999999999999999999 // 21 tokens
, 1111111111111111111 * 10 // 21 tokens
, 11111111111111111110 // 21 tokens
//adding these functions to the library results in x tokens
export f() => 1 // 4 tokens
export f() => v = 1 // 4 tokens
export f() => var v = 1 // 4 tokens
export f() => var v = 1, v // 4 tokens
//adding these functions to the library results in x tokens
export a() => const arraya = array.from(1) // 42 tokens
export a() => arraya = array.from(1) // 42 tokens
export a() => a = array.from(1) // 41 tokens
export a() => array.from(1) // 32 tokens
export a() => a = array.new() // 44 tokens
export a() => a = array.new(), a.push(1) // 56 tokens
What if we could lower the amount of tokens, so we can export more Prime Numbers?
Look at this example:
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193
Eight numbers contain the same number 8291.
If we make a function that removes recurrent values, we get fewer tokens!
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193
//is transformed to:
829111, 21, 23, 51, 59, 77, 87, 93
The code block below the publication code (// - - - Educational (1) - - - ) shows how these values were reduced. With each step of 100, only the first Prime Number is shown fully.
This function could be enhanced even more to reduce recurrent thousands, tens of thousands, etc.
Using this technique enables us to export more Prime Numbers. The number of necessary libraries was reduced to half or less.
The reduced Prime Numbers are restored using the restoreValues() function, found in the library fikira/Primes_4.
🔹 Find Prime Numbers
This function is merely added to show how I filled arrays with Prime Numbers, which were, in turn, added to libraries (after reduction of recurrent values).
To know whether a number is a Prime Number, we divide the given number by values of the Primes array (Primes 2 -> max. 1,340,011). Once the division results in an integer, where the divisor is smaller than the dividend, the calculation stops since the given number is not a Prime.
When we perform these calculations in a loop, we can check whether a series of numbers is a Prime or not. Each time a number is proven not to be a Prime, the loop starts again with a higher number. Once all Primes of the array are used without the result being an integer, we have found a new Prime Number, which is added to the array.
Doing such calculations on one bar will result in a runtime error.
To solve this, the findPrimeNumbers() function remembers the index of the array. Once a limit has been reached on 1 bar (for example, the number of iterations), calculations will stop on that bar and restart on the next bar.
This spreads the workload over several bars, making it possible to continue these calculations without a runtime error.
The result is placed in log.info() , which can be copied and pasted into a hardcoded array of Prime Number values.
These settings adjust the amount of workload per bar:
Max Size: maximum size of Primes array.
Max Bars Runtime: maximum amount of bars where the function is called.
Max Numbers To Process Per Bar: maximum numbers to check on each bar, whether they are Prime Numbers.
Max Iterations Per Bar: maximum loop calculations per bar.
🔹 The End
❗️ The code and description is written without the help of an LLM, I've only used Grammarly to improve my description (without AI :) )
Enhanced RSI KDE | Advanced FiltersThis is an enhanced version of the excellent RSI (Kernel Optimized) indicator originally created by @fluxchart. Full credit goes to fluxchart for the innovative KDE (Kernel Density Estimation) concept and the solid foundation that made this enhancement possible.
🙏 CREDITS & ACKNOWLEDGMENTS
Original Creator: @fluxchart - RSI (Kernel Optimized)
Original Concept: Kernel Density Estimation applied to RSI pivot analysis
Enhancement: Advanced filtering system and signal optimization- profitgang
License: Mozilla Public License 2.0
🚀 WHAT'S NEW IN THIS ENHANCED VERSION
Building upon fluxchart's brilliant KDE RSI foundation, this version adds:
🔥 Advanced Filtering System:
Multi-Timeframe Confluence - Confirms signals across higher timeframes
Volume Confirmation - Only signals on above-average volume
Volatility Range Filter - Avoids signals in choppy or extreme conditions
Trend Context Analysis - Considers overall market direction
Adaptive Pivot Detection - Adjusts sensitivity based on market volatility
🎯 Signal Quality Improvements:
Confluence Scoring - Each signal gets a quality score (1-6)
Label Cooldown System - Prevents chart clutter with smart spacing
Higher Activation Thresholds - More selective signal generation
Risk Management Integration - Auto stop-loss and take-profit levels
📊 Enhanced Dashboard:
Real-time filter status monitoring
KDE probability percentages
Confluence scores for both directions
Volume and volatility readings
⚙️ HOW IT WORKS
The indicator maintains fluxchart's core KDE methodology:
Collects RSI values at historical pivot points
Creates probability density functions using Gaussian/Uniform/Sigmoid kernels
Identifies high-probability zones for potential reversals
NEW: Multiple filters must align before generating signals, dramatically reducing false positives while maintaining the accuracy of high-probability setups.
🎛️ RECOMMENDED SETTINGS
Confluence Score: 5/6 (very selective)
Activation Threshold: Medium or High
Multi-Timeframe: Enabled with 2/2 alignment
Volume Filter: Enabled (1.5x threshold)
All other filters: Enabled for maximum quality
📈 BEST USE CASES
Swing Trading - Higher timeframe confirmation reduces whipsaws
Quality over Quantity - Fewer but much higher probability signals
Risk Management - Built-in stop/target levels for each signal
Multi-Asset Analysis - Works on stocks, crypto, forex, commodities
⚠️ IMPORTANT NOTES
This is a quality-focused indicator - expect fewer but better signals
Backtest thoroughly on your specific assets and timeframes
The original fluxchart indicator remains excellent for different trading styles
Consider this an alternative approach, not a replacement
🤝 COLLABORATION & FEEDBACK
Special thanks to @fluxchart for creating the original innovative KDE RSI concept. This enhancement wouldn't exist without that solid foundation.
Feel free to suggest improvements or share your results! The goal is to build upon great work in the community.
Bitcoin Expectile Model [LuxAlgo]The Bitcoin Expectile Model is a novel approach to forecasting Bitcoin, inspired by the popular Bitcoin Quantile Model by PlanC. By fitting multiple Expectile regressions to the price, we highlight zones of corrections or accumulations throughout the Bitcoin price evolution.
While we strongly recommend using this model with the Bitcoin All Time History Index INDEX:BTCUSD on the 3 days or weekly timeframe using a logarithmic scale, this model can be applied to any asset using the daily timeframe or superior.
Please note that here on TradingView, this model was solely designed to be used on the Bitcoin 1W chart, however, it can be experimented on other assets or timeframes if of interest.
🔶 USAGE
The Bitcoin Expectile Model can be applied similarly to models used for Bitcoin, highlighting lower areas of possible accumulation (support) and higher areas that allow for the anticipation of potential corrections (resistance).
By default, this model fits 7 individual Expectiles Log-Log Regressions to the price, each with their respective expectile ( tau ) values (here multiplied by 100 for the user's convenience). Higher tau values will return a fit closer to the higher highs made by the price of the asset, while lower ones will return fits closer to the lower prices observed over time.
Each zone is color-coded and has a specific interpretation. The green zone is a buy zone for long-term investing, purple is an anomaly zone for market bottoms that over-extend, while red is considered the distribution zone.
The fits can be extrapolated, helping to chart a course for the possible evolution of Bitcoin prices. Users can select the end of the forecast as a date using the "Forecast End" setting.
While the model is made for Bitcoin using a log scale, other assets showing a tendency to have a trend evolving in a single direction can be used. See the chart above on QQQ weekly using a linear scale as an example.
The Start Date can also allow fitting the model more locally, rather than over a large range of prices. This can be useful to identify potential shorter-term support/resistance areas.
🔶 DETAILS
🔹 On Quantile and Expectile Regressions
Quantile and Expectile regressions are similar; both return extremities that can be used to locate and predict prices where tops/bottoms could be more likely to occur.
The main difference lies in what we are trying to minimize, which, for Quantile regression, is commonly known as Quantile loss (or pinball loss), and for Expectile regression, simply Expectile loss.
You may refer to external material to go more in-depth about these loss functions; however, while they are similar and involve weighting specific prices more than others relative to our parameter tau, Quantile regression involves minimizing a weighted mean absolute error, while Expectile regression minimizes a weighted squared error.
The squared error here allows us to compute Expectile regression more easily compared to Quantile regression, using Iteratively reweighted least squares. For Quantile regression, a more elaborate method is needed.
In terms of comparison, Quantile regression is more robust, and easier to interpret, with quantiles being related to specific probabilities involving the underlying cumulative distribution function of the dataset; on the other expectiles are harder to interpret.
🔹 Trimming & Alterations
It is common to observe certain models ignoring very early Bitcoin price ranges. By default, we start our fit at the date 2010-07-16 to align with existing models.
By default, the model uses the number of time units (days, weeks...etc) elapsed since the beginning of history + 1 (to avoid NaN with log) as independent variable, however the Bitcoin All Time History Index INDEX:BTCUSD do not include the genesis block, as such users can correct for this by enabling the "Correct for Genesis block" setting, which will add the amount of missed bars from the Genesis block to the start oh the chart history.
🔶 SETTINGS
Start Date: Starting interval of the dataset used for the fit.
Correct for genesis block: When enabled, offset the X axis by the number of bars between the Bitcoin genesis block time and the chart starting time.
🔹 Expectiles
Toggle: Enable fit for the specified expectile. Disabling one fit will make the script faster to compute.
Expectile: Expectile (tau) value multiplied by 100 used for the fit. Higher values will produce fits that are located near price tops.
🔹 Forecast
Forecast End: Time at which the forecast stops.
🔹 Model Fit
Iterations Number: Number of iterations performed during the reweighted least squares process, with lower values leading to less accurate fits, while higher values will take more time to compute.
WaveTrend Dynamic (Lazy Bear Style)█ OVERVIEW
The WaveTrend Dynamic indicator (in the style of Lazy Bear) is an advanced tool based on the Exponential Smoothing Average (ESA), which adapts to the volatility and price of a financial instrument. It is more flexible than the classic WaveTrend but shares a similar concept of bands around a main oscillator line.
The indicator uses dynamic bands calculated as distances from the ESA, with their width adjustable via the "level" parameter. This allows it to be tailored to various markets, timeframes, and volatility conditions, making it easier to identify trends, reversal points, and buy/sell signals.
█ CONCEPTS
The WaveTrend Dynamic combines oscillator functions with trend analysis. Below, we explain the key components in a simple way, understandable even for beginner users.
Core Calculations
The indicator relies on the adaptive ESA and a few straightforward steps:
1 — ESA (Adaptive Average): Calculated as a smoothed average of the price (from high, low, and close, or HLC3) using the ESA Length parameter (default: 10). This number determines how many past candles are considered in the calculation. The ESA quickly responds to price changes, helping to track trends.
2 — Deviation (D): Measures how much the price deviates from the ESA, factoring in market volatility. This allows the indicator to adapt to different instruments.
3 — Price Distance Indicator (CI): Shows how far the price is from the ESA relative to market volatility. This forms the basis for the main indicator line, reacting to price movements.
4 — WT1 (WaveTrend 1): The main line, smoothing the Price Distance Indicator (CI) with the Average Length parameter (default: 21). It reflects the direction of price movement and momentum.
5 — WT2 (WaveTrend 2): A signal line that further smooths WT1 (with a period of 4). It helps confirm signals through crossovers with WT1.
6 — Bands (UpperBand and LowerBand): These form a dynamic channel around the ESA. Their width depends on the level parameter (default: 100). Wider bands result in fewer but more reliable signals. In the original WaveTrend, the oscillator bands use lower values, such as 50 or 60. To achieve classic oscillator signals (more frequent WT1/WT2 crossovers outside the bands), set the level to 50–60.
Trend Identification
The indicator identifies two types of trends:
• Major Trend: Determined by the position of WT1 relative to the ESA. When WT1 is above the ESA, it indicates a bullish trend. When below, it signals a bearish trend. Line and fill colors reflect this trend.
• Mini-Trend: Based on WT1 and WT2 crossovers. When the lines cross, they change to the same color, signaling short-term changes or reversal points. This is ideal for quick trading decisions.
Visuals and Effects
• WT1 and WT2 Lines: Scaled to price and displayed on the price chart for easier analysis.
• Fills: Between the bands (UpperBand/LowerBand) and between WT1/WT2, with a "wave" effect that adjusts transparency based on the trend (green for bullish, red for bearish).
• Signals: Three types—return-to-band, WT1/WT2 crossovers outside the bands, and crossovers inside the bands. Signals are displayed as triangles with different colors for buy and sell.
█ FEATURES
Detailed features of the indicator, aligned with the order of settings in the script:
• Basic Parameters: ESA Length — controls ESA smoothing; Average Length — affects WT1 responsiveness; level (WT Level) — adjusts band width for signal filtering.
• Display Elements: Options to show/hide ESA, bands, WT1/WT2; customizable colors for lines, fills, and the wave effect.
• Signals: Three signal groups (return-to-band, crossovers outside bands, crossovers inside bands) with display and color customization options.
█ HOW TO USE
1 — Add the indicator to your TradingView chart and adjust parameters: — Increase ESA Length and Average Length for low-volatility markets (e.g., stocks), or decrease for cryptocurrencies or forex. — Set level to 50–60 for classic WaveTrend signals with WT1/WT2 crossovers outside bands. The default value of 100 creates wider bands and fewer signals.
2 — Analyze trends: — Major trend (WT1 vs. ESA) shows the overall market direction. — Mini-trends (WT1/WT2 crossovers) help time short-term entries.
3 — Use signals: — Return-to-band: Buy at the lower band, sell at the upper band (mean-reversion). — Crossovers outside bands: Indicate strong momentum (with a lower level, e.g., 50). — Crossovers inside bands: Signal weaker trend changes.
4 — Combine with other tools: Use with volume, RSI, or support/resistance for better decisions. Test on historical data to optimize settings.
VWATR + VIX + VVIX Trend Regime### 🤖 VWATR + VIX + VVIX Trend Regime — Your Ultimate Volatility Dashboard! 📊
This isn't just another indicator; it's a comprehensive dashboard that brings together everything you need to understand market volatility focused on Futures. It merges price-based movement with market-wide fear and sentiment, giving you a powerful edge in your trading and risk management. Think of it as your personal volatility sidekick, ready to help you navigate market uncertainty like a pro!
***
### ✨ What's Inside?
* **VWATR (Volume-Weighted ATR):** A super-smart measure of price movement that pays close attention to where the big money is flowing.
* **VIX (The "Fear Gauge"):** Tracks the expected volatility of the S&P 500, essentially telling you how nervous the market is feeling.
* **VVIX (The "VIX of VIX"):** This one's for the pros! It measures how volatile the VIX itself is, giving you an early heads-up on potential fear spikes.
* **VX Term Structure:** A clever way to see if traders are preparing for a crisis. It compares the two nearest VIX futures to spot a rare signal called "backwardation."
* **Z-Scores:** It helps you spot when VIX and VVIX are at historic highs or lows, making it easier to predict when things might return to normal.
* **Divergence Score:** A unique tool to flag potential market shifts when the VIX and VVIX start moving in completely different directions.
* **Regime Classification:** The script automatically labels the market as "Full Panic," "Known Crisis," "Surface Calm," "Stress," or "Normal," so you always know where you stand.
* **Gradient Bars:** A visual treat! The background of your chart changes color to reflect real-time volatility shifts, giving you an instant feel for the market's mood.
* **Alerts:** Get push notifications on your phone for key events like "Full Panic" or "Backwardation" so you never miss a beat.
***
### 📝 Panel/Table Outputs
This is your mission control! The on-screen table gives you a clean summary of the current market regime, VIX and VVIX values, their ratios, term structure, Z-scores, and signals. Everything you need, right where you can see it.
***
### 🚀 How to Get Started
1. **Check your data:** You'll need access to real-time data for VIX, VVIX, VX1!, and VX2!. A paid subscription might be necessary for this.
2. **Add it to your chart:** Use the indicator on any chart (we've set it to `overlay=false`) to get your full volatility dashboard.
3. **Tweak it to perfection:** Head over to the Settings panel to customize the thresholds, colors, and your all-important "Jolt Value."
4. **Start trading smarter:** Use the dashboard to inform your trades, hedge your portfolio, and manage risk with confidence.
***
### ⚙️ Customization & Key Settings
* `showVWATR`: Toggle your price-volatility metric on or off.
* `showExpectedVol`: See the expected volatility as a percentage of the current price.
* `joltLevel`: This is a very important line on your chart! It's your personal trigger for when volatility is getting a little too wild. More on this below.
* `enableGradientBars`: Turn the awesome colored background on or off.
* `enableTable`: Hide or show your information table.
* `VIX/VVIX/VX1!/VX2! symbols`: If your broker uses different symbols for these, you can change them here.
* `VIX/VVIX thresholds`: Adjust these levels to fine-tune the indicator to your personal risk tolerance.
***
### 💡 Jolt Value: A Quick Guide for Smart Traders 🧠
The **jolt value** is your personal tripwire for volatility. Think of it as a warning light on your car's dashboard. You set the level, and when volatility (VWATR) crosses that line, you get an instant signal that something interesting is happening.
**How to Set Your Jolt Value:**
The ideal jolt value is dynamic. You want to keep it just a little above the current VIX level to stay alert without getting too many false alarms.
| Current VIX Level | Market Regime | Recommended Jolt Value |
| :--- | :--- | :--- |
| Under 15 | Calm/Complacent | 15–16 |
| 15–20 | Typical/Normal | 16–18 |
| 20–30 | Cautious/Active | 18–22 |
| Over 30 | Stress/Panic | 30+ |
**A Pro Tip for August 2025:** Since the VIX is hovering around 14.7, setting your jolt value to **16.5** is a great starting point for keeping an eye on things. If the VIX starts to climb above 20, you should adjust your jolt level to match the new reality.
***
### ⚠️ Important Things to Note
* You might experience some data delays if you're not on a paid TradingView plan or your broker does not provide real-time data for the VIX also VIX is only active during NY session, so it's not advised to use it outside of normal trading hours!
ATR: Body % + Ranges and AnomaliesATR: Body % + Ranges and Anomalies
This indicator provides a dual analysis of price bars to help you better understand market dynamics and volatility. It combines two powerful concepts into one tool: a candle body percentage and a range analysis with an anomaly-excluding average.
Key Features:
1. Candle Body Percentage
This feature plots the size of the candle's body as a percentage of its total high-low range.
A high percentage (e.g., above the 50% gray line) indicates strong, directional movement. The more solid the body is relative to its wicks, the more conviction is behind that move.
The 100% red line marks "Marubozu" candles—bars with no wicks, showing absolute control by buyers or sellers.
2. Range Analysis with Anomalies
This is a unique part of the indicator that helps you identify and understand normal vs. abnormal volatility.
Custom SMA: It calculates an average range of the last N bars, but it smartly excludes "anomalous" bars (spikes or unusually small ranges) from the calculation. This gives you a more reliable baseline for normal volatility.
Anomaly Detection: Bars are colored differently based on their range:
Blue: Small anomalies (range less than 0.5 * ATR). These often occur during periods of low liquidity or indecision.
Red: Large anomalies (range greater than 1.8 * ATR). These can signal a sudden burst of volatility, breakout events, or capitulation.
ATR Range % Label: The label on the chart shows the current bar's range as a percentage of the custom SMA. This tells you how much larger or smaller the current bar's range is compared to a clean average.
How to Use:
Spotting Trends: Use the Body % to confirm the strength of a trend. A series of bars with high body percentages can indicate a strong, healthy trend.
Identifying Volatility: Use the Range Analysis to find areas of interest. A large red anomaly bar could signal a significant event, while a series of blue anomalies might suggest the market is in a tight consolidation before a breakout.
Contextual Analysis: The combination of these tools can provide powerful context. For example, a bar with a high Body % and a red anomaly color suggests a strong, volatile move that could be a turning point or the start of a major trend.
Experiment with the input settings to fine-tune the ATR and SMA periods for different timeframes and assets.
Volume Delta Pressure Tracker by GSK-VIZAG-AP-INDIA📢 Title:
Volume Delta Pressure Tracker by GSK-VIZAG-AP-INDIA
📝 Short Description (for script title box):
Real-time volume pressure tracker with estimated Buy/Sell volumes and Delta visualization in an Indian-friendly format (K, L, Cr).
📃 Full Description
🔍 Overview:
This indicator estimates buy and sell volumes using candle structure (OHLC) and displays a real-time delta table for the last N candles. It provides traders with a quick view of volume imbalance (pressure) — often indicating strength behind price moves.
📊 Features:
📈 Buy/Sell Volume Estimation using the candle’s OHLC and Volume.
⚖️ Delta Calculation (Buy Vol - Sell Vol) to detect pressure zones.
📅 Time-stamped Table displaying:
Time (HH:MM)
Buy Volume (Green)
Sell Volume (Red)
Delta (Color-coded)
🔢 Indian Number Format (K = Thousands, L = Lakhs, Cr = Crores).
🧠 Fully auto-calculated — no need for tick-by-tick bid/ask feed.
📍 Neatly placed bottom-right table, customizable number of rows.
🛠️ Inputs:
Show Table: Toggle the table on/off
Number of Bars to Show: Choose how many recent candles to include (5–50)
🎯 Use Cases:
Identify hidden buyer/seller strength
Detect volume absorption or exhaustion
✅ Compatibility:
Works on any timeframe
Ideal for intraday instruments like NIFTY, BANKNIFTY, etc.
Ideal for volume-based strategy confirmation.
🖋️ Developed by:
GSK-VIZAG-AP-INDIA
Intraday Volume Pulse GSK-VIZAG-AP-INDIAIntraday Volume Pulse Indicator
Overview
This indicator is designed to track and visualize intraday volume dynamics during a user-defined trading session. It calculates and displays key volume metrics such as buy volume, sell volume, cumulative delta (difference between buy and sell volumes), and total volume. The data is presented in a customizable table overlay on the chart, making it easy to monitor volume pulses throughout the session. This can help traders identify buying or selling pressure in real-time, particularly useful for intraday strategies.
The indicator resets its calculations at the start of each new day and only accumulates volume data from the specified session start time onward. It uses simple logic to classify volume as buy or sell based on candle direction:
Buy Volume: Assigned to green (up) candles or half of neutral (doji) candles.
Sell Volume: Assigned to red (down) candles or half of neutral (doji) candles.
All calculations are approximate and based on available volume data from the chart. This script does not incorporate external data sources, order flow, or tick-level information—it's purely derived from standard OHLCV (Open, High, Low, Close, Volume) bars.
Key Features
Session Customization: Define the start time of your trading session (e.g., market open) and select from common timezones like Asia/Kolkata, America/New_York, etc.
Volume Metrics:
Buy Volume: Total volume attributed to bullish activity.
Sell Volume: Total volume attributed to bearish activity.
Cumulative Delta: Net difference (Buy - Sell), highlighting overall market bias.
Total Volume: Sum of all volume during the session.
Formatted Display: Volumes are formatted for readability (e.g., in thousands "K", lakhs "L", or crores "Cr" for large numbers).
Color-Coded Table: Uses a patriotic color scheme inspired by general themes (Saffron, White, Green) with dynamic backgrounds based on positive/negative values for quick visual interpretation.
Table Options: Toggle visibility and position (top-right, top-left, etc.) for a clean chart layout.
How to Use
Add to Chart: Apply this indicator to any symbol's chart (works best on intraday timeframes like 1-min, 5-min, or 15-min).
Configure Inputs:
Session Start Hour/Minute: Set to your market's open time (default: 9:15 for Indian markets).
Timezone: Choose the appropriate timezone to align with your trading hours.
Show Table: Enable/disable the metrics table.
Table Position: Place the table where it doesn't obstruct your view.
Interpret the Table:
Monitor for spikes in buy/sell volume or shifts in cumulative delta.
Positive delta (green) suggests buying pressure; negative (red) suggests selling.
Use alongside price action or other indicators for confirmation—e.g., high total volume with positive delta could indicate bullish momentum.
Limitations:
Volume classification is heuristic and not based on actual order flow (e.g., it splits doji volume evenly).
Data accumulation starts from the session time and resets daily; historical backtesting may be limited by the max_bars_back=500 setting.
This is for educational and visualization purposes only—do not use as sole basis for trading decisions.
Calculation Details
Session Filter: Uses timestamp() to define the session start and filters bars with time >= sessionStart.
New Day Detection: Resets volumes on daily changes via ta.change(time("D")).
Volume Assignment:
Buy: Full volume if close > open; half if close == open.
Sell: Full volume if close < open; half if close == open.
Cumulative Metrics: Accumulated only during the session.
Formatting: Custom function f_format() scales large numbers for brevity.
Disclaimer
This script is for educational and informational purposes only. It does not provide financial advice or signals to buy/sell any security. Always perform your own analysis and consult a qualified financial professional before making trading decisions.
© 2025 GSK-VIZAG-AP-INDIA
Awesome Indicator# Moving Average Ribbon with ADR% - Complete Trading Indicator
## Overview
The **Moving Average Ribbon with ADR%** is a comprehensive technical analysis indicator that combines multiple analytical tools to provide traders with a complete picture of price trends, volatility, relative performance, and position sizing guidance. This multi-faceted indicator is designed for both swing and positional traders looking for data-driven entry and exit signals.
## Key Components
### 1. Moving Average Ribbon System
- **4 Customizable Moving Averages** with default periods: 13, 21, 55, and 189
- **Multiple MA Types**: SMA, EMA, SMMA (RMA), WMA, VWMA
- **Color-coded visualization** for easy trend identification
- **Flexible configuration** allowing users to modify periods, types, and colors
### 2. Average Daily Range Percentage (ADR%)
- Calculates the average daily volatility as a percentage
- Uses a 20-period simple moving average of (High/Low - 1) * 100
- Helps traders understand the stock's typical daily movement range
- Essential for position sizing and stop-loss placement
### 3. Volume Analysis (Up/Down Ratio)
- Analyzes volume distribution over the last 55 periods
- Calculates the ratio of volume on up days vs down days
- Provides insight into buying vs selling pressure
- Values > 1 indicate more buying volume, < 1 indicate more selling volume
### 4. Absolute Relative Strength (ARS)
- **Dual timeframe analysis** with customizable reference points
- **High ARS**: Performance relative to benchmark from a high reference point (default: Sep 27, 2024)
- **Low ARS**: Performance relative to benchmark from a low reference point (default: Apr 7, 2025)
- Uses NSE:NIFTY as default comparison symbol
- Color-coded display: Green for outperformance, Red for underperformance
### 5. Relative Performance Table
- **5 timeframes**: 1 Week, 1 Month, 3 Months, 6 Months, 1 Year
- Shows stock performance **relative to benchmark index**
- Formula: (Stock Return - Index Return) for each period
- **Color coding**:
- Lime: >5% outperformance
- Yellow: -5% to +5% relative performance
- Red: <-5% underperformance
### 6. Dynamic Position Allocation System
- **6-factor scoring system** based on price vs EMAs (21, 55, 189)
- Evaluates:
- Price above/below each EMA
- EMA alignment (21>55, 55>189, 21>189)
- **Allocation recommendations**:
- 100% allocation: Score = 6 (all bullish signals)
- 75% allocation: Score = 4
- 50% allocation: Score = 2
- 25% allocation: Score = 0
- 0% allocation: Score = -2, -4, -6 (bearish signals)
## Display Tables
### Performance Table (Top Right)
Shows relative performance vs benchmark across multiple timeframes with intuitive color coding for quick assessment.
### Metrics Table (Bottom Right)
Displays key statistics:
- **ADR%**: Average Daily Range percentage
- **U/D**: Up/Down volume ratio
- **Allocation%**: Recommended position size
- **High ARS%**: Relative strength from high reference
- **Low ARS%**: Relative strength from low reference
## How to Use This Indicator
### For Trend Analysis
1. **Moving Average Ribbon**: Look for price above ascending MAs for bullish trends
2. **MA Alignment**: Bullish when shorter MAs are above longer MAs
3. **Color coordination**: Use consistent color scheme for quick visual analysis
### For Entry/Exit Timing
1. **Performance Table**: Enter when showing consistent outperformance across timeframes
2. **Volume Analysis**: Confirm entries with U/D ratio > 1.5 for strong buying
3. **ARS Values**: Look for positive ARS readings for relative strength confirmation
### For Position Sizing
1. **Allocation System**: Use the recommended allocation percentage
2. **ADR% Consideration**: Adjust position size based on volatility
3. **Risk Management**: Lower allocation in high ADR% stocks
### For Risk Management
1. **ADR% for Stop Loss**: Set stops at 1-2x ADR% below entry
2. **Relative Performance**: Reduce positions when consistently underperforming
3. **Volume Confirmation**: Be cautious when U/D ratio deteriorates
## Best Practices
### Timeframe Recommendations
- **Intraday**: Use lower MA periods (5, 13, 21, 55)
- **Swing Trading**: Default settings work well (13, 21, 55, 189)
- **Position Trading**: Consider higher periods (21, 50, 100, 200)
### Market Conditions
- **Trending Markets**: Focus on MA alignment and relative performance
- **Sideways Markets**: Rely more on ADR% for range trading
- **Volatile Markets**: Reduce allocation percentage regardless of signals
### Customization Tips
1. Adjust reference dates for ARS calculation based on significant market events
2. Change comparison symbol to sector-specific indices for better relative analysis
3. Modify MA periods based on your trading style and market characteristics
## Technical Specifications
- **Version**: Pine Script v6
- **Overlay**: Yes (plots on price chart)
- **Real-time Updates**: Yes
- **Data Requirements**: Minimum 252 bars for complete calculations
- **Compatible Timeframes**: All standard timeframes
## Limitations
- Performance calculations require sufficient historical data
- ARS calculations depend on selected reference dates
- Volume analysis may be less reliable in low-volume stocks
- Relative performance is only as good as the chosen benchmark
This indicator is designed to provide a comprehensive analysis framework rather than simple buy/sell signals. It's recommended to use this in conjunction with your overall trading strategy and risk management rules.
US Macro Cycle (Z-Score Model)US Macro Cycle (Z-Score Model)
This indicator tracks the US economic cycle in real time using a weighted composite of seven macro and market-based indicators, each converted into a rolling Z-score for comparability. The model identifies the current phase of the cycle — Expansion, Peak, Contraction, or Recovery — and suggests sector tilts based on historical performance in each phase.
Core Components:
Yield Curve (10y–2y): Positive & steepening = growth; inverted = slowdown risk.
Credit Spreads (HYG/LQD): Tightening = risk-on; widening = risk-off.
Sector Leadership (Cyclicals vs. Defensives): Measures market leadership regime.
Copper/Gold Ratio: Higher copper = growth signal; higher gold = defensive.
SPY vs. 200-day MA: Equity trend strength.
SPY/IEF Ratio: Stocks vs. bonds relative strength.
VIX (Inverted): Low/falling volatility = supportive; high/rising = risk-off.
Methodology:
Each series is transformed into a rolling Z-score over the selected lookback period (optionally using median/MAD for robustness and winsorization to clip outliers).
Z-scores are combined using user-defined weights and normalized.
The smoothed composite is compared against phase thresholds to classify the macro environment.
Features:
Customizable Weights: Emphasize the indicators most relevant to your strategy.
Adjustable Thresholds: Fine-tune cycle phase definitions.
Background Coloring: Visual cue for the current phase.
Summary Table: Displays composite Z, confidence %, and individual Z-scores.
Alerts: Trigger when the phase changes, with details on the composite score and recommended tilt.
Use Cases:
Align sector rotation or relative strength strategies with the macro backdrop.
Identify favorable or defensive phases for tactical allocation.
Monitor macro turning points to manage portfolio risk.
It's doesn't fill nan gaps so there is quite a bit of zeroes, non-repainting.
MT High/Low Boxes"Box out the High/Low at User-Defined Time Frame"
This feature allows users to set a custom time frame via an input panel, following TradingView's time frame conventions (e.g., "60," "240," "D," etc.).
The script dynamically captures timestamps for each custom interval to detect the start of new segments.
The box width is calculated based on the number of bars within the custom time frame, ensuring accurate coverage of the corresponding time range.
A central dashed line (yellow dotted) reflects the real-time midpoint between the high and low of the interval.
The background color adjusts based on bullish/bearish bias, comparing the opening price to the current closing price.
Simply select your desired time frame in the indicator settings—flexible and compatible with multiple time frames, including non-minute/hour units (e.g., daily, weekly).