지표 및 전략
9:30 AM Open Percentage Lines//@version=5
indicator("9:30 AM Open Percentage Lines", overlay=true)
// Define the market open time in New York (or your local time zone if different)
// This is for 9:30 AM
var float opening_price = na
// Check if the current bar is the first one of the day at 9:30 AM
is_930_bar = (dayofweek == dayofweek.monday or dayofweek == dayofweek.tuesday or dayofweek == dayofweek.wednesday or dayofweek == dayofweek.thursday or dayofweek == dayofweek.friday) and hour(time("America/New_York")) == 9 and minute(time("America/New_York")) == 30
// On the first bar that meets the criteria, capture the opening price
if is_930_bar
opening_price := open
// Calculate the percentage levels based on the captured opening price
fivePercentAbove = opening_price * 1.05
sevenPercentAbove = opening_price * 1.07
twentySevenPercentAbove = opening_price * 1.27
// Plot the lines on the chart
// The `na` condition ensures the line is only plotted after the 9:30 AM bar has passed
plot(not na(opening_price) ? fivePercentAbove : na, title="5% Above 9:30 AM Open", color=color.new(color.rgb(255, 12, 12), 0), linewidth=2, trackprice=false)
plot(not na(opening_price) ? sevenPercentAbove : na, title="7% Above 9:30 AM Open", color=color.new(color.rgb(0, 150, 255), 0), linewidth=2, trackprice=false)
plot(not na(opening_price) ? twentySevenPercentAbove : na, title="27% Above 9:30 AM Open", color=color.new(color.rgb(255, 0, 0), 0), linewidth=2, trackprice=false)
black belt cloudThe EMA Cloud indicator highlights market trend direction by filling the space between multiple exponential moving averages with dynamic color-coded clouds.
When the market is in a bullish alignment, the cloud turns green, signaling strong upward momentum.
When the market shifts into a bearish alignment, the cloud turns red, warning of downside pressure.
During periods of mixed or uncertain conditions, the cloud appears yellow to indicate potential consolidation or indecision.
The indicator also includes alerts that trigger only on trend changes, helping traders react quickly when momentum shifts.
This tool makes it easy to:
Visualize trend strength at a glance
Avoid choppy, sideways market conditions
Combine with entry/exit strategies for improved decision-making
2ATR / Current Price %### **Real-Time 2ATR Volatility Ratio Indicator**
---
### **Overview**
This indicator provides a quick and visual way to understand market volatility by calculating the ratio between the **2ATR (Average True Range)** and the **current price**.
* **ATR (Average True Range)** is a widely-used measure of market volatility, showing the average price movement over a specific period.
* **2ATR** represents a price move that is twice the average volatility. Traders often use this value as a benchmark for potential support/resistance levels or for setting a dynamic stop-loss.
### **Key Features**
* **Real-Time Calculation**: Unlike many indicators that rely on the previous candle's close, this script calculates the 2ATR ratio using the **real-time current price**, providing you with up-to-the-second data.
* **Intuitive Display**: The final percentage value is shown in a clear **yellow label** at the **bottom-right** of your chart, making it easy to monitor without cluttering your view.
* **Customizable Input**: You can adjust the `ATR Period` setting to change the sensitivity of the volatility calculation, allowing you to adapt the indicator to different trading styles and timeframes.
### **How to Use It**
This tool is especially useful for **risk management and setting stop-loss orders**. The percentage displayed on the label tells you how much the price would need to move from its current level to equal a 2ATR change.
**Example**: If the indicator shows **3.5%**, it means a price drop of 3.5% from the current level would be equal to a 2ATR move. This gives you a clear and quantifiable number to help you set a **logical stop-loss** or to quickly assess the potential downside risk before entering a trade.
Triple-EMA Cloud (3× configurable EMAs + timeframe + fill)About This Script
Name: Triple-EMA Cloud (3× configurable EMAs + timeframe + fill)
What it does:
The script plots three Exponential Moving Averages (EMAs) on your chart.
You can set each EMA’s length (how many bars or days it averages over), source (for example, closing price, opening price, or the midpoint of high + low), and timeframe (you can have one EMA use daily data, another hourly data, etc.).
The indicator draws a “cloud” or channel by shading the area between the outermost two EMAs of the three. This lets you see a band or zone that the price is moving in, defined by those EMAs.
You also get full control over how each of the three EMA‐lines looks: color, thickness, transparency, and plot style (solid line, steps, circles, etc.).
How to Use It (for Beginners)
Here’s how a trader who’s new to charts can use this tool, especially when looking for pullbacks or undercut price action.
Key Concepts
Trend: Imagine the market price is generally going up or down. EMAs are a way to smooth out price movements so you can see the trend more clearly.
Pullback: When a price has been going up (an uptrend), sometimes it dips down a little before going up again. That dip is the pullback. It’s a chance to enter or add to a position at a “better price.”
Undercut: This is when price drops below an important level (for example an EMA) and then comes back up. It looks like it broke below, but then it recovers. That may show reverse pressure or strength building.
How the Script Helps With Pullbacks & Undercuts
Marking Trend Zones with the Cloud
The cloud between the outer EMA lines gives you a zone of expected support/resistance. If the price is above the cloud, that zone can act like a “floor” in uptrends; if it is below, the cloud might act like a “ceiling” in downtrends.
Watching Price vs the EMAs
If the price pulls back toward the cloud (or toward one of the EMAs) and then bounces back up, that’s a signal that the uptrend might continue.
If the price undercuts (goes a bit below) one of the EMAs or the cloud and then returns above it, that can also be a signal. It suggests that even though there was a temporary drop, buyers stepped in.
Using the Three EMAs for Confirmation
Because the script uses three EMAs, you can see how tightly or loosely they are spaced.
If all three EMAs are broadly aligned (for example, in an uptrend: shorter length above longer length, each pulling from reliable price source), that gives more confidence in trend strength.
If the middle EMA (or different source/timeframe) is holding up as support while others are above, it strengthens signal.
Entry & Exit Points
Entry: For example, after a pullback toward the cloud or “mid‐EMA”, wait for price to show a bounce up. That could be a better entry than buying at the top.
Stop Loss / Risk: You might place a stop loss just below the cloud or the lowest of your selected EMAs so that if price breaks through, the idea is invalidated.
Profit Target: Could be a recent high, resistance level, or a fixed reward-risk multiple (for example aiming to make twice what you risked).
Practical Steps for New Traders
Set up the EMAs
Choose simple lengths like 10, 21, 50.
For example, EMA #1 = length 10, source Close, timeframe “current chart”; EMA #2 = length 21, source (H+L)/2; EMA #3 = length 50, maybe timeframe daily.
Observe the Price Action
When price moves up, then dips, see if it comes back near the shaded cloud or one of the EMAs.
See if the dip touches the EMAs lightly (not a big drop) and then price starts climbing again.
Look for undercuts
If price briefly goes below a line (or below cloud) and then closes back above, that’s undercut + recovery. That bounce back is often meaningful.
Manage risk
Only put in money you can afford to lose.
Use small position size until you get comfortable.
Use stop-loss (as mentioned) in case the price doesn’t bounce as expected.
Practice
Put this indicator on charts (stocks you follow) in past time periods. See how price behaved with pullbacks / undercuts relative to the EMAs & cloud. This helps you learn to see signals.
What It Doesn’t Do (and What to Be Careful Of)
It doesn’t predict the future — it simply shows zones and trends. Price can still break down through the cloud.
In a “choppy” market (i.e. when price is going up and down without a clear trend), signals from EMAs / clouds are less reliable. You’ll get more “false bounces.”
Under / overshoots & big news events can break through clean levels, so always watch for confirmation (volume, price behavior) before putting big money in.
MGY Smart Fibonacci ProMGY Smart Fibonacci Pro Indicator
Overview:
MGY Smart Fibonacci Pro is an advanced multi-timeframe Fibonacci indicator that automatically adapts to your current chart timeframe. It intelligently displays the most relevant Fibonacci retracement levels based on the higher timeframes, providing traders with dynamic support and resistance levels.
Stocks Sessions TableThe stock market open session table is a great way to keep an eye on the market's open and close. This is aimed at the UK traders working with the BST timezone
Alert N seconds before candle closeThe indicator alerts about the closing of the candle in N seconds.
Instruction:
1. Add an indicator
2. Specify the time in the indicator settings
3. Alt+A, Condition - choose indicator
MA//@version=5
indicator("MA20 và EMA9", overlay=true)
// === Input tham số ===
lengthMA = input.int(20, "Độ dài MA", minval=1)
lengthEMA = input.int(9, "Độ dài EMA", minval=1)
// === Tính toán đường trung bình ===
ma20 = ta.sma(close, lengthMA) // Simple Moving Average 20
ema9 = ta.ema(close, lengthEMA) // Exponential Moving Average 9
// === Vẽ ra biểu đồ ===
plot(ma20, color=color.red, linewidth=2, title="MA20")
plot(ema9, color=color.blue, linewidth=2, title="EMA9")
Tape Pressure Proxy — CVD Panel (Oscillators) v1.1 2. Add TV_TapePressure_CVDPanel.pine in a new pane to see CVD, CVD slope, and Imbalance (Z) histogram with thresholds.
3. Set alerts on the overlay script:
• “Bull Tape Pressure” → long scalps
• “Bear Tape Pressure” → short/puts scalps
4. Tune: imbThresh (0.6–1.2 typical), deltaLen (10–30), and volume filter per symbol/timeframe.
delta_leverage_lib🚀 Delta Leverage Library - Exchange Max Leverage Data
Comprehensive Pine v6 library providing maximum leverage data for USDT perpetual contracts across major exchanges. Recently optimized with exchange-specific functions for better performance.
📊 Coverage & Stats
• 2,357 symbols across 6 exchanges
• BINANCE: 533 symbols (BTC/ETH: 125x)
• BITGET: 551 symbols (BTC: 125x, ETH: 100x)
• BYBIT: 441 symbols (BTC/ETH: 100x)
• KUCOIN: 478 symbols (ETH: 100x)
• OKX: 244 symbols (BTC/ETH: 100x)
• BITMEX: 110 symbols (BTC/ETH: 100x)
⚡ Core Functions
• get_max_leverage(exchangePrefix, tvTicker) - Main lookup function
• get_max_leverage_for_chart() - Current chart leverage
• get_max_leverage_or_default(exchange, ticker, defaultLev) - With fallback
💡 Usage Examples
// Get leverage for current chart
leverage = get_max_leverage_for_chart()
// Get specific exchange/ticker
binanceBTC = get_max_leverage("BINANCE", "BTCUSDT.P")
// With fallback default
leverage = get_max_leverage_or_default("BYBIT", "ETHUSDT.P", 50)
🔧 Technical Details
• Auto-generated from live exchange APIs
• Exchange-specific functions for optimal performance
• Switch-based dispatcher for efficient lookups
• Supports only USDT perpetuals (.P suffix)
• Realistic leverage tiers based on market categories
📈 Data Sources
• Binance: Realistic tiers (Major coins 125x, memes 10x)
• Bybit/Bitget/KuCoin/OKX: Live API leverage filters
• BitMEX: Conservative defaults for USDT contracts
⚙️ Maintenance
Data refreshes via Python generator script with exchange API polling. Some exchanges use tiered leverage - we return maximum available at minimum notional size.
Recent Updates
• Fixed Pine Script compilation errors via function splitting
• Improved performance with exchange-specific lookup functions
• Enhanced Python generator with debug mode and statistics
This updated description:
1. **Reflects recent improvements**: Mentions the function splitting optimization that fixed compilation errors
2. **Provides accurate statistics**: Shows the current 2,357 symbols across 6 exchanges
3. **Better organized**: Uses clear sections with emojis for visual appeal
4. **Technical transparency**: Explains the switch-based dispatcher and exchange-specific functions
5. **Practical usage**: Shows realistic code examples
6. **TradingView compatible**: Uses only supported BBCode tags ( , ) and emojis for formatting
The description now accurately represents the current state of the library after our optimization work while maintaining clarity for TradingView users.
get_max_leverage_binance(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bitget(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bitmex(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bybit(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_kucoin(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_okx(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage(exchangePrefix, tvTicker)
Parameters:
exchangePrefix (string)
tvTicker (string)
get_max_leverage_for_chart()
get_max_leverage_or_default(exchangePrefix, tvTicker, defaultLev)
Parameters:
exchangePrefix (string)
tvTicker (string)
defaultLev (int)
KT_Global Bond Yields by CountryGlobal Bond Yields Indicator Summary
The Global Bond Yields by Country indicator, developed for Trading View (Pine Script v5), provides a comprehensive tool for visualizing and analyzing government bond yields across multiple countries and maturities. Below are its key features:
Features
Country Selection: Choose from 20 countries, including the United States, China, Japan, Germany, United Kingdom, and more, to display their respective bond yields.
Multiple Maturities: Supports 18 bond maturities ranging from 1 month to 40 years, allowing users to analyze short-term to long-term yield trends.
Customizable Display:
Toggle visibility for each maturity (1M, 3M, 6M, 1Y, 2Y, 3Y, 4Y, 5Y, 6Y, 7Y, 8Y, 9Y, 10Y, 15Y, 20Y, 25Y, 30Y, 40Y) individually.
Option to show or hide all maturities with a single toggle for streamlined analysis.
10Y-2Y Yield Spread: Plots the difference between 10-year and 2-year bond yields, a key indicator of yield curve dynamics, with an option to enable/disable.
Zero Line Reference: Displays a dashed grey horizontal line at zero for clear visual reference.
Color-Coded Plots: Each maturity is plotted with a distinct color, ranging from lighter shades (short-term) to darker shades (long-term), for easy differentiation.
Country Label: Displays the selected country's name as a large, prominent label on the chart for quick identification.
Error Handling: Alerts users if an invalid country is selected, ensuring robust operation.
Data Integration: Fetches bond yield data from Trading View's database (e.g., TVC:US10Y) with support for ignoring invalid symbols to prevent errors.
This indicator is ideal for traders and analysts monitoring global fixed-income markets, yield curve shapes, and cross-country comparisons.
Custom Trade Checklist by [YSFX]# Custom Trade Checklist: Your On-Chart Trading Co-Pilot
## Overview
Ever taken a trade based on impulse, only to realize you forgot a key step in your analysis? The Custom Trade Checklist is a simple yet powerful on-chart utility designed to help you remain disciplined and consistent with your trading strategy.
By externalizing your trading plan into a visible, interactive checklist, you can reduce emotional decision-making and systematically verify your criteria before entering or exiting a trade. This tool acts as your personal co-pilot, ensuring you follow your rules on every single trade.
## Key Features
✅ Fully Customizable Rules: Define up to 10 unique checklist items tailored to your specific trading strategy. Examples include "Market Structure Aligned?", "RSI Oversold?", "News Events Checked?", or "Risk/Reward > 2:1?".
⚪ Dynamic Status Tracking: Use a simple dropdown menu in the settings to mark each rule with intuitive symbols like:
✅ / ✓ - Completed / True
❌ / ✕ - Failed / False
🟡 - Pending / Caution
⚪ - Neutral / Not Checked
And many more for complete flexibility.
📋 Clean & Minimalist Display: The checklist is presented in a clean, unobtrusive table that can be positioned in any corner of your chart, ensuring it provides guidance without cluttering your analysis.
⚙️ Flexible Configuration:
Choose the maximum number of entries to display.
Optionally hide disabled checklist items to keep your view focused on what's active.
Customize the table title to match your strategy (e.g., "Pre-Trade Checklist", "Swing Trade Rules").
🎨 Complete Color Control: Personalize every aspect of the table's appearance. You can independently set the colors for the title, text, background, border, and each individual status symbol to perfectly match your chart's theme.
## How to Use
Add the Indicator to your chart.
Open the Settings Panel by clicking the gear icon (⚙️) on the indicator.
Define Your Rules:
Go through Entry 1 to Entry 10.
For each rule you want to use, check the box to enable it.
In the text field, write your rule (e.g., "Price above 200 EMA").
Update Your Status: Before placing a trade, go back into the settings and update the status dropdown for each rule based on your analysis.
Customize Appearance:
Under the "General" tab, change the table title and position.
Under the "Colors" tab, adjust the colors to your liking.
## Who Is This For?
This tool is perfect for:
Discretionary Traders who need to enforce a consistent set of rules.
New Traders looking to build good habits and internalize their trading plan.
Systematic Traders who want a final pre-flight check before executing a trade.
Anyone working on improving their trading psychology and reducing impulsive actions.
This indicator does not generate signals or trading advice; it is a utility to support the trader's own process and discipline. We hope it helps you achieve greater consistency in your trading journey!
EMA 9 vs 21 Spread VarianceEMA 9 vs 21 Spread Variance
What it does
Tracks the distance between EMA 9 and EMA 21, then measures how volatile that distance has been over your chosen lookback. The indicator plots the EMA spread around zero and a rolling variance of that spread. Rising variance signals expanding dispersion between the fast and slow EMAs, which often precedes momentum bursts or regime shifts. Falling variance points to compression and mean-reversion conditions.
How it is calculated
Fast EMA and slow EMA are computed on the selected source.
Spread = EMA9 minus EMA21, plotted around zero.
Variance = rolling variance of the spread over Variance Lookback. Variance is always non-negative.
For readability you can show the variance either on its raw scale, or fitted to the spread’s recent range so both lines are comparable in one pane.
How to read it
Spread near zero with variance rising suggests an impending expansion from balance.
Large positive spread with elevated variance confirms a strong up-trend that is still dynamic.
Large negative spread with elevated variance confirms a strong down-trend that is still dynamic.
Variance rolling over after a run warns that momentum dispersion is cooling and that a consolidation or pullback is likely.
The horizontal zero line applies to the spread only. Variance does not cross zero.
Inputs
Source: price series for EMAs.
Fast EMA Length and Slow EMA Length: defaults 9 and 21.
Variance Lookback: window for the spread variance, common ranges 20 to 100 on intraday charts and 50 to 200 on higher timeframes.
Show spread line and Fit variance to spread scale: display controls.
Suggested use
Combine with your breakout logic. Look for variance expansion from low levels as a filter before taking continuation entries.
Use as a volatility context for EMA cross systems. Crosses that occur with rising variance tend to travel farther than crosses that occur during compression.
Caveats
Variance reacts to spikes in the spread, so it can jump around news bars. Smoothing reduces noise but adds lag. Consider pairing with ATR or session filters if you only want signals during liquid hours.
ITCRM CCL (aprox BCRA)This script calculates an approximation of the Real Multilateral Exchange Rate Index (ITCRM) with the CCL dollar, replicating the methodology of the Central Bank of Argentina (BCRA) but using the financial exchange rate (AL30C/AL30D) as a base.
Bilateral ARS/currency rates are built for Argentina’s main trading partners (Brazil, USA, Eurozone, China, etc.).
A weighted geometric average is applied according to trade shares.
The index is normalized to base 100 at the start of the series.
⚠️ This is a reference version, not official.
ITCRM CCL (aprox BCRA)This script calculates an approximation of the Real Multilateral Exchange Rate Index (ITCRM) with the CCL dollar, replicating the methodology of the Central Bank of Argentina (BCRA) but using the financial exchange rate (AL30C/AL30D) as a base.
Bilateral ARS/currency rates are built for Argentina’s main trading partners (Brazil, USA, Eurozone, China, etc.).
A weighted geometric average is applied according to trade shares.
The index is normalized to base 100 at the start of the series.
⚠️ This is a reference version, not official.
EMA 200 MultiTF G/R + Cross Alerts by LifeHack Trader1. Indicator Setup
The script starts by defining the version of Pine Script (v5) and creating an indicator called "EMA 200 MultiTF G/R + Cross Alerts by LifeHack Trader."
The overlay=true parameter ensures that the indicator is plotted directly on the price chart.
2. Function to Get EMA200
A custom function getEma200 is defined to retrieve the 200-period Exponential Moving Average (EMA) for a specified timeframe (tf).
This function uses the request.security function to fetch the close price's EMA from different timeframes.
3. Calculate EMA200 for Multiple Timeframes
The script calculates the EMA200 for four timeframes: 15 minutes ("15"), 1 hour ("60"), 4 hours ("240"), and 1 day ("D").
These values are stored in variables (ema15, ema1h, ema4h, ema1d) and represent the EMA for each timeframe.
4. Determine Price Above or Below EMA200 (G/R)
For each timeframe, the script checks whether the closing price is above or below the EMA200.
It uses boolean checks to determine if the price is above the EMA200, assigning the status "G" (Green) for above and "R" (Red) for below.
5. Cross Signal Detection (Up/Down)
The script detects crossovers and crossunders between the price and EMA200 for each timeframe.
A crossover signal is detected when the price crosses above the EMA200 (bullish), and a crossunder signal is detected when the price crosses below the EMA200 (bearish).
These signals are stored in separate variables (crossUp, crossDown).
6. Display a Table with G/R Status and Cross Alerts
A table is created and displayed in the top-right corner of the chart. The table shows the status (G or R) for each timeframe and the cross signal (▲ for crossover, ▼ for crossunder, or - for no cross event).
The table is updated with the respective values for each timeframe every time a new bar is formed.
7. Alert Conditions
The script defines alert conditions based on the crossovers and crossunders.
When a price crosses above the EMA200 (cross-up), an alert is triggered for a potential buy opportunity. When the price crosses below the EMA200 (cross-down), an alert is triggered for a potential sell opportunity.
Alerts are configured for each timeframe (15 minutes, 1 hour, 4 hours, and 1 day).
This script provides a comprehensive system for monitoring price action relative to the EMA200 on multiple timeframes, highlighting crossovers, and delivering visual feedback and alerts based on the price's relationship with the EMA.
Multiplied and Divided Moving Average ### Multiplied and Divided Moving Average Indicator
**Description**:
The "Multiplied and Divided Moving Average" indicator is a customizable tool for TradingView users, designed to create dynamic bands around a user-selected moving average (MA). It calculates a moving average (SMA, EMA, WMA, VWMA, or RMA) and generates a user-defined number of lines above and below it by multiplying and dividing the MA by linearly spaced factors. These bands serve as potential support and resistance levels, aiding in trend identification, mean reversion strategies, or breakout detection. Optional Buy/Sell labels appear when the price crosses below the divided MAs (Buy) or above the multiplied MAs (Sell), providing clear visual cues for trading opportunities.
**Key Features**:
- **Flexible MA Types**: Choose from Simple (SMA), Exponential (EMA), Weighted (WMA), Volume-Weighted (VWMA), or Running (RMA) moving averages.
- **Customizable Bands**: Set the number of lines (0–10) above and below the MA, allowing tailored analysis for any market or timeframe.
- **Dynamic Factors**: Bands are created using factors that scale linearly from 1 to a user-defined maximum (default: 5.0), creating intuitive overbought/oversold zones.
- **Buy/Sell Signals**: Optional labels highlight potential entry (Buy) and exit (Sell) points when the price crosses the bands.
- **Clear Visuals**: The main MA is plotted in blue, with green (multiplied) and red (divided) lines using graduated transparency for easy differentiation.
**Inputs**:
- **MA Type**: Select the moving average type (default: SMA).
- **MA Length**: Set the MA period (default: 14).
- **Number of Lines Above/Below**: Choose how many bands to plot above and below the MA (default: 4, range: 0–10).
- **Max Factor**: Define the largest multiplier/divisor for the outermost bands (default: 5.0).
- **Source**: Select the price data for the MA (default: close).
- **Show Buy/Sell Labels**: Enable or disable Buy/Sell labels (default: true).
**How It Works**:
1. Calculates the chosen moving average based on user inputs.
2. Creates up to 10 lines above the MA (e.g., MA × 2, ×3, ×4, ×5 for `numLines=4`, `maxFactor=5`) and 10 below (e.g., MA ÷ 2, ÷3, ÷4, ÷5).
3. Plots the main MA in blue, multiplied lines in green, and divided lines in red, with transparency increasing for outer bands.
4. If enabled, displays "Buy" labels when the price crosses below any divided MA and "Sell" labels when it crosses above any multiplied MA, positioned at the outermost band.
**Use Cases**:
- **Trend Analysis**: Use the bands as dynamic support/resistance to confirm trend direction or reversals.
- **Mean Reversion**: Identify overbought (near multiplied MAs) or oversold (near divided MAs) conditions.
- **Breakout Trading**: Monitor price crossovers of the outermost bands for potential breakout signals.
- **Signal Confirmation**: Use Buy/Sell labels for swing trading or to complement other indicators.
**How to Use**:
1. Copy the script into TradingView’s Pine Editor.
2. Compile and apply it to your chart (e.g., stocks, forex, crypto).
3. Adjust inputs like `numLines`, `maxFactor`, or `maType` to fit your strategy.
4. Enable `Show Buy/Sell Labels` to visualize trading signals.
5. Test on various timeframes (e.g., 1H, 4H, 1D) and assets to optimize settings.
**Example Settings**:
- **Swing Trading**: Use `numLines=3`, `maxFactor=4`, `maType=EMA`, `maLength=20` on a 4-hour chart.
- **Intraday**: Try `numLines=2`, `maxFactor=3`, `maType=SMA`, `maLength=10` on a 15-minute chart.
**Notes**:
- **Performance**: Supports up to 20 bands (10 above, 10 below), staying within TradingView’s 64-plot limit.
- **False Signals**: In choppy markets, frequent crossovers may occur. Combine with trend filters (e.g., ADX, higher-timeframe MA) to reduce noise.
- **Enhancements**: Add alerts via TradingView’s alert system for Buy/Sell signals, or experiment with different `maxFactor` values for volatility.
**Limitations**:
- Bands are reactive, as they’re based on a moving average, so confirm signals with other indicators.
- High `numLines` values may clutter the chart; use 2–4 for clarity.
- Signals may lag in fast-moving markets due to the MA’s smoothing effect.
This indicator is perfect for traders seeking a customizable, visually clear tool to enhance technical analysis on TradingView. For support, feature requests (e.g., alerts, custom colors), or community discussion, visit TradingView’s forums or contact the script author.
Bar Index & TimeLibrary to convert a bar index to a timestamp and vice versa.
Utilizes runtime memory to store the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 values of every bar on the chart (and optional future bars), with the ability of storing additional custom values for every chart bar.
█ PREFACE
This library aims to tackle some problems that pine coders (from beginners to advanced) often come across, such as:
I'm trying to draw an object with a 𝚋𝚊𝚛_𝚒𝚗𝚍𝚎𝚡 that is more than 10,000 bars into the past, but this causes my script to fail. How can I convert the 𝚋𝚊𝚛_𝚒𝚗𝚍𝚎𝚡 to a UNIX time so that I can draw visuals using xloc.bar_time ?
I have a diagonal line drawing and I want to get the "y" value at a specific time, but line.get_price() only accepts a bar index value. How can I convert the timestamp into a bar index value so that I can still use this function?
I want to get a previous 𝚘𝚙𝚎𝚗 value that occurred at a specific timestamp. How can I convert the timestamp into a historical offset so that I can use 𝚘𝚙𝚎𝚗 ?
I want to reference a very old value for a variable. How can I access a previous value that is older than the maximum historical buffer size of 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎 ?
This library can solve the above problems (and many more) with the addition of a few lines of code, rather than requiring the coder to refactor their script to accommodate the limitations.
█ OVERVIEW
The core functionality provided is conversion between xloc.bar_index and xloc.bar_time values.
The main component of the library is the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object, created via the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function which basically stores the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 of every bar on the chart, and there are 3 more overloads to this function that allow collecting and storing additional data. Once a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object is created, use any of the exported methods:
Methods to convert a UNIX timestamp into a bar index or bar offset:
𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚐𝚎𝚝𝙽𝚞𝚖𝚋𝚎𝚛𝙾𝚏𝙱𝚊𝚛𝚜𝙱𝚊𝚌𝚔()
Methods to retrieve the stored data for a bar index:
𝚝𝚒𝚖𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚝𝚒𝚖𝚎𝙲𝚕𝚘𝚜𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚟𝚊𝚕𝚞𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚐𝚎𝚝𝙰𝚕𝚕𝚅𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡()
Methods to retrieve the stored data at a number of bars back (i.e., historical offset):
𝚝𝚒𝚖𝚎(), 𝚝𝚒𝚖𝚎𝙲𝚕𝚘𝚜𝚎(), 𝚟𝚊𝚕𝚞𝚎()
Methods to retrieve all the data points from the earliest bar (or latest bar) stored in memory, which can be useful for debugging purposes:
𝚐𝚎𝚝𝙴𝚊𝚛𝚕𝚒𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊(), 𝚐𝚎𝚝𝙻𝚊𝚝𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊()
Note: the library's strong suit is referencing data from very old bars in the past, which is especially useful for scripts that perform its necessary calculations only on the last bar.
█ USAGE
Step 1
Import the library. Replace with the latest available version number for this library.
//@version=6
indicator("Usage")
import n00btraders/ChartData/
Step 2
Create a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object to collect data on every bar. Do not declare as `var` or `varip`.
chartData = ChartData.collectChartData() // call on every bar to accumulate the necessary data
Step 3
Call any method(s) on the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object. Do not modify its fields directly.
if barstate.islast
int firstBarTime = chartData.timeAtBarIndex(0)
int lastBarTime = chartData.time(0)
log.info("First `time`: " + str.format_time(firstBarTime) + ", Last `time`: " + str.format_time(lastBarTime))
█ EXAMPLES
• Collect Future Times
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚋𝚊𝚛𝚜𝙵𝚘𝚛𝚠𝚊𝚛𝚍 argument can additionally store time values for up to 500 bars into the future.
//@version=6
indicator("Example `collectChartData(barsForward)`")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData(barsForward = 500)
var rectangle = box.new(na, na, na, na, xloc = xloc.bar_time, force_overlay = true)
if barstate.islast
int futureTime = chartData.timeAtBarIndex(bar_index + 100)
int lastBarTime = time
box.set_lefttop(rectangle, lastBarTime, open)
box.set_rightbottom(rectangle, futureTime, close)
box.set_text(rectangle, "Extending box 100 bars to the right. Time: " + str.format_time(futureTime))
• Collect Custom Data
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜 argument can additionally store custom user-specified values for every bar on the chart.
//@version=6
indicator("Example `collectChartData(variables)`")
import n00btraders/ChartData/1
var map variables = map.new()
variables.put("open", open)
variables.put("close", close)
variables.put("open-close midpoint", (open + close) / 2)
variables.put("boolean", open > close ? 1 : 0)
chartData = ChartData.collectChartData(variables = variables)
var fgColor = chart.fg_color
var table1 = table.new(position.top_right, 2, 9, color(na), fgColor, 1, fgColor, 1, true)
var table2 = table.new(position.bottom_right, 2, 9, color(na), fgColor, 1, fgColor, 1, true)
if barstate.isfirst
table.cell(table1, 0, 0, "ChartData.value()", text_color = fgColor)
table.cell(table2, 0, 0, "open ", text_color = fgColor)
table.merge_cells(table1, 0, 0, 1, 0)
table.merge_cells(table2, 0, 0, 1, 0)
for i = 1 to 8
table.cell(table1, 0, i, text_color = fgColor, text_halign = text.align_left, text_font_family = font.family_monospace)
table.cell(table2, 0, i, text_color = fgColor, text_halign = text.align_left, text_font_family = font.family_monospace)
table.cell(table1, 1, i, text_color = fgColor)
table.cell(table2, 1, i, text_color = fgColor)
if barstate.islast
for i = 1 to 8
float open1 = chartData.value("open", 5000 * i)
float open2 = i < 3 ? open : -1
table.cell_set_text(table1, 0, i, "chartData.value(\"open\", " + str.tostring(5000 * i) + "): ")
table.cell_set_text(table2, 0, i, "open : ")
table.cell_set_text(table1, 1, i, str.tostring(open1))
table.cell_set_text(table2, 1, i, open2 >= 0 ? str.tostring(open2) : "Error")
• xloc.bar_index → xloc.bar_time
The 𝚝𝚒𝚖𝚎 value (or 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 value) can be retrieved for any bar index that is stored in memory by the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object.
//@version=6
indicator("Example `timeAtBarIndex()`")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData()
if barstate.islast
int start = bar_index - 15000
int end = bar_index - 100
// line.new(start, close, end, close) // !ERROR - `start` value is too far from current bar index
start := chartData.timeAtBarIndex(start)
end := chartData.timeAtBarIndex(end)
line.new(start, close, end, close, xloc.bar_time, width = 10)
• xloc.bar_time → xloc.bar_index
Use 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡() to find the bar that a timestamp belongs to.
If the timestamp falls in between the close of one bar and the open of the next bar,
the 𝚜𝚗𝚊𝚙 parameter can be used to determine which bar to choose:
𝚂𝚗𝚊𝚙.𝙻𝙴𝙵𝚃 - prefer to choose the leftmost bar (typically used for closing times)
𝚂𝚗𝚊𝚙.𝚁𝙸𝙶𝙷𝚃 - prefer to choose the rightmost bar (typically used for opening times)
𝚂𝚗𝚊𝚙.𝙳𝙴𝙵𝙰𝚄𝙻𝚃 (or 𝚗𝚊) - copies the same behavior as xloc.bar_time uses for drawing objects
//@version=6
indicator("Example `timestampToBarIndex()`")
import n00btraders/ChartData/1
startTimeInput = input.time(timestamp("01 Aug 2025 08:30 -0500"), "Session Start Time")
endTimeInput = input.time(timestamp("01 Aug 2025 15:15 -0500"), "Session End Time")
chartData = ChartData.collectChartData()
if barstate.islastconfirmedhistory
int startBarIndex = chartData.timestampToBarIndex(startTimeInput, ChartData.Snap.RIGHT)
int endBarIndex = chartData.timestampToBarIndex(endTimeInput, ChartData.Snap.LEFT)
line1 = line.new(startBarIndex, 0, startBarIndex, 1, extend = extend.both, color = color.new(color.green, 60), force_overlay = true)
line2 = line.new(endBarIndex, 0, endBarIndex, 1, extend = extend.both, color = color.new(color.green, 60), force_overlay = true)
linefill.new(line1, line2, color.new(color.green, 90))
// using Snap.DEFAULT to show that it is equivalent to drawing lines using `xloc.bar_time` (i.e., it aligns to the same bars)
startBarIndex := chartData.timestampToBarIndex(startTimeInput)
endBarIndex := chartData.timestampToBarIndex(endTimeInput)
line.new(startBarIndex, 0, startBarIndex, 1, extend = extend.both, color = color.yellow, width = 3)
line.new(endBarIndex, 0, endBarIndex, 1, extend = extend.both, color = color.yellow, width = 3)
line.new(startTimeInput, 0, startTimeInput, 1, xloc.bar_time, extend.both, color.new(color.blue, 85), width = 11)
line.new(endTimeInput, 0, endTimeInput, 1, xloc.bar_time, extend.both, color.new(color.blue, 85), width = 11)
• Get Price of Line at Timestamp
The pine script built-in function line.get_price() requires working with bar index values. To get the price of a line in terms of a timestamp, convert the timestamp into a bar index or offset.
//@version=6
indicator("Example `line.get_price()` at timestamp")
import n00btraders/ChartData/1
lineStartInput = input.time(timestamp("01 Aug 2025 08:30 -0500"), "Line Start")
chartData = ChartData.collectChartData()
var diagonal = line.new(na, na, na, na, force_overlay = true)
if time <= lineStartInput
line.set_xy1(diagonal, bar_index, open)
if barstate.islastconfirmedhistory
line.set_xy2(diagonal, bar_index, close)
if barstate.islast
int timeOneWeekAgo = timenow - (7 * timeframe.in_seconds("1D") * 1000)
// Note: could also use `timetampToBarIndex(timeOneWeekAgo, Snap.DEFAULT)` and pass the value directly to `line.get_price()`
int barsOneWeekAgo = chartData.getNumberOfBarsBack(timeOneWeekAgo)
float price = line.get_price(diagonal, bar_index - barsOneWeekAgo)
string formatString = "Time 1 week ago: {0,number,#} - Equivalent to {1} bars ago 𝚕𝚒𝚗𝚎.𝚐𝚎𝚝_𝚙𝚛𝚒𝚌𝚎(): {2,number,#.##}"
string labelText = str.format(formatString, timeOneWeekAgo, barsOneWeekAgo, price)
label.new(timeOneWeekAgo, price, labelText, xloc.bar_time, style = label.style_label_lower_right, size = 16, textalign = text.align_left, force_overlay = true)
█ RUNTIME ERROR MESSAGES
This library's functions will generate a custom runtime error message in the following cases:
𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() is not called consecutively, or is called more than once on a single bar
Invalid 𝚋𝚊𝚛𝚜𝙵𝚘𝚛𝚠𝚊𝚛𝚍 argument in the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function
Invalid 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜 argument in the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function
Invalid 𝚕𝚎𝚗𝚐𝚝𝚑 argument in any of the functions that accept a number of bars back
Note: there is no runtime error generated for an invalid 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙 or 𝚋𝚊𝚛𝙸𝚗𝚍𝚎𝚡 argument in any of the functions. Instead, the functions will assign 𝚗𝚊 to the returned values.
Any other runtime errors are due to incorrect usage of the library.
█ NOTES
• Function Descriptions
The library source code uses Markdown for the exported functions. Hover over a function/method call in the Pine Editor to display formatted, detailed information about the function/method.
//@version=6
indicator("Demo Function Tooltip")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData()
int barIndex = chartData.timestampToBarIndex(timenow)
log.info(str.tostring(barIndex))
• Historical vs. Realtime Behavior
Under the hood, the data collector for this library is declared as `var`. Because of this, the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object will always reflect the latest available data on realtime updates. Any data that is recorded for historical bars will remain unchanged throughout the execution of a script.
//@version=6
indicator("Demo Realtime Behavior")
import n00btraders/ChartData/1
var map variables = map.new()
variables.put("open", open)
variables.put("close", close)
chartData = ChartData.collectChartData(variables)
if barstate.isrealtime
varip float initialOpen = open
varip float initialClose = close
varip int updateCount = 0
updateCount += 1
float latestOpen = open
float latestClose = close
float recordedOpen = chartData.valueAtBarIndex("open", bar_index)
float recordedClose = chartData.valueAtBarIndex("close", bar_index)
string formatString = "# of updates: {0} 𝚘𝚙𝚎𝚗 at update #1: {1,number,#.##} 𝚌𝚕𝚘𝚜𝚎 at update #1: {2,number,#.##} "
+ "𝚘𝚙𝚎𝚗 at update #{0}: {3,number,#.##} 𝚌𝚕𝚘𝚜𝚎 at update #{0}: {4,number,#.##} "
+ "𝚘𝚙𝚎𝚗 stored in memory: {5,number,#.##} 𝚌𝚕𝚘𝚜𝚎 stored in memory: {6,number,#.##}"
string labelText = str.format(formatString, updateCount, initialOpen, initialClose, latestOpen, latestClose, recordedOpen, recordedClose)
label.new(bar_index, close, labelText, style = label.style_label_left, force_overlay = true)
• Collecting Chart Data for Other Contexts
If your use case requires collecting chart data from another context, avoid directly retrieving the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object as this may exceed memory limits .
//@version=6
indicator("Demo Return Calculated Results")
import n00btraders/ChartData/1
timeInput = input.time(timestamp("01 Sep 2025 08:30 -0500"), "Time")
var int oneMinuteBarsAgo = na
// !ERROR - Memory Limits Exceeded
// chartDataArray = request.security_lower_tf(syminfo.tickerid, "1", ChartData.collectChartData())
// oneMinuteBarsAgo := chartDataArray.last().getNumberOfBarsBack(timeInput)
// function that returns calculated results (a single integer value instead of an entire `ChartData` object)
getNumberOfBarsBack() =>
chartData = ChartData.collectChartData()
chartData.getNumberOfBarsBack(timeInput)
calculatedResultsArray = request.security_lower_tf(syminfo.tickerid, "1", getNumberOfBarsBack())
oneMinuteBarsAgo := calculatedResultsArray.size() > 0 ? calculatedResultsArray.last() : na
if barstate.islast
string labelText = str.format("The selected timestamp occurs 1-minute bars ago", oneMinuteBarsAgo)
label.new(bar_index, hl2, labelText, style = label.style_label_left, size = 16, force_overlay = true)
• Memory Usage
The library's convenience and ease of use comes at the cost of increased usage of computational resources. For simple scripts, using this library will likely not cause any issues with exceeding memory limits. But for large and complex scripts, you can reduce memory issues by specifying a lower 𝚌𝚊𝚕𝚌_𝚋𝚊𝚛𝚜_𝚌𝚘𝚞𝚗𝚝 amount in the indicator() or strategy() declaration statement.
//@version=6
// !ERROR - Memory Limits Exceeded using the default number of bars available (~20,000 bars for Premium plans)
//indicator("Demo `calc_bars_count` parameter")
// Reduce number of bars using `calc_bars_count` parameter
indicator("Demo `calc_bars_count` parameter", calc_bars_count = 15000)
import n00btraders/ChartData/1
map variables = map.new()
variables.put("open", open)
variables.put("close", close)
variables.put("weekofyear", weekofyear)
variables.put("dayofmonth", dayofmonth)
variables.put("hour", hour)
variables.put("minute", minute)
variables.put("second", second)
// simulate large memory usage
chartData0 = ChartData.collectChartData(variables)
chartData1 = ChartData.collectChartData(variables)
chartData2 = ChartData.collectChartData(variables)
chartData3 = ChartData.collectChartData(variables)
chartData4 = ChartData.collectChartData(variables)
chartData5 = ChartData.collectChartData(variables)
chartData6 = ChartData.collectChartData(variables)
chartData7 = ChartData.collectChartData(variables)
chartData8 = ChartData.collectChartData(variables)
chartData9 = ChartData.collectChartData(variables)
log.info(str.tostring(chartData0.time(0)))
log.info(str.tostring(chartData1.time(0)))
log.info(str.tostring(chartData2.time(0)))
log.info(str.tostring(chartData3.time(0)))
log.info(str.tostring(chartData4.time(0)))
log.info(str.tostring(chartData5.time(0)))
log.info(str.tostring(chartData6.time(0)))
log.info(str.tostring(chartData7.time(0)))
log.info(str.tostring(chartData8.time(0)))
log.info(str.tostring(chartData9.time(0)))
if barstate.islast
result = table.new(position.middle_right, 1, 1, force_overlay = true)
table.cell(result, 0, 0, "Script Execution Successful ✅", text_size = 40)
█ EXPORTED ENUMS
Snap
Behavior for determining the bar that a timestamp belongs to.
Fields:
LEFT : Snap to the leftmost bar.
RIGHT : Snap to the rightmost bar.
DEFAULT : Default `xloc.bar_time` behavior.
Note: this enum is used for the 𝚜𝚗𝚊𝚙 parameter of 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡().
█ EXPORTED TYPES
Note: users of the library do not need to worry about directly accessing the fields of these types; all computations are done through method calls on an object of the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 type.
Variable
Represents a user-specified variable that can be tracked on every chart bar.
Fields:
name (series string) : Unique identifier for the variable.
values (array) : The array of stored values (one value per chart bar).
ChartData
Represents data for all bars on a chart.
Fields:
bars (series int) : Current number of bars on the chart.
timeValues (array) : The `time` values of all chart (and future) bars.
timeCloseValues (array) : The `time_close` values of all chart (and future) bars.
variables (array) : Additional custom values to track on all chart bars.
█ EXPORTED FUNCTIONS
collectChartData()
Collects and tracks the `time` and `time_close` value of every bar on the chart.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars.
Parameters:
barsForward (simple int) : Number of future bars to collect data for.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
variables (simple map) : Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward, variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
barsForward (simple int) : Number of future bars to collect data for.
variables (simple map) : Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
█ EXPORTED METHODS
method timestampToBarIndex(chartData, timestamp, snap)
Converts a UNIX timestamp to a bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
timestamp (series int) : A UNIX time.
snap (series Snap) : A `Snap` enum value.
Returns: A bar index, or `na` if unable to find the appropriate bar index.
method getNumberOfBarsBack(chartData, timestamp)
Converts a UNIX timestamp to a history-referencing length (i.e., number of bars back).
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
timestamp (series int) : A UNIX time.
Returns: A bar offset, or `na` if unable to find a valid number of bars back.
method timeAtBarIndex(chartData, barIndex)
Retrieves the `time` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
barIndex (int) : The bar index.
Returns: The `time` value, or `na` if there is no `time` stored for the bar index.
method time(chartData, length)
Retrieves the `time` value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
length (series int) : Number of bars back.
Returns: The `time` value `length` bars ago, or `na` if there is no `time` stored for that bar.
method timeCloseAtBarIndex(chartData, barIndex)
Retrieves the `time_close` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
barIndex (series int) : The bar index.
Returns: The `time_close` value, or `na` if there is no `time_close` stored for the bar index.
method timeClose(chartData, length)
Retrieves the `time_close` value of the bar that is `length` bars back from the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
length (series int) : Number of bars back.
Returns: The `time_close` value `length` bars ago, or `na` if there is none stored.
method valueAtBarIndex(chartData, name, barIndex)
Retrieves the value of a custom variable for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
name (series string) : The variable name.
barIndex (series int) : The bar index.
Returns: The value of the variable, or `na` if that variable is not stored for the bar index.
method value(chartData, name, length)
Retrieves a variable value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
name (series string) : The variable name.
length (series int) : Number of bars back.
Returns: The value `length` bars ago, or `na` if that variable is not stored for the bar index.
method getAllVariablesAtBarIndex(chartData, barIndex)
Retrieves all custom variables for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
barIndex (series int) : The bar index.
Returns: Map of all custom variables that are stored for the specified bar index.
method getEarliestStoredData(chartData)
Gets all values from the earliest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
Returns: A tuple:
method getLatestStoredData(chartData, futureData)
Gets all values from the latest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData) : The `ChartData` object.
futureData (series bool) : Whether to include the future data that is stored in memory.
Returns: A tuple:
cd_Quarterly_cycles_SSMT_TPD_CxGeneral
This indicator is designed in line with the Quarterly Theory to display each cycle on the chart, either boxed and/or in candlestick form.
Additionally, it performs inter-cycle divergence analysis ( SSMT ) with the correlated symbol, Terminus Price Divergence ( TPD ), Precision Swing Point ( PSP ) analysis, and potential Power of Three ( PO3 ) analysis.
Special thanks to @HandlesHandled for his great indicator, which I used while preparing the cycles content.
Details & Usage:
Optional cycles available: Weekly, Daily, 90m, and Micro cycles.
Displaying/removing cycles can be controlled from the menu (cycles / candles / labels).
All selected cycles can be shown, or you can limit the number of displayed cycles (min: 2, max: 4).
The summary table can be toggled on/off and repositioned.
What’s in the summary table?
• Below the header, the correlated symbol used in the analysis is displayed (e.g., SSMT → US500).
• If available, live and previous bar results of the SSMT analysis are shown.
• Under the PSP & TPD section, results are displayed when conditions are met.
• Under Alerts, the real-time status of conditions defined in the menu is shown.
• Under Potential AMD, possible PO3 analysis results are displayed.
Analysis & Symbol Selection:
To run analyses, a correlated symbol must first be defined with the main symbol.
Default pairs are preloaded (see below), but users should adjust them according to their exchange and instruments.
If no correlated pair is defined, cycles are displayed only as boxes/candles.
Once defined pairs are opened on the chart, analyses load automatically.
Pairs listed on the same row in the menu are automatically linked, so no need to re-enter them across rows.
SSMT Analysis:
Based on the chart’s timeframe, divergences are searched across Weekly, Daily, 90m, and Micro cycles.
The code will not produce results for smaller cycles than the current timeframe.
(Example: On H1, Micro cycles will not be displayed.)
Results are obtained by comparing the highs and lows of consecutive cycles in the same period.
If one pair makes a new high/low while the other does not, this divergence is added to SSMT results.
The difference from classic SMT is that cycles are used instead of bars.
PSP & TPD Analysis:
A correlated symbol must be defined.
For PSP, timeframe options are added to the menu.
Users toggle timeframes on/off by checking/unchecking boxes.
In selected timeframes, PSP & TPD analysis is performed.
• PSP: If candlesticks differ in color (bullish/bearish) between symbols and the bar is at a high/low of the timeframe (and higher/lower than the bars before/after it), it is identified as a PSP. Divergences between pairs are interpreted as potential reversal signals.
• TPD: Once a PSP occurs, the closing price of the previous bar and the opening price of the next bar are compared. If one symbol shows continuation while the other does not, it is marked as a divergence.
Example:
Let’s assume Pair 1 and Pair 2 are selected in the menu with the H4 timeframe, and our cycle is Weekly (Box).
For Pair 1, the H4 candle at the Weekly high level:
• Is positioned at the Weekly high,
• Its high is above both the previous and the next candle,
• It closed bearish (open > close).
For Pair 2, the same H4 candle closed bullish (close > open).
→ PSP conditions are met.
For TPD, we now check the candles before and after this PSP (H4) candle on both pairs.
Comparing the previous candle’s close with the next candle’s open, we see that:
• In Pair 1, the next open is lower than the previous close,
• In Pair 2, the next open is higher than the previous close.
Pair 1 → close > open
Pair 2 → close < open
Since they are not aligned in the same direction, this is interpreted as a divergence — a potential reversal signal.
While TPD results are displayed in the summary table, whenever the conditions are met in the selected timeframes, the signals are also plotted directly on the chart. (🚦, X)
• Higher timeframe TPD example:
• Current timeframe TPD example:
Alerts:
The indicator can be conditioned based on aligned timeframes defined within the concept.
Example (assuming random active rows in the screenshot):
• Weekly Bullish SSMT → Tf2 (menu-selected) Bullish TPD → Daily Bullish SSMT.
Selecting “none” in the menu means that condition is not required.
When an alert is triggered, it will be displayed in the corresponding row of the table.
• Example with only condition 3 enabled:
Potential PO3 Analysis:
According to Quarterly Theory, price moves in cycles, and the same structures are assumed to continue in smaller timeframes.
From classical PO3 knowledge: before the main move, price first manipulates in the opposite direction to trap buyers/sellers, then makes its true move.
The cyclical sequence is:
(A)ccumulation → (M)anipulation → (D)istribution → (R)eversal / Continuation.
Within cycle candles, the first letter of each phase is displayed.
So how does the analysis work?
If the active cycle is in (M)anipulation or (D)istribution phase, and it sweeps the previous cycle’s high or low but then pulls back inside, this is flagged in the summary table as a possible PO3 signal.
In other words, it reflects the alignment of theoretical sequence with real-time price action.
Confluence with SSMT and TPD conditions further strengthens the expectation.
Final Note:
No single marking or alert carries meaning on its own — it must always be evaluated in the context of your concept knowledge.
Instead of trading purely on expectations, align bias + trend + entry confirmations to improve your success rate.
Feedback and suggestions are welcome.
Happy trading!
nATR*ATR Multiplication Indicator - Optimal Selection Tool forThis indicator is specifically designed as an analysis tool for investors using grid bot strategies. It displays both nATR (Normalized Average True Range) and ATR (Average True Range) values on a single chart screen, calculating the multiplication of these two critical volatility measurements.
Primary Purpose of the Indicator:
To facilitate the selection of the most optimal stock and time period for grid bot trading. The nATR*ATR multiplication provides a hybrid measurement that combines both percentage-based return potential (nATR) and absolute volatility magnitude (ATR).
Importance for Grid Bot Strategy:
High nATR: Greater percentage-based return potential
High ATR: Wider price range = Fewer grid levels = More budget allocation per grid
Formula: Price Range/ATR = Theoretical Grid Count
Usage Advantages:
Test different time periods to find the highest multiplication value
Make optimal stock and time frame selections for grid bot setup
Monitor both nATR and ATR values on a single screen
High multiplication values indicate ideal conditions for grid bots
Technical Features:
Adjustable calculation period (1-500 candles)
Visual alert system (high/low multiplication values)
Real-time value tracking table
SMA-based smoothed calculations
This serves as a reliable guide for grid bot investors in optimal timing and stock selection.