real_time_candlesIntroduction
The Real-Time Candles Library provides comprehensive tools for creating, manipulating, and visualizing custom timeframe candles in Pine Script. Unlike standard indicators that only update at bar close, this library enables real-time visualization of price action and indicators within the current bar, offering traders unprecedented insight into market dynamics as they unfold.
This library addresses a fundamental limitation in traditional technical analysis: the inability to see how indicators evolve between bar closes. By implementing sophisticated real-time data processing techniques, traders can now observe indicator movements, divergences, and trend changes as they develop, potentially identifying trading opportunities much earlier than with conventional approaches.
Key Features
The library supports two primary candle generation approaches:
Chart-Time Candles: Generate real-time OHLC data for any variable (like RSI, MACD, etc.) while maintaining synchronization with chart bars.
Custom Timeframe (CTF) Candles: Create candles with custom time intervals or tick counts completely independent of the chart's native timeframe.
Both approaches support traditional candlestick and Heikin-Ashi visualization styles, with options for moving average overlays to smooth the data.
Configuration Requirements
For optimal performance with this library:
Set max_bars_back = 5000 in your script settings
When using CTF drawing functions, set max_lines_count = 500, max_boxes_count = 500, and max_labels_count = 500
These settings ensure that you will be able to draw correctly and will avoid any runtime errors.
Usage Examples
Basic Chart-Time Candle Visualization
// Create real-time candles for RSI
float rsi = ta.rsi(close, 14)
Candle rsi_candle = candle_series(rsi, CandleType.candlestick)
// Plot the candles using Pine's built-in function
plotcandle(rsi_candle.Open, rsi_candle.High, rsi_candle.Low, rsi_candle.Close,
"RSI Candles", rsi_candle.candle_color, rsi_candle.candle_color)
Multiple Access Patterns
The library provides three ways to access candle data, accommodating different programming styles:
// 1. Array-based access for collection operations
Candle candles = candle_array(source)
// 2. Object-oriented access for single entity manipulation
Candle candle = candle_series(source)
float value = candle.source(Source.HLC3)
// 3. Tuple-based access for functional programming styles
= candle_tuple(source)
Custom Timeframe Examples
// Create 20-second candles with EMA overlay
plot_ctf_candles(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 20,
timezone = -5,
tied_open = true,
ema_period = 9,
enable_ema = true
)
// Create tick-based candles (new candle every 15 ticks)
plot_ctf_tick_candles(
source = close,
candle_type = CandleType.heikin_ashi,
number_of_ticks = 15,
timezone = -5,
tied_open = true
)
Advanced Usage with Custom Visualization
// Get custom timeframe candles without automatic plotting
CandleCTF my_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 30
)
// Apply custom logic to the candles
float ema_values = my_candles.ctf_ema(14)
// Draw candles and EMA using time-based coordinates
my_candles.draw_ctf_candles_time()
ema_values.draw_ctf_line_time(line_color = #FF6D00)
Library Components
Data Types
Candle: Structure representing chart-time candles with OHLC, polarity, and visualization properties
CandleCTF: Extended candle structure with additional time metadata for custom timeframes
TickData: Structure for individual price updates with time deltas
Enumerations
CandleType: Specifies visualization style (candlestick or Heikin-Ashi)
Source: Defines price components for calculations (Open, High, Low, Close, HL2, etc.)
SampleType: Sets sampling method (Time-based or Tick-based)
Core Functions
get_tick(): Captures current price as a tick data point
candle_array(): Creates an array of candles from price updates
candle_series(): Provides a single candle based on latest data
candle_tuple(): Returns OHLC values as a tuple
ctf_candles_array(): Creates custom timeframe candles without rendering
Visualization Functions
source(): Extracts specific price components from candles
candle_ctf_to_float(): Converts candle data to float arrays
ctf_ema(): Calculates exponential moving averages for candle arrays
draw_ctf_candles_time(): Renders candles using time coordinates
draw_ctf_candles_index(): Renders candles using bar index coordinates
draw_ctf_line_time(): Renders lines using time coordinates
draw_ctf_line_index(): Renders lines using bar index coordinates
Technical Implementation Notes
This library leverages Pine Script's varip variables for state management, creating a sophisticated real-time data processing system. The implementation includes:
Efficient tick capturing: Samples price at every execution, maintaining temporal tracking with time deltas
Smart state management: Uses a hybrid approach with mutable updates at index 0 and historical preservation at index 1+
Temporal synchronization: Manages two time domains (chart time and custom timeframe)
The tooltip implementation provides crucial temporal context for custom timeframe visualizations, allowing users to understand exactly when each candle formed regardless of chart timeframe.
Limitations
Custom timeframe candles cannot be backtested due to Pine Script's limitations with historical tick data
Real-time visualization is only available during live chart updates
Maximum history is constrained by Pine Script's array size limits
Applications
Indicator visualization: See how RSI, MACD, or other indicators evolve in real-time
Volume analysis: Create custom volume profiles independent of chart timeframe
Scalping strategies: Identify short-term patterns with precisely defined time windows
Volatility measurement: Track price movement characteristics within bars
Custom signal generation: Create entry/exit signals based on custom timeframe patterns
Conclusion
The Real-Time Candles Library bridges the gap between traditional technical analysis (based on discrete OHLC bars) and the continuous nature of market movement. By making indicators more responsive to real-time price action, it gives traders a significant edge in timing and decision-making, particularly in fast-moving markets where waiting for bar close could mean missing important opportunities.
Whether you're building custom indicators, researching price patterns, or developing trading strategies, this library provides the foundation for sophisticated real-time analysis in Pine Script.
Implementation Details & Advanced Guide
Core Implementation Concepts
The Real-Time Candles Library implements a sophisticated event-driven architecture within Pine Script's constraints. At its heart, the library creates what's essentially a reactive programming framework handling continuous data streams.
Tick Processing System
The foundation of the library is the get_tick() function, which captures price updates as they occur:
export get_tick(series float source = close, series float na_replace = na)=>
varip float price = na
varip int series_index = -1
varip int old_time = 0
varip int new_time = na
varip float time_delta = 0
// ...
This function:
Samples the current price
Calculates time elapsed since last update
Maintains a sequential index to track updates
The resulting TickData structure serves as the fundamental building block for all candle generation.
State Management Architecture
The library employs a sophisticated state management system using varip variables, which persist across executions within the same bar. This creates a hybrid programming paradigm that's different from standard Pine Script's bar-by-bar model.
For chart-time candles, the core state transition logic is:
// Real-time update of current candle
candle_data := Candle.new(Open, High, Low, Close, polarity, series_index, candle_color)
candles.set(0, candle_data)
// When a new bar starts, preserve the previous candle
if clear_state
candles.insert(1, candle_data)
price.clear()
// Reset state for new candle
Open := Close
price.push(Open)
series_index += 1
This pattern of updating index 0 in real-time while inserting completed candles at index 1 creates an elegant solution for maintaining both current state and historical data.
Custom Timeframe Implementation
The custom timeframe system manages its own time boundaries independent of chart bars:
bool clear_state = switch settings.sample_type
SampleType.Ticks => cumulative_series_idx >= settings.number_of_ticks
SampleType.Time => cumulative_time_delta >= settings.number_of_seconds
This dual-clock system synchronizes two time domains:
Pine's execution clock (bar-by-bar processing)
The custom timeframe clock (tick or time-based)
The library carefully handles temporal discontinuities, ensuring candle formation remains accurate despite irregular tick arrival or market gaps.
Advanced Usage Techniques
1. Creating Custom Indicators with Real-Time Candles
To develop indicators that process real-time data within the current bar:
// Get real-time candles for your data
Candle rsi_candles = candle_array(ta.rsi(close, 14))
// Calculate indicator values based on candle properties
float signal = ta.ema(rsi_candles.first().source(Source.Close), 9)
// Detect patterns that occur within the bar
bool divergence = close > close and rsi_candles.first().Close < rsi_candles.get(1).Close
2. Working with Custom Timeframes and Plotting
For maximum flexibility when visualizing custom timeframe data:
// Create custom timeframe candles
CandleCTF volume_candles = ctf_candles_array(
source = volume,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 60
)
// Convert specific candle properties to float arrays
float volume_closes = volume_candles.candle_ctf_to_float(Source.Close)
// Calculate derived values
float volume_ema = volume_candles.ctf_ema(14)
// Create custom visualization
volume_candles.draw_ctf_candles_time()
volume_ema.draw_ctf_line_time(line_color = color.orange)
3. Creating Hybrid Timeframe Analysis
One powerful application is comparing indicators across multiple timeframes:
// Standard chart timeframe RSI
float chart_rsi = ta.rsi(close, 14)
// Custom 5-second timeframe RSI
CandleCTF ctf_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 5
)
float fast_rsi_array = ctf_candles.candle_ctf_to_float(Source.Close)
float fast_rsi = fast_rsi_array.first()
// Generate signals based on divergence between timeframes
bool entry_signal = chart_rsi < 30 and fast_rsi > fast_rsi_array.get(1)
Final Notes
This library represents an advanced implementation of real-time data processing within Pine Script's constraints. By creating a reactive programming framework for handling continuous data streams, it enables sophisticated analysis typically only available in dedicated trading platforms.
The design principles employed—including state management, temporal processing, and object-oriented architecture—can serve as patterns for other advanced Pine Script development beyond this specific application.
------------------------
Library "real_time_candles"
A comprehensive library for creating real-time candles with customizable timeframes and sampling methods.
Supports both chart-time and custom-time candles with options for candlestick and Heikin-Ashi visualization.
Allows for tick-based or time-based sampling with moving average overlay capabilities.
get_tick(source, na_replace)
Captures the current price as a tick data point
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
na_replace (float) : Optional - Value to use when source is na
Returns: TickData structure containing price, time since last update, and sequential index
candle_array(source, candle_type, sync_start, bullish_color, bearish_color)
Creates an array of candles based on price updates
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
sync_start (simple bool) : Optional - Whether to synchronize with the start of a new bar
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of Candle objects ordered with most recent at index 0
candle_series(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides a single candle based on the latest price data
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: A single Candle object representing the current state
candle_tuple(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides candle data as a tuple of OHLC values
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Tuple representing current candle values
method source(self, source, na_replace)
Extracts a specific price component from a Candle
Namespace types: Candle
Parameters:
self (Candle)
source (series Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
na_replace (float) : Optional - Value to use when source value is na
Returns: The requested price value from the candle
method source(self, source)
Extracts a specific price component from a CandleCTF
Namespace types: CandleCTF
Parameters:
self (CandleCTF)
source (simple Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
Returns: The requested price value from the candle as a varip
method candle_ctf_to_float(self, source)
Converts a specific price component from each CandleCTF to a float array
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
Returns: Array of float values extracted from the candles, ordered with most recent at index 0
method ctf_ema(self, ema_period)
Calculates an Exponential Moving Average for a CandleCTF array
Namespace types: array
Parameters:
self (array)
ema_period (simple float) : Period for the EMA calculation
Returns: Array of float values representing the EMA of the candle data, ordered with most recent at index 0
method draw_ctf_candles_time(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar time coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using time-based x-coordinates
method draw_ctf_candles_index(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar index coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using index-based x-coordinates
method draw_ctf_line_time(self, source, line_size, line_color)
Renders a line representing a price component from the candles using time coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_time(self, line_size, line_color)
Renders a line from a varip float array using time coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_index(self, source, line_size, line_color)
Renders a line representing a price component from the candles using index coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
method draw_ctf_line_index(self, line_size, line_color)
Renders a line from a varip float array using index coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots tick-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots tick-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots time-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots time-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_candles(source, candle_type, sample_type, number_of_ticks, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, enable_ema, line_width, ema_color, use_time_indexing)
Unified function for plotting candles with comprehensive options
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Optional - Type of candle chart to display
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
ema_period (simple float) : Optional - Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
enable_ema (bool) : Optional - Whether to display the EMA overlay
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with optional EMA overlay
ctf_candles_array(source, candle_type, sample_type, number_of_ticks, number_of_seconds, tied_open, bullish_color, bearish_color)
Creates an array of custom timeframe candles without rendering them
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to create (candlestick or Heikin-Ashi)
sample_type (simple SampleType) : Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of CandleCTF objects ordered with most recent at index 0
Candle
Structure representing a complete candle with price data and display properties
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
candle_color (series color) : Color to use when rendering the candle
ready (series bool) : Boolean indicating if candle data is valid and ready for use
TickData
Structure for storing individual price updates
Fields:
price (series float) : The price value at this tick
time_delta (series float) : Time elapsed since the previous tick in milliseconds
series_index (series int) : Sequential index identifying this tick
CandleCTF
Structure representing a custom timeframe candle with additional time metadata
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
open_time (series int) : Timestamp marking when the candle was opened (in Unix time)
time_delta (series float) : Duration of the candle in milliseconds
candle_color (series color) : Color to use when rendering the candle
Custom
Triple Doji SequenceThe Triple Doji Sequence indicator helps traders identify consecutive Doji candlestick patterns, allowing them to choose between spotting single, double, or triple Dojis. A Doji is detected when the candle's body is small relative to its wicks, with either the upper or lower wick being significantly larger. Users can customize their own Doji criteria by adjusting the body size and wick dominance settings. The indicator ensures that consecutive Dojis align in the same direction before confirming a valid pattern, making it easier to identify market indecision or potential trend reversals.
When the chosen Doji sequence is detected, the indicator plots a star (*) above bearish Dojis (upper wick dominant) and below bullish Dojis (lower wick dominant). It also sends alerts when a valid sequence is confirmed at the close of the bar. This tool helps traders refine their strategy by spotting repeated Doji formations, which may indicate key turning points or continuation patterns in price action.
How to Use the Triple Doji Sequence Indicator?
Apply the Indicator:
Add the Triple Doji Sequence indicator to your TradingView chart.
It will automatically scan for Doji patterns based on your settings.
Customize Your Doji Criteria:
Adjust the body size and wick dominance settings to define what qualifies as a Doji.
Choose whether to detect single, double, or triple Doji sequences.
Interpret the Signals:
A star (*) above a candle signals a bearish Doji (upper wick dominant).
A star (*) below a candle signals a bullish Doji (lower wick dominant).
Set Up Alerts:
Enable alerts to receive notifications when a Doji sequence is confirmed at bar close.
Choose alert frequency based on your trading strategy (e.g., once per bar, once per bar close).
Use in Trading Strategy:
Doji sequences can indicate trend reversals or market indecision.
Combine this indicator with support/resistance levels, volume, or other indicators to confirm signals.
PS: Good luck in finding a Triple Doji :)
Custom Index CompositeCustom Index Composite calculates an unweighted composite index by averaging the daily returns of multiple stock tickers. Instead of using price-level weighting, it focuses solely on percentage change, allowing you to compare diverse market themes side by side on a common basis.
Why Use a Custom Index Composite?
Unlike traditional indices that often lean on market capitalization or price-level data, a custom composite based solely on returns strips out the bias inherent to high-priced stocks. This provides several benefits:
Objective Cross-Comparison:
When stocks or market themes trade at very different price levels, it can be difficult to assess performance objectively. Using percentage returns, the composite creates an even playing field, enabling a clear comparison between different assets or themes.
Tailored Benchmarking:
By selecting and combining specific tickers, you can create benchmarks that better represent the segments or strategies you’re interested in. This is particularly useful when standard indices do not capture the nuances of your investment approach.
Performance Normalization:
Converting raw price data into daily percentage returns minimizes distortions that arise from price differences. This normalization helps in understanding true performance trends across the chosen tickers, making the composite index a more reliable gauge of relative market movement.
Custom Analysis Framework:
The indicator offers flexibility to adjust the lookback period (defaulting to about 3 months) so you can fine-tune the sensitivity of the index to recent market behavior. This enables you to either smooth out volatility or capture a more immediate trend, depending on your analytical needs.
Key Features:
Configurable Appearance:
You can easily configure the line color, line width, index name, and index name color via the options panel.
Ticker Configuration:
By default, you can enter up to 15 different tickers into the composite index. Technically, the indicator supports up to 40 tickers (these additional inputs are commented out by default to maintain performance), and you may enable them individually if required.
Calculated Bars Length:
The indicator uses a “Calculated bars length” setting, which is set by default to 63 days (approximately 3 months). This value can be adjusted, and it is recommended to use the greatest common denominator for consistent analysis.
How To Configure Your Chart:
Add the Indicator:
Place the Custom Index Composite on your chart.
Disable Main Symbol Visibility:
Hide the primary symbol’s plot and set its scale to “None” to prevent interference with the composite display.
Pin to Right Scale:
Set the scale of the first composite indicator to “Pinned to right scale.” This helps maintain consistency across different composite indicators.
Add Multiple Composites:
You can add additional composite indicators and set their scales to “Pinned to right scale” (or alternatively to “A”) for convenient comparison.
Limitations:
If a ticker symbol is set once in the options, it cannot be cleared to an empty value later. As a result, the symbol will continue to appear in the indicator’s title on the chart. The only way to remove an unwanted symbol is to completely reset the settings and re-enter your desired tickers.
[EmreKb] Custom PatternCustom Pattern
With this indicator, you can create and display as many patterns as you want on the chart. The indicator works by taking two inputs. We can start the explanation by describing these inputs.
Inputs
Zigzag Length: Length for zigzag legs.
Patternscript Code: Patternscript code. (But what is patternscript?)
Explanation Of Patternscript
Patternscript (it's a completely fictional script language) is a scripting language that allows you to write your own patterns, and it operates within Pinescript). Let's take a look at the syntax of this language.
{
(, )
}
...
This means that the Fibonacci levels drawn from the from_point to the to_point must have the target_point between the min_fib_level and max_fib_level .
Let's see a few practical examples.
Patternscript Code For ABCD Pattern
ABCD{
ABC(0.618, 0.886)
BCD(1.272, 1.618)
}
ABC(0.618, 0.886): Fibonacci drawn from the A to B, must have the C between the 0.618 and 0.886
BCD(1.272, 1.618): Fibonacci drawn from the B to C, must have the D between the 1.272 and 1.618
Patternscript Code For Multiple Pattern
BAT{
XAB(0.382, 0.5)
ABC(0.382, 0.886)
BCD(1.618, 2.618)
XAD(0.382, 0.886)
}
ABCD{
ABC(0.618, 0.886)
BCD(1.272, 1.618)
}
Notes:
You can set the pattern name as you like, this is not related to the pattern rules.
There is no limit for pattern count, but remember pine limits.
Stock vs Custom Symbol OutperformanceStock vs Custom Symbol Outperformance" is a powerful technical analysis indicator designed to help traders and investors gauge the relative performance of a stock against a selected benchmark symbol. This tool enables users to easily visualize how a stock is performing in comparison to another asset, such as an index or another stock.
Key Features:
Custom Symbol Comparison: Input any symbol to compare against the stock of interest, allowing for flexible analysis tailored to specific market conditions.
Outperformance Calculation: The indicator calculates the percentage change in price for both the stock and the selected benchmark, providing a clear view of relative performance.
Moving Average Smoothing: A customizable moving average smooths the outperformance data, helping to identify trends and reduce noise in the signals.
Threshold Lines: Set upper and lower threshold lines to visualize significant levels of outperformance or underperformance, aiding in decision-making.
Dynamic Color Coding: The outperformance bars are color-coded—green indicates that the stock is outperforming the benchmark, while red indicates underperformance.
How to Use:
Select a Benchmark: Use the input field to choose the symbol against which you want to compare the stock.
Adjust Parameters: Modify the moving average length and set your desired thresholds for easier identification of performance metrics.
Interpret Results: Analyze the plot for insights into the stock's performance relative to the benchmark, with the moving average providing additional context for trends.
This indicator is ideal for traders looking to refine their strategies by understanding how individual stocks measure up against key benchmarks in the market.
Growth Producer
Applicable to FTX:ETHPERP 15 min
Relative volatility index (RVI) that will determine the entry and exit points only when the volatility will start to increase and Money Flow index as an additional point for entry.
IMPORTANT
• Input Partial take profits in your Bot settings
• This is a trend strategy and works better in the trending market
• We added the trend identifier using the EMA and SMA interaction
• We added Take profit and stop loss levels
• We added inputs for the period selection, so you could see how the strategy is performing on a monthly basis.
• RVI for the entry conditions
• MFI was added for the additional entries.
• Partial Take-profits
[-_-] DictionaryThe script shows an example implementation of dictionary-like data type which can store key:value pairs (Python style). Both keys and values can have any of the following type:
• string
• integer
• float
• boolean
• color
You can add items of different types to the same dictionary (e.g. key = 12 and value = "value" stored in the same dictionary with key = "key" and value = 0.23).
Under the hood dictionary is a custom Object (see www.tradingview.com), that has two array fields (one for storing keys, another for storing values). Keys and values of different types are converted into a string representation when adding a new item to the dictionary. The value is then converted back to certain type (bool/color/etc.) from that string representation when being retrieved. Script also utilises the new Methods (see www.tradingview.com).
The following methods are implemented:
• init() -> initialises the array fields of dictionary (without this the script throws an error "Array methods can't be called when ID of array is na"
• set(key, value) -> add a new item to dictionary; if an item for given key already exists - change it to new value
• getS(key) -> get value of string type
• getI(key) -> get value of integer type
• getF(key) -> get value of float type
• getB(key) -> get value of boolean type
• getC(key) -> get value of color type
• remove(key) -> removes item from dictionary
• len() -> get length of dictionary (the number of keys)
I could not make just one "get" function that returns any type of value (color/string/etc.), so instead I created a get function for each value type. Example usage:
• you add a string item: dictionary.set(2, "string here")
• you add a float item: dictionary.set(3, 24.56)
• to retrieve first value (key=2) do this: dictionary.getS(2)
• to retrieve second value (key=3) do this: dictionary.getF(3)
TICK - Custom Tickers [Pt]Traditionally, the TICK index is a technical analysis indicator that shows the difference in the number of stocks that are trading on an uptick vs a downtick in a particular period of time. This indicator allows user to choose up to 40 tickers to calculate TICK.
By default, it uses the SPY Top 40 stocks, but can be changed to any tickers.
There are options to show:
- Top 7 , ie. can be used for just showing TICK for FAANGMT => $FB + $AMZN + $AAPL + $NFLX + $GOOG + $MSFT + $TSLA
- Top 10
- Top 20
- Top 30
- Top 40
Data can be displayed in candle bars, line, or both.
Enjoy~
Simple OHLC Custom Range Interactive█ OVERVIEW
This indicator show lines of OHLC which can be commonly used as support and resistance zones.
OHLC can be shown table with candlestick visual.
Color of candlestick depends on direction of bullish / bearish of the chosen candlestick.
█ INSPIRATION
Inspired by design, code and usage of CAGR . Basic usage of custom range / interactive, pretty much explained here . Credits to TradingView .
█ FEATURES
Table can positioned by any position and font size can be resized.
OHLC can be in full or simple name.
Lines can be extend either right, left, both or none.
█ HOW TO USE
Only 1 point is required.
Dont worry about magnet, point will attached depends on High or Low of the candle.
█ USAGE / TIPS EXAMPLES (Description explained in each image)
Custom IndexEnables users to create their own custom Stock Index with up to 29 tickers! Has included optionality to include/exclude certain sectors, plot sectors individually and measure in gold. Good for having a look at how your favorite tickers have performed (with your modification of course). Also has option to show Moving Averages for your convenience.
Volume Spread for VSA CustomHey everyone, I have been using volume a lot more lately as price action can sometimes get manipulated but volume shows us the truth!
Anyways, I have enjoyed the Volume Spread for VSA indicator but wished I had the code to change a few settings. This volume indicator includes spread analysis with the ability to customize input values and I'm making it open source so you can do with it as you please.
I have made notes all throughout the code to give suggestions on a few changes or why I have written it in such a way. I have also tried to section everything off to make it easier to see where each piece of the code is used. Overall I think it is a good example of how to code cleanly and how to add useful notes when you are learning Pine for yourself :D
The indicator on the price chart is my Donchian Channel indicator, which you can also find on my profile. This is the one I use every day.
[FR]WmThis a water mark that uses a table to allow placement at 9 different locations on the screen
you can either pick on of the given Date and time formats or you can choose custom and build your own
One of the reasons for this project I wanted to be able to add the "s,m,h" to the water marks timeframe not have i.e. "240" and have it say 4h..
you can select what format for the dates from in the settings if the user selects custom it will make it so you can input what ever format
string into the input box "Custom Format input'"
Hope You Enjoy!
FFriZz
Custom Price LineThis indicator lets you freely customize your price line. Choose between static or dynamic colors for falling/rising prices. In addition you can adjust the following:
Line style
Thickness
Length
Direction
It is also possible to mix different designs by using a single indicator.
Customized Multi EMAPlot several EMA with only one script.
Default EMA: 20、50、100、200.
All of these are adjustable.
Also, Vegas tunnel and filter line can be presented or not according to your needs.
HighLow Box Highlight between EarningsHighLow Box Highlight between Earnings
This is an indicator to highlight area between two earning periods and their highest and lowest points.
It also alternates the highlight color in each subsequent block.
Tested to work in 1D charts and 1M charts
Just drop a message, if you want this further developed with more features.
Note: This was requested by user Meatpye on a forum.
%-[Guz] Vortex Indicator Custom// Custom Vortex Strategy (backtester)
// Custom version of the Vortex indicators that adds many features:
// -Triggers trades after a threshold is reached instead of the normal vortex lines cross (once the difference between the 2 lines is important enough)
// -Smooths the Vortex lines with an EMA
// -Adds Take Profit and Stop Loss selection
// -Adds the possibility to go Long only, Short only or both of them
// ! notice that it uses 10% position size and 0.04% trade fee, found on some crypto exchanges futures contracts
// Allows testing leverage with position size modification (values above 100% position size, to be done with caution)
// Not an investment advice
Simple Watchlist with % Change Screener & AlertsHi fellow traders..
TV has generously increased the number of alerts!!
A Simple Watchlist with heatmap based on % change on daily timeframe.
Gives % change and RSI
you can set the percentage in the input box and then set alerts on your favorite watchlist.
Alerts also include days high and low..
Simple Table and array based code.
set for scrip close >10 can be easily changed in line 43..
Hope you Like it!
Custom Date Buy/Sell StrategyThis strategy allows you to back test longing or shorting during a period of time between two dates.
Make sure you are in the daily time frame while viewing the performance and trade history to ensure you have the most historical data as possible from Trading View.
Finally, due to the way Trading View enters trades at the end of a candle, you must subtract one day from your starting and your end dates.
SuperTrend - Custom Screener and Dynamic AlertsTrading View today published a desktop Bad Internet connection indicator ?! which set me thinking…
Despite recently introduced Dynamic Alerts many scripts do not leverage the information available for active traders and traders on the GO!
So decided to share this script totally ALERT focused on one of the most popular DAY trading indicators.
Of course no more BAD internet problem as long your TV APP is configured , you will have enough data for a mental picture of the chart..
The Alerts give you the BAR Close , %percent gain or loss over previous day CLOSE ++ Previous Day High and Low to effectively plan your trade without a chart!(just in case)
2 additions in the way Alerts are delivered over the last script :
1. You get SUMMARY alerts or concatenated alerts by default , however if you uncomment or activate code lines 48 and 55 you will get individual Stock alerts Too!
2. Summary Alerts will come only if there is some Buy or Sell signal NO more empty Alerts!
Few useful EXTRAS in the code :
1. Flexible code can convert any indicator to screener or Alert function.
2. You will NOT get Mutable Variable error while converting any indicator to screener as long as the function is in "GLOBAL" scope..
3. Many Custom Screeners are available but few give OHLC data in output so easily…and very difficult for traders to MODIFY hundreds of lines of code..
4. For UP or DOWN on SCREEN Stock monitoring copy /paste functions in line 41 and 42 in lieu of CROSS functions in 44 and 51 respectively..
5. You can also uncomment/activate lines 66 and 67 for labels in monitoring.
6. The default mode of the scripts is set to Alerts!
Max Stocks only 20!
Finally idea is to help traders to use the great features that TV works so hard to create and constantly improvise.
Enjoy Profitable Trading on the Fly !!
Example - Custom Defined Dual-State SessionThis script example aims to cover the following:
defining custom timeframe / session windows
gather a price range from the custom period ( high/low values )
create a secondary "holding" period through which to display the data collected from the initial session
simple method to shift times to re-align to preferred timezone
Articles and further reading:
www.investopedia.com - trading session
Reason for Study:
Educational purposes only.
Before considering writing this example I had seen multiple similar questions
asking how to go about creating custom timeframes or sessions, so it seemed
this might be a good topic to attempt to create a relatively generic example.
Nifty Pharma VolumeThis indicator plots volume for the index Nifty Pharma using data from it's constituent stocks.
Code taken from @daytraderph 's script called Custom Volume.
[SK] Custom Klinger OscillatorThis Custom Klinger Oscillator allows you to change the time frames for the Force Volume and Signal calculations to use instead of it's default values. Although the default Fibonacci values ( 34, 55 and 13 ) provide exceptional signals, you can now explore using lower Fibonacci numbers and get faster signals for your own adventures in the market.
This indicator adds conditional coloring of the Klinger line when over / under the signal along with a transparent fill cloud between both lines colored by the same condition. You can change colors to your preference on the style configurations.
--
Below is more information on the KIinger Oscillator from investopedia:
Interpretations for Price Direction
The Klinger Oscillator is fairly complex to calculate, but it's based on the idea of force volume, which accounts for volume, trend (positive or negative), and temp (based on multiple inputs and if/then statements). Using this data, the oscillator is created by looking at the difference between two exponential moving averages of force volume involving different time frames (typically 34 and 55). The idea is to show how the volume flowing through the securities is impacting its long-term and short-term price direction.
The Signal Line
A signal line (13-period moving average) is used to trigger buy or sell signals. This technique is very similar to signals that are created with other indicators such as the moving average convergence divergence (MACD). While these are the basic signals generated by these indicators, it's important to note that these techniques may generate a lot of trading signals that may not be as effective in sideways markets.
The Uptrend
When an asset is in an overall uptrend—such as when it is above its 100-period moving average and the Klinger is above zero or moving above zero—traders could buy when the Klinger oscillator moves above the signal line from below.
Klinger noted that when a stock was in an uptrend, and then dropped to unusually low levels below zero, and then moved above its signal line, this was a favorable long position to take.
The Downtrend
When an asset is in an overall downtrend, traders could sell or short-sell when the Klinger oscillator moves below the signal line from above. Klinger noted this was especially noteworthy when the indicator had seen an uncharacteristic spike above zero.
The zero line is also used by some traders to mark the transition from an uptrend to downtrend, or vice versa. While such signals won't always agree with price movements, a move above zero helps confirm a rising price, while a drop below zero helps confirm a falling price.
Klinger Oscillator and Divergence
The Klinger oscillator also uses divergence to identify when the indicator's inputs are not confirming the direction of the price move. It's a bullish sign when the value of the indicator is heading upward while the price of the security continues to fall. It is a bearish signal when the price is rising but the indicator is falling. Divergence can be coupled with signal line crossovers to generate trades. For example, if a bearish divergence forms, a sell or short-sell could be initiated the next time the Klinger crosses below the signal line.
[SK] Double MACDThe Double MACD indicator is precisely two different MACD indicators plotted on the same axis for precise visual correlation between each other.
This correlation provides more information than a single regular MACD by allowing you to compare the signals of a shorter timeframe to the default or longer timeframe,
showing the strength of the change in momentum and the peak of the momentum between both configurations.
The indicator has cloud options by default if you toggle on the MACD / Signal lines for better readability.
The cloud will change color to the line on top of it's set. This is to help you not get lost in the 4 different lines.
Customize the indicator to your preference and make it your own
If you'd like a candle like visualization, change the short MACD plot style to a histogram.
For a beautiful double bars style, select bars on both configurations and set the transparency to 30 - 40
For a dynamic moving average style, go with the line plot style ( default )
All MACD/Signal lines are toggled off by default, toggle them on in the inputs section.
On the styles panel, you can turn off the cloud fills or the lines.
Change all the colors you'd like!
High/Low X Bars AgoThis indicator will plot a line on your chart that shows the highest high point between two previous points on the chart. It does this by reporting the highest point of X number of candles, and begins the look-back X number of candles ago.
Default candle group size is 50, and default look-back begins 50 candles back.
With these settings, the script will essentially plot the highest high point between the candle that printed 100 candles ago, and the candle that printed 50 candles ago.
Options are available for looking for the highest point, or lowest point, with configurable distances in the look-back and candle group ranges.
This script was custom built by Pine-Labs for a user who requested it.