DH EMA 21/55/200 Ribbon (Scaled HTF)ema 21 / 55 /200 cập nhật thêm multiTF, chỉnh sửa màu sắc dải mây
Pine utilities
FiniteStateMachine🟩 OVERVIEW
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events.
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include:
• Explicit logic : You can see all rules easily side-by-side.
• Validation : Tables show your rules and validation results right on the chart.
• Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
• Type safety : Shows how to use enums for robustness while maintaining string compatibility.
• Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
• Priority control : Explicit control over which rules take precedence when multiple conditions are met.
• Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩 SIMPLE FSM (MATRIX-BASED)
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩 CONCURRENT FSM (MAP-BASED)
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/FiniteStateMachine/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 TECHNICAL IMPLEMENTATION
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
• Exact state + exact event match
• Exact state + empty event (event wildcard)
• Empty state + exact event (state wildcard)
• Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
• o_eventRule : Maps a condition name to an output
• o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩 VALIDATION & ERROR HANDLING
The library includes comprehensive validation functions that catch common FSM design errors:
Error detection:
• Empty next states
• Invalid states not in the states array
• Duplicate rules
• Conflicting transitions
• Unreachable states (no entry/exit rules)
Warning detection:
• Redundant wildcards
• Empty states/events (potential unintended wildcards)
• Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩 PRACTICAL EXAMPLES
The library includes four comprehensive demos:
Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
• Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
• Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
• Includes position management, stop losses, and re-entry logic
Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩 BRING ON THE FUNCTIONS
f_printFSMMatrix(_mat_rules, _a_states, _tablePosition)
Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
Parameters:
_mat_rules (matrix)
_a_states (array)
_tablePosition (simple string)
Returns: The table of states and rules.
method m_loadMatrixRulesFromText(_mat_rules, _rulesText)
Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_rulesText (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState)
Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_nextState (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition)
Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_a_states (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions)
Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_strictInput (bool)
_strictTransitions (bool)
Returns: The next state or `na`.
method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output)
Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
Namespace types: map
Parameters:
_map_eventRules (map)
_state (string)
_condName (string)
_output (string)
Returns: No explicit return. The map is modified as a side-effect.
method m_addEventRulesToMapFromText(_map_eventRules, _configText)
Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state | > output" (condition wildcard), " | > output" (full wildcard).
Splits lines by , extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
Namespace types: map
Parameters:
_map_eventRules (map)
_configText (string)
Returns: No explicit return. The map is modified as a side-effect.
f_printFSMMap(_map_eventRules, _a_states, _tablePosition)
Prints a table of map-based event rules to the specified position on the chart.
Parameters:
_map_eventRules (map)
_a_states (array)
_tablePosition (simple string)
Returns: The table of map-based event rules.
method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition)
Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
Namespace types: map
Parameters:
_map_eventRules (map)
_a_states (array)
_a_validEvents (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules)
Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
Namespace types: series string, simple string, input string, const string
Parameters:
_currentState (string)
_a_activeConditions (array)
_map_eventRules (map)
Returns: The output string (event or state) for the first matching condition, or na if no match found.
o_eventRule
o_eventRule defines a condition-to-output mapping for the concurrent FSM.
Fields:
condName (series string) : The name of the condition to check.
output (series string) : The output (event or state) when the condition is true.
o_eventRuleWrapper
o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
Fields:
a_rules (array) : Array of o_eventRule objects for a specific state.
Daily + 4H MACD & RSI Screeneri used this script for my swing trading entry.
//@version=5
indicator("Daily + 4H MACD & RSI Screener", overlay=false)
// settings
rsiLength = input.int(14, "RSI Length")
rsiLevel = input.int(50, "RSI Threshold")
macdFast = input.int(12, "MACD Fast")
macdSlow = input.int(26, "MACD Slow")
macdSignal = input.int(9, "MACD Signal")
// ---- daily timeframe ----
dailyRsi = request.security(syminfo.tickerid, "D", ta.rsi(close, rsiLength))
= request.security(syminfo.tickerid, "D", ta.macd(close, macdFast, macdSlow, macdSignal))
dailyRsiPass = dailyRsi < rsiLevel
dailyMacdPass = dailyMacd < 0
dailyCondition = dailyRsiPass and dailyMacdPass
// ---- 4H timeframe ----
h4Rsi = request.security(syminfo.tickerid, "240", ta.rsi(close, rsiLength))
= request.security(syminfo.tickerid, "240", ta.macd(close, macdFast, macdSlow, macdSignal))
h4RsiPass = h4Rsi < rsiLevel
h4MacdPass = h4Macd < 0
h4Condition = h4RsiPass and h4MacdPass
// ---- combined condition ----
finalCondition = dailyCondition and h4Condition
// plot signals
plotshape(finalCondition, style=shape.triangledown, location=location.top, color=color.red, size=size.large, title="Signal")
bgcolor(finalCondition ? color.new(color.red, 85) : na)
// ---- table (3 columns x 4 rows) ----
var table statusTable = table.new(position=position.top_right, columns=3, rows=4, border_width=1)
// headers
table.cell(statusTable, 0, 0, "Timeframe", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(statusTable, 1, 0, "RSI", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(statusTable, 2, 0, "MACD", text_color=color.white, bgcolor=color.new(color.black, 0))
// daily row
table.cell(statusTable, 0, 1, "Daily", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(statusTable, 1, 1, str.tostring(dailyRsi, "#.##"),
text_color=color.white, bgcolor=dailyRsiPass ? color.new(color.green, 60) : color.new(color.red, 60))
table.cell(statusTable, 2, 1, str.tostring(dailyMacd, "#.##"),
text_color=color.white, bgcolor=dailyMacdPass ? color.new(color.green, 60) : color.new(color.red, 60))
// 4H row
table.cell(statusTable, 0, 2, "4H", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(statusTable, 1, 2, str.tostring(h4Rsi, "#.##"),
text_color=color.white, bgcolor=h4RsiPass ? color.new(color.green, 60) : color.new(color.red, 60))
table.cell(statusTable, 2, 2, str.tostring(h4Macd, "#.##"),
text_color=color.white, bgcolor=h4MacdPass ? color.new(color.green, 60) : color.new(color.red, 60))
// status row (simulate colspan by using two adjacent cells with the same bgcolor)
table.cell(statusTable, 0, 3, "Status", text_color=color.white, bgcolor=color.new(color.black, 0))
statusText = finalCondition ? "match" : "no match"
statusBg = finalCondition ? color.new(color.green, 0) : color.new(color.red, 0)
table.cell(statusTable, 1, 3, statusText, text_color=color.white, bgcolor=statusBg, text_size=size.large)
table.cell(statusTable, 2, 3, "", text_color=color.white, bgcolor=statusBg)
Market Order Risk CalculatorObviously the Long/Short Position tool does this, but when you are scalping, 10 - 15 seconds matters. What matters more than that is defined risk, you dont want your losses being scattered, 300 here 145 there, you want consistent risk to have consistent data.
What this does is when you are framing a trade, it provides a hands off tool that tells you exactly how many contracts to enter with, that way if you have bracket orders on, your stop will be exactly where you want it to be without going over your defined risk.
MTF Supply and Demand Zones [MMT]Description
The MTF Supply and Demand Zones indicator is a powerful tool designed to identify and display supply and demand zones across multiple timeframes (MTF) on your TradingView chart. These zones highlight key areas where price is likely to react, based on significant price movements in higher timeframes. The indicator is highly customizable, allowing traders to adjust zone strength, timeframes, colors, and display settings to suit their trading style.
Key Features
Multi-Timeframe Analysis : Detects supply and demand zones from up to five user-defined timeframes (e.g., 30m, 1H, 4H, 1D, 1W).
Zone Strength Filter : Filters zones based on the strength of price movements, ensuring only significant zones are displayed.
Customizable Display : Toggle supply and demand zones on/off, adjust colors, border styles, and label settings for clarity.
Dynamic Zone Extension : Extends zones to the right of the chart for better visibility, with adjustable extension length.
Zone Cleanup : Automatically removes zones when price breaks through them, keeping the chart clean and relevant.
Labels : Displays timeframe labels on zones for easy identification, with customizable size, color, and alignment.
How It Works
Supply Zones : Identified when a strong bearish candle follows a bullish or neutral candle, indicating potential selling pressure.
Demand Zones : Identified when a strong bullish candle follows a bearish or neutral candle, indicating potential buying pressure.
Zones are drawn as boxes, with the top and bottom based on key price levels (e.g., highs/lows or open prices).
The indicator uses a strength filter to ensure only significant zones (based on candle size ratios) are plotted.
Zones are updated dynamically, extending to the right by a user-defined number of bars and removed when price breaks through them.
Settings
S&D Zones Settings
Zone Strength Filter : Adjust the minimum candle size ratio (default: 1.8) to filter weaker zones.
Show Supply/Demand : Enable or disable supply and/or demand zones.
Supply/Demand Colors : Customize the fill and border colors for supply (default: red) and demand (default: green) zones.
Timeframes : Enable up to five timeframes (e.g., 30m, 1H, 4H, 1D, 1W) to analyze zones. Only zones from timeframes higher than the chart’s timeframe are displayed.
Display Settings
Zone Extension : Set how far zones extend to the right (in bars, default: 15).
Show Label: Toggle timeframe labels on zones.
Label Style : Customize label color, size (tiny, small, normal, large, huge), and alignment (horizontal/vertical).
Usage Tips
Use higher timeframes (e.g., 4H, 1D) for stronger, more reliable zones.
Combine with other indicators (e.g., support/resistance, trendlines) to confirm trade setups.
Adjust the Zone Strength Filter to reduce noise in volatile markets.
Enable labels to quickly identify the timeframe of each zone.
Notes
The indicator is overlayed on the price chart and supports up to 500 zones.
Zones are removed when price breaks above (supply) or below (demand), ensuring only active zones remain.
Works best on markets with clear price action, such as futures, forex, stocks, or cryptocurrencies.
Happy trading! 🚀
KILLZONE & CHECK LIST ICAKILLZONE & CHECK LIST ICA | The Inner Circle Alchemist
✨ Features:
Display of precise trading killzones on the chart
Marking the high, low, and mid-level of each killzone
Option to show/hide killzone names
Daily separators at custom times (e.g. 17:00 or 00:00)
Highlighting Midnight Open, 8:30 Open, and New York Stock Exchange Open
Display of previous day, week, and month highs & lows (optional)
A clean and practical trading checklist on the bottom-right of the chart
Visual customization, such as showing your name/brand on the chart
Clear indication of weekdays
⚡️ A perfect mix of professional tools & visual style to keep you one step ahead!
ID on All Platforms: TheInnerCircleAlchemist
#Forex #Trading #Indicator #Killzone #TradingChecklist #PriceAction #DayTrading #SwingTrading #SmartMoney #MarketStructure #TradingTools #ChartAnalysis #TechnicalAnalysis #ForexStrategy #TraderLife #ForexTrading
KILLZONE & CHECK LIST ICAKILLZONE & CHECK LIST | The Inner Circle Alchemist
✨ Features:
Display of precise trading killzones on the chart
Marking the high, low, and mid-level of each killzone
Option to show/hide killzone names
Daily separators at custom times (e.g. 17:00 or 00:00)
Highlighting Midnight Open, 8:30 Open, and New York Stock Exchange Open
Display of previous day, week, and month highs & lows (optional)
A clean and practical trading checklist on the bottom-right of the chart
Visual customization, such as showing your name/brand on the chart
Clear indication of weekdays
⚡️ A perfect mix of professional tools & visual style to keep you one step ahead!
ID on all platforms: TheInnerCircleAlchemist
#Forex #Trading #Indicator #Killzone #TradingChecklist #PriceAction #DayTrading #SwingTrading #SmartMoney #MarketStructure #TradingTools #ChartAnalysis #TechnicalAnalysis #ForexStrategy #TraderLife #ForexTrading
CD - Promedio de Posición ManualIndicador que muestra el precio promedio a medida que vas construyendo la posicion, util para hacer backtest.
Indicator that shows the average price as you build your position, useful for backtesting.
BTC US opening range breakout6PM-7PM IST Trading Range Setup
This indicator captures the price range during the first hour of the US market session (6PM-7PM IST) and uses it as a breakout trading zone. The grey box shows the high and low prices formed during this hour, which often acts as a key reference range for the rest of the US trading session.
How to Use:
Go Long when price breaks and closes above the green line (the top of the range)
Go Short when price breaks and closes below the red line (the bottom of the range)
The lines extend until 3:30AM IST (US session end), giving you clear entry levels throughout the night
This works well because the first hour often sets the tone for the entire session - a breakout from this range typically signals strong directional momentum. Best used on 15-minute charts for crypto or forex trading during US hours
Highlight 10-11 AM NY//@version=5
indicator("Highlight 10-11 AM NY", overlay=true)
// Inputs for flexibility
startHour = input.int(10, "Start Hour (NY time)")
endHour = input.int(11, "End Hour (NY time)")
// Check if the current bar is within the session (uses chart time zone)
inSession = (hour(time, syminfo.timezone) >= startHour) and (hour(time, syminfo.timezone) < endHour)
// Highlight background
bgcolor(inSession ? color.new(color.yellow, 85) : na)
⭐ WUKONG_PRO_V4.2.2_EN ⭐⭐ WUKONG PRO SEMI-AUTO TRADING SYSTEM V4.2.2 ⭐
✅ High Tight Trendline Breakout Method
✅ Simple and highly effective (anyone can do it)
✅ Automatically connect TradingView and MT5 for automatic trading & order management
✅ Focus on tight capital and risk management, do not hold on to losses
✅ Reduce 95% of emotional loss and stress when trading
✅ Suitable for all markets: Forex, Gold, Crypto, Stocks...
♾️ If you do not need to trade automatically via MT5, the Wukong Pro System can also be used as An effective Indicator in Visual Order Management on TradingView charts, helps maintain discipline and good trading psychology (less Stress or FOMO)
💊 WHO IS WUKONG PRO TRADING SYSTEM FOR ? 💊
🚀 Traders who are trading via TradingView and MT5 but are not successful
🚦 Traders who have basic knowledge but often lose due to psychology, emotions, lack of discipline
🤖 Traders who do not like to sit all day in front of the screen (tired and stressed)
🏆 Traders who want to succeed with FTMO, The5ers, Oanda Prop, E8 Market...
🦸 New or Experienced Traders both need Wukong Pro System
==> THERE IS A 30-DAY FREE TRIAL PROGRAM, CONTACT NOW
Analyst HUD — Side / ADX / RSI / rVol (bot thresholds)Analyst HUD — Side / ADX / RSI / rVol (bot thresholds)
A clean heads-up display that puts the essentials right on your chart:
✅ Side – quick trend bias (bullish/bearish)
✅ ADX – trend strength, color-coded
✅ RSI – momentum zones (overbought/oversold/neutral)
✅ rVol – relative volume vs average
Built with bot-style thresholds for instant clarity.
No signals, no clutter — just the key metrics you need to spot strong trends and momentum at a glance.
Futures Tick & Point Value [BoredYeti]Futures Tick & Point Value
This utility displays tick size, dollars per tick, and (optionally) a per-point row for the current futures contract.
Features
• Hardcoded $/tick map for common CME/NYMEX/CBOT/COMEX contracts
• Automatic fallback using pointvalue * mintick for any other symbol
• Table settings: adjustable position, text size, customizable colors
• Optional “Per Point” row showing ticks and $/point
Notes
• Contract specs can vary by broker/exchange and may change over time. Always confirm with official specifications.
• Educational tool only; not financial advice.
Intelligent Currency Breakout ChannelIndicator: Intelligent Currency Breakout Channel
This document provides a detailed explanation of the "Intelligent Currency Breakout Channel" indicator for TradingView.
1. Overview
The Intelligent Currency Breakout Channel is an advanced technical analysis tool designed to identify periods of price consolidation and signal potential breakouts. It automatically draws channels around ranging price action and utilizes sophisticated volume analysis to provide deeper insights into market sentiment. The indicator also includes a built-in logarithmic regression screener to help traders align their breakout signals with the broader market trend.
2. Key Features
Automatic Channel Detection: The indicator identifies periods of low volatility and automatically draws a containing channel (box) around the price action.
Breakout Signals: It generates clear visual alerts (▲ for bullish, ▼ for bearish) when the price closes decisively outside of a channel.
In-Depth Volume Analysis: Within each channel, the indicator plots volume as candlestick-like bars, offering three distinct modes: Total Volume, Buy/Sell Comparison, and Volume Delta. This helps traders gauge the strength and conviction behind price movements.
Real-time Sentiment Gauge: When a channel is active, a dynamic color-graded gauge appears on the right side of the chart. It visualizes the current volume delta momentum relative to its recent range, offering an at-a-glance sentiment reading.
Integrated Trend Screener: A secondary analysis tool based on logarithmic regression is included to determine the underlying trend direction (Up, Down, or Neutral), which can be used to filter breakout signals.
Fully Customizable: Users can extensively customize all parameters, from calculation lengths and breakout sensitivity to the visual appearance of every component.
3. How to Use
Channel Formation: Watch for the indicator to draw a new channel. This signifies that the market is in a consolidation or ranging phase. The formation of a channel itself can be an alertable event.
Volume Interpretation: Observe the volume bars inside the channel. An increase in volume as the price approaches the channel's upper or lower boundary can foreshadow a potential breakout. Use the Volume Display Mode to analyze if buying pressure (Comparison, Delta) or selling pressure is building.
Breakout Confirmation: A bullish breakout signal (▲) appears when the price closes above the channel's upper boundary. A bearish breakout signal (▼) appears when the price closes below the lower boundary. For higher-quality signals, enable the Strong Closes Only option.
Trend Confirmation (Screener): Use the screener's plot and background color to confirm the broader trend. For instance, you might choose to only take bullish breakout signals when the screener indicates an uptrend (green background) and bearish signals when it indicates a downtrend (red background).
Sentiment Gauge: The pointer on the gauge indicates current momentum. A pointer in the upper (green) section suggests bullish pressure, while a pointer in the lower (red) section suggests bearish pressure. This can provide additional confluence for a trade decision.
4. Settings and Inputs
Main Settings
Overlap Channels: If enabled, allows multiple channels to be drawn on the chart simultaneously, even if they overlap. When disabled, a new channel will only form if it doesn't intersect with an existing one.
Strong Closes Only: If enabled, a breakout is only triggered if the midpoint of the candle's body (average of open and close) is outside the channel. This helps filter out false signals caused by long wicks. If disabled, any close outside the channel triggers a breakout.
Normalization Length: The lookback period (in bars) used for price normalization. A higher value creates a more stable normalization but may be slower to react to recent price changes.
Box Detection Length: The lookback period used to detect the channel formation pattern. A lower value will result in more frequent channels but may be more sensitive to noise. A higher value will result in fewer, but potentially more significant, channels.
Volume Analysis
Show Volume Analysis: Toggles the visibility of the candlestick-like volume bars inside the channel.
Volume Display Mode:
Volume: Displays total volume as symmetrical bars around the channel's midline.
Comparison: Shows buying volume (green) above the midline and selling volume (red) below it.
Delta: Shows the net difference between buying and selling volume. Positive delta is shown above the midline, and negative delta is shown below.
Volume Delta Timeframe Source: The timeframe from which to source volume data for calculations. Using a lower timeframe can provide a more granular view of volume dynamics.
Volume Scaling: A multiplier that adjusts the vertical size of the volume bars relative to the channel's height.
Appearance
Volume Text Size: Sets the size of the volume data text displayed in the corners of the channel. Options: Tiny, Small, Medium, Large.
Bullish Color: The primary color for all bullish visual elements, including breakout signals and positive volume bars.
Bearish Color: The primary color for all bearish visual elements, including breakout signals and negative volume bars.
Screener Settings
Lookback Period: The number of bars used for the logarithmic regression calculation to determine the trend.
Screener Type:
Log Regression Channel: The signal is based on the slope of the entire regression channel over the lookback period. An upward sloping channel is bullish (1), and a downward sloping one is bearish (-1).
Logarithmic Regression: The signal is based on the most recent value of the regression line compared to its value 3 bars ago. This provides a more responsive measure of the immediate trend.
5. Alerts
You can set up the following alerts through the TradingView alerts panel:
New Channel Formed: Triggers when a new price consolidation channel is detected and drawn on the chart.
Bullish Breakout: Triggers when the price breaks out and closes above the upper boundary of a channel.
Bearish Breakout: Triggers when the price breaks out and closes below the lower boundary of a channel.
Is In Channel: Triggers on every bar that the price is currently trading inside an active channel.
Signal UP: Triggers when the Screener's signal turns bullish (1).
Signal DOWN: Triggers when the Screener's signal turns bearish (-1).
⭐ WUKONG_PRO_V4.2.2_VN ⭐WUKONG PRO SYSTEM V4.2.2
- High Tight Trendline Breakout Method
- Simple and highly effective (anyone can do it)
- Automatically place orders and manage orders according to the settings
- Automatically connect TradingView and MT5 for automatic trading
- Focus on tight capital and risk management, do not hold on to losses
- Reduce 95% of emotional loss and stress when trading
- Suitable for all markets: Forex, Gold, Crypto, Stocks...
- If you do not need to trade automatically via MT5, the Wukong Pro System can also be used as An effective Indicator in Visual Order Management on TradingView charts, helps maintain discipline and good trading psychology (less Stress or FOMO)
===> THERE IS A 30-DAY FREE TRIAL PROGRAM, CONTACT NOW
FXSArbitrage Spread (Custom Start Time)
This indicator analyzes the spread and correlation between two selected instruments or currency pairs.
Key Features:
Displays the percentage change of the two instruments in a separate chart (does not overlay the main chart).
Lines show the entire historical price movement of the selected instruments.
Calculates the current spread and correlation from a chosen date and time (default — last Monday 00:00).
Spread and corr values are rounded to two decimal places for convenience.
The top-right table displays:
corr — correlation coefficient between the instruments,
spread — current spread between the pairs,
Average max deviation for the period — manual input,
Maximum deviation for the entire period — manual input.
The top-left table shows the color of each pair for clarity.
Alerts can be set for specific corr and spread values.
Features:
Historical lines allow visual tracking of dynamics over the entire available period.
Current spread is calculated separately from the selected start time, allowing analysis of current conditions without affecting historical visualization.
Fully customizable: line colors, calculation period, start date/time for spread, manual statistical data.
AInfluence Manual Data Input Utility Indicator V101AInfluence (Manual Data Input Utility Indicator) V101
Overview
This utility indicator enables you to plot an external data series directly on your TradingView chart. It is designed for users who want to correlate custom datasets, such as sentiment analysis, economic data, or other external metrics, with price action.
Instructions
1. Add the indicator to your chart.
2. Go into the indicator's "Settings" panel.
3. Paste your pre-formatted data into the text input field.
Data Formatting Rules
The script requires a specific format for each data point, which consists of a numerical value and a timestamp
• Structure: Each data point must be on a new line.
• Limit: You can paste a maximum of 146 records.
Example Data:
93.1562,2025-09-06 00:59:11
94.9062,2025-09-06 01:59:21
93.4062,2025-09-06 02:59:18
95.2188,2025-09-06 03:59:31
93.4062,2025-09-06 04:59:21
91.4583,2025-09-06 05:58:51
93.7812,2025-09-06 06:59:17
The source code for this indicator is open and accessible.
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!
Channel Breakout Gold For 15m 1hChannel Breakout – ATR Buffer + RR Fix
This strategy is designed for Gold (XAUUSD) on 15m and 1h timeframes, based on the “Channel Breakout” concept.
When price closes above or below the channel (highest/lowest over a given length), a Buy or Sell signal is triggered with automatic TP and SL placement.
Key Features:
✅ Uses ATR buffer to filter out false breakouts
✅ Customizable Risk:Reward Ratio (RR) for precise trade management
✅ Stop Loss automatically placed at the opposite channel for strong protection
✅ Real-time plotting of TP and SL lines for better visualization
✅ Works well for both Day Trading and Swing Trading
Best suited for traders who want:
- Clear breakout entries
- Robust risk management
- A versatile strategy adaptable to multiple timeframes
⚠️ Note:
- This strategy is for educational and testing purposes only, not financial advice.
- Always backtest/forward test and adjust parameters to fit your trading style and instrument.
================================================
กลยุทธ์ Channel Breakout – ATR Buffer + RR Fix
กลยุทธ์นี้ออกแบบมาเพื่อใช้กับทองคำ (XAUUSD) ใน Timeframe 15m และ 1h โดยอิงตามหลักการ “Channel Breakout”
เมื่อราคาเบรกกรอบบนหรือล่างของราคาย้อนหลัง (Channel Length) จะเกิดสัญญาณ Buy หรือ Sell ตามทิศทาง พร้อมกำหนดจุด TP และ SL อัตโนมัติ
คุณสมบัติเด่น:
✅ ใช้ ATR เป็น Buffer เพื่อลดสัญญาณหลอก (False Breakout)
✅ กำหนด Risk:Reward Ratio (RR) ได้เอง ทำให้ควบคุมกำไร/ขาดทุนต่อไม้ได้ชัดเจน
✅ SL ถูกตั้งที่กรอบตรงข้าม (Opposite Channel) เพื่อให้ป้องกันการกลับตัว
✅ แสดงเส้น TP/SL บนกราฟแบบ Real-Time ให้ผู้ใช้งานเห็นจุดออกชัดเจน
✅ ใช้งานได้ทั้ง Day Trade และ Swing Trade
เหมาะสำหรับเทรดเดอร์ที่ต้องการ:
- ระบบเบรกกรอบที่ชัดเจน
- การจัดการความเสี่ยงที่แม่นยำ
- กลยุทธ์ที่สามารถปรับใช้ได้กับหลาย Timeframe
⚠️ หมายเหตุ:
- กลยุทธ์นี้เป็นเครื่องมือช่วยวิเคราะห์ ไม่ใช่คำแนะนำการลงทุนโดยตรง
- ควรทดสอบ (Backtest/Forward test) และปรับค่าพารามิเตอร์ให้เหมาะกับสไตล์การเทรดและสินทรัพย์ที่ใช้งาน
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: