100 MAThis is a 100-period Simple Moving Average (SMA) indicator, designed to highlight longer-term trends. The MA 100 provides insight into overall market direction and helps identify key support and resistance levels.
Indicadores e estratégias
50 MAThis is a simple 50-period Simple Moving Average (SMA) indicator, designed to identify medium-term trends. The MA 50 helps in spotting potential support and resistance levels and aids in filtering market movements.
My script//@version=5
strategy("Advanced Breakout + EMA Trend Strategy ", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// === INPUTS === //
fastEMA_len = input.int(9, title="Fast EMA")
slowEMA_len = input.int(21, title="Slow EMA")
atrLen = input.int(14, title="ATR Length")
atr_mult_sl = input.float(1.5, title="ATR Stop Loss Multiplier")
atr_mult_tp = input.float(3.0, title="ATR Take Profit Multiplier")
consolidationBars = input.int(20, title="Consolidation Lookback")
volumeSpikeMult = input.float(1.8, title="Volume Spike Multiplier")
leverage = input.int(10, title="Leverage", minval=1)
// === CALCULATIONS === //
fastEMA = ta.ema(close, fastEMA_len)
slowEMA = ta.ema(close, slowEMA_len)
atr = ta.atr(atrLen)
rangeHigh = ta.highest(high, consolidationBars)
rangeLow = ta.lowest(low, consolidationBars)
volumeAvg = ta.sma(volume, consolidationBars)
// === MARKET CONDITIONS === //
isTrendingUp = fastEMA > slowEMA
isTrendingDown = fastEMA < slowEMA
isConsolidating = (rangeHigh - rangeLow) / close < 0.02
isBreakoutUp = close > rangeHigh and volume > volumeAvg * volumeSpikeMult
isBreakoutDown = close < rangeLow and volume > volumeAvg * volumeSpikeMult
// === ENTRY CONDITIONS === //
enterLong = isConsolidating and isBreakoutUp and isTrendingUp
enterShort = isConsolidating and isBreakoutDown and isTrendingDown
// === EXIT PRICES === //
longSL = close - atr * atr_mult_sl
longTP = close + atr * atr_mult_tp
shortSL = close + atr * atr_mult_sl
shortTP = close - atr * atr_mult_tp
// === ENTRY/EXIT EXECUTION === //
if (enterLong)
strategy.entry("Long", strategy.long, comment="Long Entry")
strategy.exit("TP/SL Long", from_entry="Long", stop=longSL, limit=longTP)
if (enterShort)
strategy.entry("Short", strategy.short, comment="Short Entry")
strategy.exit("TP/SL Short", from_entry="Short", stop=shortSL, limit=shortTP)
// === CHART PLOTTING === //
plot(fastEMA, color=color.green, title="Fast EMA")
plot(slowEMA, color=color.red, title="Slow EMA")
plotshape(enterLong, title="Long Entry", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(enterShort, title="Short Entry", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")
// === ALERT MESSAGES === //
alertcondition(enterLong, title="Long Signal", message="Long Entry Signal: BUY at {{close}} | Leverage: " + str.tostring(leverage))
alertcondition(enterShort, title="Short Signal", message="Short Entry Signal: SELL at {{close}} | Leverage: " + str.tostring(leverage))
MTF Pivot Fib Speed Resistance FansOverview
This Pine Script indicator, titled "MTF Pivot Fib Speed Resistance Fans", is a multi-timeframe tool that automatically plots Fib Speed Resistance Fan lines based on pivot structures derived from higher timeframes. It mirrors the functionality of TradingView’s built-in “Fib Speed Resistance Fan” drawing tool, but in a dynamic, programmatic way. It uses pivot highs and lows to anchor fan projections, drawing forward-facing trend lines that align with well-known Fibonacci ratios and their extensions.
Pivot Detection Logic
The script identifies pivots by comparing the current bar’s high and low against the highest and lowest prices over a user-defined pivot period. This pivot detection occurs on a higher timeframe of your choice, giving a broader and more strategic view of price structure. The script tracks direction changes in the pivot trend and stores only the most recent few pivots to maintain clean and meaningful fan drawings.
Fan Direction Control
The user can select whether to draw fans for "Buys", "Sells", or "Both". The script only draws fan lines when a new directional move is detected based on the pivot structure and the selected bias. For example, in “Buys” mode, a rising pivot followed by another higher low will trigger upward fan projections.
Fib Speed Resistance Levels
Once two pivots are identified, the script draws multiple fan lines from the first pivot outward, at angles defined by a preset list of Fibonacci levels. These fan lines help visualize speed and strength of a price move.
The script also draws a horizontal line from the pivot for additional confluence at the base level (1.0).
Price Level Plotting
In addition to drawing fan lines, the indicator also plots their price levels on the right-hand price scale. This makes it easier for users to visually reference the projected support and resistance levels without needing to trace the lines manually across the chart.
Mapping to TradingView’s "Fib Speed Resistance Fan"
The expanded set of values used in this script is not arbitrary—they closely align with the default and extended levels available in TradingView's built-in "Fib Speed Resistance Fan" tool.
TradingView’s Fib Fan tool offers several levels by default, including traditional Fibonacci ratios like 0.382, 0.5, 0.618, and 1. However, if you right-click the tool and open its settings, you’ll find additional toggles for levels like 1.618, 2.000, 2.618, and even 4.000. These deeper levels are used to project stronger trend continuations beyond the standard retracement zones.
The inclusion of levels such as 0.25, 0.75, and 1.34 reflects configurations that are available when you manually add or customize levels in TradingView’s fan tool. While 1.34 is not a canonical Fibonacci ratio, it is often found in hybrid Gann/Fib methods and is included in some preset templates in TradingView’s drawing tool for advanced users.
By incorporating these levels directly into the Pine Script, the indicator faithfully reproduces the fan structure users would manually draw using TradingView’s graphical Fib Fan tool—but does so programmatically, dynamically, and with multi-timeframe control. This eliminates manual errors, allows for responsive updating, and adds custom visual tracking via the price scale.
These values are standardized within the context of TradingView's Fib Fan tool and not made up. This script automates what the manual drawing tool achieves, with added precision and flexibility.
True Hour Open🧠 Why Count an Hour from 30th Minute to 30th Minute?
✅ Traditional Hour vs. Functional Hour
Traditional Time Logic: We’re used to viewing time in clean hourly chunks: 12:00 to 1:00, 1:00 to 2:00, and so on. This structure is fine for general purposes like clocks, meetings, and schedules.
Market Logic: Markets, however, don’t always respect these arbitrary human-made time divisions. Price action often develops momentum, structure, and transitions based on market participants' behavior, not on the clock.
🛠 What the Indicator Does
Marks the start of each hour at the 30th minute past the hour (e.g., 1:30, 2:30, 3:30).
Can highlight or segment candles that fall within a “30-to-30” hourly window.
Optionally draws background shading, lines, or boxes to visually group candles from one 30-minute mark to the next.
This helps you:
Visually align your trading with more accurate price behavior windows.
Anchor time blocks around actual market rhythm, not artificial time slots.
Backtest and strategize based on how candles behave in these alternative hourly segments.
📈 Summary
Trading is about timing. But great trading is about timing that makes sense.
By redefining the hour from 30 to 30, you’re not changing time—you’re aligning with how price moves in time.
Prev_bar_open_RSPS_IBRARYLibrary "Prev_bar_open_RSPS_IBRARY"
get_color_scheme(scheme)
Parameters:
scheme (string)
f_get_color(value, threshold, pos_col, neg_col)
Parameters:
value (float)
threshold (float)
pos_col (color)
neg_col (color)
matrix_get(A, i, j, nrows)
Parameters:
A (array)
i (int)
j (int)
nrows (int)
matrix_set(A, value, i, j, nrows)
Parameters:
A (array)
value (float)
i (int)
j (int)
nrows (int)
transpose(A, nrows, ncolumns)
Parameters:
A (array)
nrows (int)
ncolumns (int)
multiply(A, B, nrowsA, ncolumnsA, ncolumnsB)
Parameters:
A (array)
B (array)
nrowsA (int)
ncolumnsA (int)
ncolumnsB (int)
vnorm(X)
Parameters:
X (array)
qr_diag(A, nrows, ncolumns)
Parameters:
A (array)
nrows (int)
ncolumns (int)
pinv(A, nrows, ncolumns)
Parameters:
A (array)
nrows (int)
ncolumns (int)
calc_beta(beta_length, benchmark_symbol)
Parameters:
beta_length (int)
benchmark_symbol (string)
calc_alpha(alpha_length, beta_length, benchmark_symbol, risk_free_rate)
Parameters:
alpha_length (int)
beta_length (int)
benchmark_symbol (string)
risk_free_rate (float)
adftest(a, nLag, conf)
Parameters:
a (array)
nLag (int)
conf (string)
f_bartlett_weight(lag, max_lag)
Parameters:
lag (int)
max_lag (int)
f_autocovariance(x, lag)
Parameters:
x (array)
lag (int)
f_kpss_test(x, lags)
Parameters:
x (array)
lags (int)
f_get_critical_value(significance, sample_size)
Parameters:
significance (float)
sample_size (int)
get_ma(type, src, len)
Parameters:
type (string)
src (float)
len (simple int)
calculate_bb_percent(src, base_len, sd_len, sd_mult, percent_mult)
Parameters:
src (float)
base_len (int)
sd_len (int)
sd_mult (float)
percent_mult (float)
calculate_bb_market_filter(src, enable, base_len, sd_len, sd_mult, percent_mult, long_threshold, short_threshold, return_bb_percent)
Parameters:
src (float)
enable (bool)
base_len (int)
sd_len (int)
sd_mult (float)
percent_mult (float)
long_threshold (float)
short_threshold (float)
return_bb_percent (bool)
calc_TPI(src, base_len, sd_len, sd_mult, percent_mult, long_threshold, short_threshold)
Parameters:
src (float)
base_len (int)
sd_len (int)
sd_mult (float)
percent_mult (float)
long_threshold (float)
short_threshold (float)
detect_market_regime(price_src, enable_adf, adf_threshold, lookback, enable_dmi, dmi_threshold, enable_kpss, kpss_lookback, kpss_significance, enable_chop, chop_period, signal_period, enable_hilbert, smoothing_period, filter_period)
Parameters:
price_src (float)
enable_adf (bool)
adf_threshold (float)
lookback (int)
enable_dmi (bool)
dmi_threshold (float)
enable_kpss (bool)
kpss_lookback (int)
kpss_significance (float)
enable_chop (bool)
chop_period (int)
signal_period (simple int)
enable_hilbert (bool)
smoothing_period (int)
filter_period (int)
aggregate_market_regime(market_regimes, threshold)
Parameters:
market_regimes (array)
threshold (float)
f_get_asset_name(symbol)
Parameters:
symbol (string)
f_get_ranks(alphas, tpis, alpha_threshold)
Parameters:
alphas (array)
tpis (array)
alpha_threshold (float)
calc_metrics(current_equity, max_eq, returns_array, negative_returns_array, positive_returns_array, risk_free_rate)
Parameters:
current_equity (float)
max_eq (float)
returns_array (array)
negative_returns_array (array)
positive_returns_array (array)
risk_free_rate (float)
calculateMaxDrawdown(_equityCurve)
Parameters:
_equityCurve (float)
10 MA > 21 MA HighlightWhen the 10 day is above the 21 MA , this script will show a light green color on the screen
MACD Breakout SuperCandlesMACD Breakout SuperCandles
The MACD Breakout SuperCandles indicator is a candle-coloring tool that monitors trend alignment across multiple timeframes using a combination of MACD behavior and simple price structure. It visually reflects market sentiment directly on price candles, helping traders quickly recognize shifting momentum conditions.
How It Works
The script evaluates trend behavior based on:
- Multi-timeframe MACD Analysis: Uses MACD values and signal line relationships to gauge trend direction and strength.
- Price Relative to SMA Zones: Analyzes whether price is positioned above or below the 20-period high and low SMAs on each timeframe.
For each timeframe, the script assigns one of five possible trend statuses:
- SUPERBULL: Strong bullish MACD signal with price above both SMAs.
- Bullish: Bullish MACD crossover with price showing upward bias.
- Basing: MACD flattening or neutralizing near zero with no directional dominance.
- Bearish: Bearish MACD signal without confirmation of stronger trend.
- SUPERBEAR: Strong bearish MACD signal with price below both SMAs.
-Ghost Candles: Candles with basing attributes that can signal directional change or trend strength.
Signal Scoring System
The script compares conditions across four timeframes:
- TF1 (Short)
- TF2 (Medium)
- TF3 (Long)
- MACD at a fixed 10-minute resolution
Each status type is tracked independently. A colored candle is only applied when a status type (e.g., SUPERBULL) reaches the minimum match threshold, defined by the "Min Status Matches for Candle Color" setting. If no status meets the required threshold, the candle is displayed in a neutral "Ghost" color.
Customizable Visuals
The indicator offers full control over candle appearance via grouped settings:
Body Colors
- SUPERBULL Body
- Bullish Body
- Basing Body
- Bearish Body
- SUPERBEAR Body
- Ghost Candle Body (used when no match)
Border & Wick Colors
- SUPERBULL Border/Wick
- Bullish Border/Wick
- Basing Border/Wick
- Bearish Border/Wick
- SUPERBEAR Border/Wick
- Ghost Border/Wick
Colors are grouped by function and can be adjusted independently to match your chart theme or personal preferences.
Settings Overview
- TF1, TF2, TF3: Select short, medium, and long timeframes to monitor trend structure.
- Min Status Matches: Set how many timeframes must agree before a candle status is applied.
- MACD Settings: Customize MACD fast, slow, and signal lengths, and choose MA type (EMA, SMA, WMA).
This tool helps visualize how aligned various timeframe conditions are by embedding sentiment into the candles themselves. It can assist with trend identification, momentum confirmation, or visual filtering for discretionary strategies.
light_logLight Log - A Defensive Programming Library for Pine Script
Overview
The Light Log library transforms Pine Script development by introducing structured logging and defensive programming patterns typically found in enterprise languages like C#. This library addresses a fundamental challenge in Pine Script: the lack of sophisticated error handling and debugging tools that developers expect when building complex trading systems.
At its core, Light Log provides three transformative capabilities that work together to create more reliable and maintainable code. First, it wraps all native Pine Script types in error-aware containers, allowing values to carry validation state alongside their data. Second, it offers a comprehensive logging system with severity levels and conditional rendering. Third, it includes defensive programming utilities that catch errors early and make code self-documenting.
The Philosophy of Errors as Values
Traditional Pine Script error handling relies on runtime errors that halt execution, making it difficult to build resilient systems that can gracefully handle edge cases. Light Log introduces a paradigm shift by treating errors as first-class values that flow through your program alongside regular data.
When you wrap a value using Light Log's type system, you're not just storing data – you're creating a container that can carry both the value and its validation state. For example, when you call myNumber.INT() , you receive an INT object that contains both the integer value and a Log object that can describe any issues with that value. This approach, inspired by functional programming languages, allows errors to propagate through calculations without causing immediate failures.
Consider how this changes error handling in practice. Instead of a calculation failing catastrophically when it encounters invalid input, it can produce a result object that contains both the computed value (which might be na) and a detailed log explaining what went wrong. Subsequent operations can check has_error() to decide whether to proceed or handle the error condition gracefully.
The Typed Wrapper System
Light Log provides typed wrappers for every native Pine Script type: INT, FLOAT, BOOL, STRING, COLOR, LINE, LABEL, BOX, TABLE, CHART_POINT, POLYLINE, and LINEFILL. These wrappers serve multiple purposes beyond simple value storage.
Each wrapper type contains two fields: the value field v holds the actual data, while the error field e contains a Log object that tracks the value's validation state. This dual nature enables powerful programming patterns. You can perform operations on wrapped values and accumulate error information along the way, creating an audit trail of how values were processed.
The wrapper system includes convenient methods for converting between wrapped and unwrapped values. The extension methods like INT() , FLOAT() , etc., make it easy to wrap existing values, while the from_INT() , from_FLOAT() methods extract the underlying values when needed. The has_error() method provides a consistent interface for checking whether any wrapped value has encountered issues during processing.
The Log Object: Your Debugging Companion
The Log object represents the heart of Light Log's debugging capabilities. Unlike simple string concatenation for error messages, the Log object provides a structured approach to building, modifying, and rendering diagnostic information.
Each Log object carries three essential pieces of information: an error type (info, warning, error, or runtime_error), a message string that can be built incrementally, and an active flag that controls conditional rendering. This structure enables sophisticated logging patterns where you can build up detailed diagnostic information throughout your script's execution and decide later whether and how to display it.
The Log object's methods support fluent chaining, allowing you to build complex messages in a readable way. The write() and write_line() methods append text to the log, while new_line() adds formatting. The clear() method resets the log for reuse, and the rendering methods ( render_now() , render_condition() , and the general render() ) control when and how messages appear.
Defensive Programming Made Easy
Light Log's argument validation functions transform how you write defensive code. Instead of cluttering your functions with verbose validation logic, you can use concise, self-documenting calls that make your intentions clear.
The argument_error() function provides strict validation that halts execution when conditions aren't met – perfect for catching programming errors early. For less critical issues, argument_log_warning() and argument_log_error() record problems without stopping execution, while argument_log_info() provides debug visibility into your function's behavior.
These functions follow a consistent pattern: they take a condition to check, the function name, the argument name, and a descriptive message. This consistency makes error messages predictable and helpful, automatically formatting them to show exactly where problems occurred.
Building Modular, Reusable Code
Light Log encourages a modular approach to Pine Script development by providing tools that make functions more self-contained and reliable. When functions validate their inputs and return wrapped values with error information, they become true black boxes that can be safely composed into larger systems.
The void_return() function addresses Pine Script's requirement that all code paths return a value, even in error handling branches. This utility function provides a clean way to satisfy the compiler while making it clear that a particular code path should never execute.
The static log pattern, initialized with init_static_log() , enables module-wide error tracking. You can create a persistent Log object that accumulates information across multiple function calls, building a comprehensive diagnostic report that helps you understand complex behaviors in your indicators and strategies.
Real-World Applications
In practice, Light Log shines when building sophisticated trading systems. Imagine developing a complex indicator that processes multiple data streams, performs statistical calculations, and generates trading signals. With Light Log, each processing stage can validate its inputs, perform calculations, and pass along both results and diagnostic information.
For example, a moving average calculation might check that the period is positive, that sufficient data exists, and that the input series contains valid values. Instead of failing silently or throwing runtime errors, it can return a FLOAT object that contains either the calculated average or a detailed explanation of why the calculation couldn't be performed.
Strategy developers benefit even more from Light Log's capabilities. Complex entry and exit logic often involves multiple conditions that must all be satisfied. With Light Log, each condition check can contribute to a comprehensive log that explains exactly why a trade was or wasn't taken, making strategy debugging and optimization much more straightforward.
Performance Considerations
While Light Log adds a layer of abstraction over raw Pine Script values, its design minimizes performance impact. The wrapper objects are lightweight, containing only two fields. The logging operations only consume resources when actually rendered, and the conditional rendering system ensures that production code can run with logging disabled for maximum performance.
The library follows Pine Script best practices for performance, using appropriate data structures and avoiding unnecessary operations. The var keyword in init_static_log() ensures that persistent logs don't create new objects on every bar, maintaining efficiency even in real-time calculations.
Getting Started
Adopting Light Log in your Pine Script projects is straightforward. Import the library, wrap your critical values, add validation to your functions, and use Log objects to track important events. Start small by adding logging to a single function, then expand as you see the benefits of better error visibility and code organization.
Remember that Light Log is designed to grow with your needs. You can use as much or as little of its functionality as makes sense for your project. Even simple uses, like adding argument validation to key functions, can significantly improve code reliability and debugging ease.
Transform your Pine Script development experience with Light Log – because professional trading systems deserve professional development tools.
Light Log Technical Deep Dive: Advanced Patterns and Architecture
Understanding Errors as Values
The concept of "errors as values" represents a fundamental shift in how we think about error handling in Pine Script. In traditional Pine Script development, errors are events – they happen at a specific moment in time and immediately interrupt program flow. Light Log transforms errors into data – they become information that flows through your program just like any other value.
This transformation has profound implications. When errors are values, they can be stored, passed between functions, accumulated, transformed, and inspected. They become part of your program's data flow rather than exceptions to it. This approach, popularized by languages like Rust with its Result type and Haskell with its Either monad, brings functional programming's elegance to Pine Script.
Consider a practical example. Traditional Pine Script might calculate a momentum indicator like this:
momentum = close - close
If period is invalid or if there isn't enough historical data, this calculation might produce na or cause subtle bugs. With Light Log's approach:
calculate_momentum(src, period)=>
result = src.FLOAT()
if period <= 0
result.e.write("Invalid period: must be positive", true, ErrorType.error)
result.v := na
else if bar_index < period
result.e.write("Insufficient data: need " + str.tostring(period) + " bars", true, ErrorType.warning)
result.v := na
else
result.v := src - src
result.e.write("Momentum calculated successfully", false, ErrorType.info)
result
Now the function returns not just a value but a complete computational result that includes diagnostic information. Calling code can make intelligent decisions based on both the value and its associated metadata.
The Monad Pattern in Pine Script
While Pine Script lacks the type system features to implement true monads, Light Log brings monadic thinking to Pine Script development. The wrapped types (INT, FLOAT, etc.) act as computational contexts that carry both values and metadata through a series of transformations.
The key insight of monadic programming is that you can chain operations while automatically propagating context. In Light Log, this context is the error state. When you have a FLOAT that contains an error, operations on that FLOAT can check the error state and decide whether to proceed or propagate the error.
This pattern enables what functional programmers call "railway-oriented programming" – your code follows a success track when all is well but can switch to an error track when problems occur. Both tracks lead to the same destination (a result with error information), but they take different paths based on the validity of intermediate values.
Composable Error Handling
Light Log's design encourages composition – building complex functionality from simpler, well-tested components. Each component can validate its inputs, perform its calculation, and return a result with appropriate error information. Higher-level functions can then combine these results intelligently.
Consider building a complex trading signal from multiple indicators:
generate_signal(src, fast_period, slow_period, signal_period) =>
log = init_static_log(ErrorType.info)
// Calculate components with error tracking
fast_ma = calculate_ma(src, fast_period)
slow_ma = calculate_ma(src, slow_period)
// Check for errors in components
if fast_ma.has_error()
log.write_line("Fast MA error: " + fast_ma.e.message, true)
if slow_ma.has_error()
log.write_line("Slow MA error: " + slow_ma.e.message, true)
// Proceed with calculation if no errors
signal = 0.0.FLOAT()
if not (fast_ma.has_error() or slow_ma.has_error())
macd_line = fast_ma.v - slow_ma.v
signal_line = calculate_ma(macd_line, signal_period)
if signal_line.has_error()
log.write_line("Signal line error: " + signal_line.e.message, true)
signal.e := log
else
signal.v := macd_line - signal_line.v
log.write("Signal generated successfully")
else
signal.e := log
signal.v := na
signal
This composable approach makes complex calculations more reliable and easier to debug. Each component is responsible for its own validation and error reporting, and the composite function orchestrates these components while maintaining comprehensive error tracking.
The Static Log Pattern
The init_static_log() function introduces a powerful pattern for maintaining state across function calls. In Pine Script, the var keyword creates variables that persist across bars but are initialized only once. Light Log leverages this to create logging objects that can accumulate information throughout a script's execution.
This pattern is particularly valuable for debugging complex strategies where you need to understand behavior across multiple bars. You can create module-level logs that track important events:
// Module-level diagnostic log
diagnostics = init_static_log(ErrorType.info)
// Track strategy decisions across bars
check_entry_conditions() =>
diagnostics.clear() // Start fresh each bar
diagnostics.write_line("Bar " + str.tostring(bar_index) + " analysis:")
if close > sma(close, 20)
diagnostics.write_line("Price above SMA20", false)
else
diagnostics.write_line("Price below SMA20 - no entry", true, ErrorType.warning)
if volume > sma(volume, 20) * 1.5
diagnostics.write_line("Volume surge detected", false)
else
diagnostics.write_line("Normal volume", false)
// Render diagnostics based on verbosity setting
if debug_mode
diagnostics.render_now()
Advanced Validation Patterns
Light Log's argument validation functions enable sophisticated precondition checking that goes beyond simple null checks. You can implement complex validation logic while keeping your code readable:
validate_price_data(open_val, high_val, low_val, close_val) =>
argument_error(na(open_val) or na(high_val) or na(low_val) or na(close_val),
"validate_price_data", "OHLC values", "contain na values")
argument_error(high_val < low_val,
"validate_price_data", "high/low", "high is less than low")
argument_error(close_val > high_val or close_val < low_val,
"validate_price_data", "close", "is outside high/low range")
argument_log_warning(high_val == low_val,
"validate_price_data", "high/low", "are equal (no range)")
This validation function documents its requirements clearly and fails fast with helpful error messages when assumptions are violated. The mix of errors (which halt execution) and warnings (which allow continuation) provides fine-grained control over how strict your validation should be.
Performance Optimization Strategies
While Light Log adds abstraction, careful design minimizes overhead. Understanding Pine Script's execution model helps you use Light Log efficiently.
Pine Script executes once per bar, so operations that seem expensive in traditional programming might have negligible impact. However, when building real-time systems, every optimization matters. Light Log provides several patterns for efficient use:
Lazy Evaluation: Log messages are only built when they'll be rendered. Use conditional logging to avoid string concatenation in production:
if debug_mode
log.write_line("Calculated value: " + str.tostring(complex_calculation))
Selective Wrapping: Not every value needs error tracking. Wrap values at API boundaries and critical calculation points, but use raw values for simple operations:
// Wrap at boundaries
input_price = close.FLOAT()
validated_period = validate_period(input_period).INT()
// Use raw values internally
sum = 0.0
for i = 0 to validated_period.v - 1
sum += close
Error Propagation: When errors occur early, avoid expensive calculations:
process_data(input) =>
validated = validate_input(input)
if validated.has_error()
validated // Return early with error
else
// Expensive processing only if valid
perform_complex_calculation(validated)
Integration Patterns
Light Log integrates smoothly with existing Pine Script code. You can adopt it incrementally, starting with critical functions and expanding coverage as needed.
Boundary Validation: Add Light Log at the boundaries of your system – where user input enters and where final outputs are produced. This catches most errors while minimizing changes to existing code.
Progressive Enhancement: Start by adding argument validation to existing functions. Then wrap return values. Finally, add comprehensive logging. Each step improves reliability without requiring a complete rewrite.
Testing and Debugging: Use Light Log's conditional rendering to create debug modes for your scripts. Production users see clean output while developers get detailed diagnostics:
// User input for debug mode
debug = input.bool(false, "Enable debug logging")
// Conditional diagnostic output
if debug
diagnostics.render_now()
else
diagnostics.render_condition() // Only shows errors/warnings
Future-Proofing Your Code
Light Log's patterns prepare your code for Pine Script's evolution. As Pine Script adds more sophisticated features, code that uses structured error handling and defensive programming will adapt more easily than code that relies on implicit assumptions.
The type wrapper system, in particular, positions your code to take advantage of potential future features or more sophisticated type inference. By thinking in terms of wrapped values and error propagation today, you're building code that will remain maintainable and extensible tomorrow.
Light Log doesn't just make your Pine Script better today – it prepares it for the trading systems you'll need to build tomorrow.
Library "light_log"
A lightweight logging and defensive programming library for Pine Script.
Designed for modular and extensible scripts, this utility provides structured runtime validation,
conditional logging, and reusable `Log` objects for centralized error propagation.
It also introduces a typed wrapping system for all native Pine values (e.g., `INT`, `FLOAT`, `LABEL`),
allowing values to carry errors alongside data. This enables functional-style flows with built-in
validation tracking, error detection (`has_error()`), and fluent chaining.
Inspired by structured logging patterns found in systems like C#, it reduces boilerplate,
enforces argument safety, and encourages clean, maintainable code architecture.
method INT(self, error_type)
Wraps an `int` value into an `INT` struct with an optional log severity.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The raw `int` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: An `INT` object containing the value and a default Log instance.
method FLOAT(self, error_type)
Wraps a `float` value into a `FLOAT` struct with an optional log severity.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : The raw `float` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `FLOAT` object containing the value and a default Log instance.
method BOOL(self, error_type)
Wraps a `bool` value into a `BOOL` struct with an optional log severity.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
self (bool) : The raw `bool` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOOL` object containing the value and a default Log instance.
method STRING(self, error_type)
Wraps a `string` value into a `STRING` struct with an optional log severity.
Namespace types: series string, simple string, input string, const string
Parameters:
self (string) : The raw `string` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `STRING` object containing the value and a default Log instance.
method COLOR(self, error_type)
Wraps a `color` value into a `COLOR` struct with an optional log severity.
Namespace types: series color, simple color, input color, const color
Parameters:
self (color) : The raw `color` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `COLOR` object containing the value and a default Log instance.
method LINE(self, error_type)
Wraps a `line` object into a `LINE` struct with an optional log severity.
Namespace types: series line
Parameters:
self (line) : The raw `line` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINE` object containing the value and a default Log instance.
method LABEL(self, error_type)
Wraps a `label` object into a `LABEL` struct with an optional log severity.
Namespace types: series label
Parameters:
self (label) : The raw `label` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LABEL` object containing the value and a default Log instance.
method BOX(self, error_type)
Wraps a `box` object into a `BOX` struct with an optional log severity.
Namespace types: series box
Parameters:
self (box) : The raw `box` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOX` object containing the value and a default Log instance.
method TABLE(self, error_type)
Wraps a `table` object into a `TABLE` struct with an optional log severity.
Namespace types: series table
Parameters:
self (table) : The raw `table` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `TABLE` object containing the value and a default Log instance.
method CHART_POINT(self, error_type)
Wraps a `chart.point` value into a `CHART_POINT` struct with an optional log severity.
Namespace types: chart.point
Parameters:
self (chart.point) : The raw `chart.point` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `CHART_POINT` object containing the value and a default Log instance.
method POLYLINE(self, error_type)
Wraps a `polyline` object into a `POLYLINE` struct with an optional log severity.
Namespace types: series polyline, series polyline, series polyline, series polyline
Parameters:
self (polyline) : The raw `polyline` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `POLYLINE` object containing the value and a default Log instance.
method LINEFILL(self, error_type)
Wraps a `linefill` object into a `LINEFILL` struct with an optional log severity.
Namespace types: series linefill
Parameters:
self (linefill) : The raw `linefill` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINEFILL` object containing the value and a default Log instance.
method from_INT(self)
Extracts the integer value from an INT wrapper.
Namespace types: INT
Parameters:
self (INT) : The wrapped INT instance.
Returns: The underlying `int` value.
method from_FLOAT(self)
Extracts the float value from a FLOAT wrapper.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The wrapped FLOAT instance.
Returns: The underlying `float` value.
method from_BOOL(self)
Extracts the boolean value from a BOOL wrapper.
Namespace types: BOOL
Parameters:
self (BOOL) : The wrapped BOOL instance.
Returns: The underlying `bool` value.
method from_STRING(self)
Extracts the string value from a STRING wrapper.
Namespace types: STRING
Parameters:
self (STRING) : The wrapped STRING instance.
Returns: The underlying `string` value.
method from_COLOR(self)
Extracts the color value from a COLOR wrapper.
Namespace types: COLOR
Parameters:
self (COLOR) : The wrapped COLOR instance.
Returns: The underlying `color` value.
method from_LINE(self)
Extracts the line object from a LINE wrapper.
Namespace types: LINE
Parameters:
self (LINE) : The wrapped LINE instance.
Returns: The underlying `line` object.
method from_LABEL(self)
Extracts the label object from a LABEL wrapper.
Namespace types: LABEL
Parameters:
self (LABEL) : The wrapped LABEL instance.
Returns: The underlying `label` object.
method from_BOX(self)
Extracts the box object from a BOX wrapper.
Namespace types: BOX
Parameters:
self (BOX) : The wrapped BOX instance.
Returns: The underlying `box` object.
method from_TABLE(self)
Extracts the table object from a TABLE wrapper.
Namespace types: TABLE
Parameters:
self (TABLE) : The wrapped TABLE instance.
Returns: The underlying `table` object.
method from_CHART_POINT(self)
Extracts the chart.point from a CHART_POINT wrapper.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The wrapped CHART_POINT instance.
Returns: The underlying `chart.point` value.
method from_POLYLINE(self)
Extracts the polyline object from a POLYLINE wrapper.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The wrapped POLYLINE instance.
Returns: The underlying `polyline` object.
method from_LINEFILL(self)
Extracts the linefill object from a LINEFILL wrapper.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The wrapped LINEFILL instance.
Returns: The underlying `linefill` object.
method has_error(self)
Returns true if the INT wrapper has an active log entry.
Namespace types: INT
Parameters:
self (INT) : The INT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the FLOAT wrapper has an active log entry.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The FLOAT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOOL wrapper has an active log entry.
Namespace types: BOOL
Parameters:
self (BOOL) : The BOOL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the STRING wrapper has an active log entry.
Namespace types: STRING
Parameters:
self (STRING) : The STRING instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the COLOR wrapper has an active log entry.
Namespace types: COLOR
Parameters:
self (COLOR) : The COLOR instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINE wrapper has an active log entry.
Namespace types: LINE
Parameters:
self (LINE) : The LINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LABEL wrapper has an active log entry.
Namespace types: LABEL
Parameters:
self (LABEL) : The LABEL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOX wrapper has an active log entry.
Namespace types: BOX
Parameters:
self (BOX) : The BOX instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the TABLE wrapper has an active log entry.
Namespace types: TABLE
Parameters:
self (TABLE) : The TABLE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the CHART_POINT wrapper has an active log entry.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The CHART_POINT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the POLYLINE wrapper has an active log entry.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The POLYLINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINEFILL wrapper has an active log entry.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The LINEFILL instance to check.
Returns: True if an error or message is active in the log.
void_return()
Utility function used when a return is syntactically required but functionally unnecessary.
Returns: Nothing. Function never executes its body.
argument_error(condition, function, argument, message)
Throws a runtime error when a condition is met. Used for strict argument validation.
Parameters:
condition (bool) : Boolean expression that triggers the runtime error.
function (string) : Name of the calling function (for formatting).
argument (string) : Name of the problematic argument.
message (string) : Description of the error cause.
Returns: Never returns. Halts execution if the condition is true.
argument_log_info(condition, function, argument, message)
Logs an informational message when a condition is met. Used for optional debug visibility.
Parameters:
condition (bool) : Boolean expression that triggers the log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Informational message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_warning(condition, function, argument, message)
Logs a warning when a condition is met. Non-fatal but highlights potential issues.
Parameters:
condition (bool) : Boolean expression that triggers the warning.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Warning message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_error(condition, function, argument, message)
Logs an error message when a condition is met. Does not halt execution.
Parameters:
condition (bool) : Boolean expression that triggers the error log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Error message to log.
Returns: Nothing. Logs if the condition is true.
init_static_log(error_type, message, active)
Initializes a persistent (var) Log object. Ideal for global logging in scripts or modules.
Parameters:
error_type (series ErrorType) : Initial severity level (required).
message (string) : Optional starting message string. Default value of ("").
active (bool) : Whether the log should be flagged active on initialization. Default value of (false).
Returns: A static Log object with the given parameters.
method new_line(self)
Appends a newline character to the Log message. Useful for separating entries during chained writes.
Namespace types: Log
Parameters:
self (Log) : The Log instance to modify.
Returns: The updated Log object with a newline appended.
method write(self, message, flag_active, error_type)
Appends a message to a Log object without a newline. Updates severity and active state if specified.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method write_line(self, message, flag_active, error_type)
Appends a message to a Log object, prefixed with a newline for clarity.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method clear(self, flag_active, error_type)
Clears a Log object’s message and optionally reactivates it. Can also update the error type.
Namespace types: Log
Parameters:
self (Log) : The Log instance being cleared.
flag_active (bool) : Whether to activate the log after clearing. Default value of (false).
error_type (series ErrorType) : Optional new error type to assign. If not provided, the previous type is retained. Default value of (na).
Returns: The cleared Log object.
method render_condition(self, flag_active, error_type)
Conditionally renders the log if it is active. Allows overriding error type and controlling active state afterward.
Namespace types: Log
Parameters:
self (Log) : The Log instance to evaluate and render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Useful for contextual formatting just before rendering. Default value of (na).
Returns: The updated Log object.
method render_now(self, flag_active, error_type)
Immediately renders the log regardless of `active` state. Allows overriding error type and active flag.
Namespace types: Log
Parameters:
self (Log) : The Log instance to render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Allows dynamic severity adjustment at render time. Default value of (na).
Returns: The updated Log object.
render(self, condition, flag_active, error_type)
Renders the log conditionally or unconditionally. Allows full control over render behavior.
Parameters:
self (Log) : The Log instance to render.
condition (bool) : If true, renders only if the log is active. If false, always renders. Default value of (false).
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override passed to the render methods. Default value of (na).
Returns: The updated Log object.
Log
A structured object used to store and render logging messages.
Fields:
error_type (series ErrorType) : The severity level of the message (from the ErrorType enum).
message (series string) : The text of the log message.
active (series bool) : Whether the log should trigger rendering when conditionally evaluated.
INT
A wrapped integer type with attached logging for validation or tracing.
Fields:
v (series int) : The underlying `int` value.
e (Log) : Optional log object describing validation status or error context.
FLOAT
A wrapped float type with attached logging for validation or tracing.
Fields:
v (series float) : The underlying `float` value.
e (Log) : Optional log object describing validation status or error context.
BOOL
A wrapped boolean type with attached logging for validation or tracing.
Fields:
v (series bool) : The underlying `bool` value.
e (Log) : Optional log object describing validation status or error context.
STRING
A wrapped string type with attached logging for validation or tracing.
Fields:
v (series string) : The underlying `string` value.
e (Log) : Optional log object describing validation status or error context.
COLOR
A wrapped color type with attached logging for validation or tracing.
Fields:
v (series color) : The underlying `color` value.
e (Log) : Optional log object describing validation status or error context.
LINE
A wrapped line object with attached logging for validation or tracing.
Fields:
v (series line) : The underlying `line` value.
e (Log) : Optional log object describing validation status or error context.
LABEL
A wrapped label object with attached logging for validation or tracing.
Fields:
v (series label) : The underlying `label` value.
e (Log) : Optional log object describing validation status or error context.
BOX
A wrapped box object with attached logging for validation or tracing.
Fields:
v (series box) : The underlying `box` value.
e (Log) : Optional log object describing validation status or error context.
TABLE
A wrapped table object with attached logging for validation or tracing.
Fields:
v (series table) : The underlying `table` value.
e (Log) : Optional log object describing validation status or error context.
CHART_POINT
A wrapped chart point with attached logging for validation or tracing.
Fields:
v (chart.point) : The underlying `chart.point` value.
e (Log) : Optional log object describing validation status or error context.
POLYLINE
A wrapped polyline object with attached logging for validation or tracing.
Fields:
v (series polyline) : The underlying `polyline` value.
e (Log) : Optional log object describing validation status or error context.
LINEFILL
A wrapped linefill object with attached logging for validation or tracing.
Fields:
v (series linefill) : The underlying `linefill` value.
e (Log) : Optional log object describing validation status or error context.
Multifractal Forecast [ScorsoneEnterprises]Multifractal Forecast Indicator
The Multifractal Forecast is an indicator designed to model and forecast asset price movements using a multifractal framework. It uses concepts from fractal geometry and stochastic processes, specifically the Multifractal Model of Asset Returns (MMAR) and fractional Brownian motion (fBm), to generate price forecasts based on historical price data. The indicator visualizes potential future price paths as colored lines, providing traders with a probabilistic view of price trends over a specified trading time scale. Below is a detailed breakdown of the indicator’s functionality, inputs, calculations, and visualization.
Overview
Purpose: The indicator forecasts future price movements by simulating multiple price paths based on a multifractal model, which accounts for the complex, non-linear behavior of financial markets.
Key Concepts:
Multifractal Model of Asset Returns (MMAR): Models price movements as a multifractal process, capturing varying degrees of volatility and self-similarity across different time scales.
Fractional Brownian Motion (fBm): A generalization of Brownian motion that incorporates long-range dependence and self-similarity, controlled by the Hurst exponent.
Binomial Cascade: Used to model trading time, introducing heterogeneity in time scales to reflect market activity bursts.
Hurst Exponent: Measures the degree of long-term memory in the price series (persistence, randomness, or mean-reversion).
Rescaled Range (R/S) Analysis: Estimates the Hurst exponent to quantify the fractal nature of the price series.
Inputs
The indicator allows users to customize its behavior through several input parameters, each influencing the multifractal model and forecast generation:
Maximum Lag (max_lag):
Type: Integer
Default: 50
Minimum: 5
Purpose: Determines the maximum lag used in the rescaled range (R/S) analysis to calculate the Hurst exponent. A higher lag increases the sample size for Hurst estimation but may smooth out short-term dynamics.
2 to the n values in the Multifractal Model (n):
Type: Integer
Default: 4
Purpose: Defines the resolution of the multifractal model by setting the size of arrays used in calculations (N = 2^n). For example, n=4 results in N=16 data points. Larger n increases computational complexity and detail but may exceed Pine Script’s array size limits (capped at 100,000).
Multiplier for Binomial Cascade (m):
Type: Float
Default: 0.8
Purpose: Controls the asymmetry in the binomial cascade, which models trading time. The multiplier m (and its complement 2.0 - m) determines how mass is distributed across time scales. Values closer to 1 create more balanced cascades, while values further from 1 introduce more variability.
Length Scale for fBm (L):
Type: Float
Default: 100,000.0
Purpose: Scales the fractional Brownian motion output, affecting the amplitude of simulated price paths. Larger values increase the magnitude of forecasted price movements.
Cumulative Sum (cum):
Type: Integer (0 or 1)
Default: 1
Purpose: Toggles whether the fBm output is cumulatively summed (1=On, 0=Off). When enabled, the fBm series is accumulated to simulate a price path with memory, resembling a random walk with long-range dependence.
Trading Time Scale (T):
Type: Integer
Default: 5
Purpose: Defines the forecast horizon in bars (20 bars into the future). It also scales the binomial cascade’s output to align with the desired trading time frame.
Number of Simulations (num_simulations):
Type: Integer
Default: 5
Minimum: 1
Purpose: Specifies how many forecast paths are simulated and plotted. More simulations provide a broader range of possible price outcomes but increase computational load.
Core Calculations
The indicator combines several mathematical and statistical techniques to generate price forecasts. Below is a step-by-step explanation of its calculations:
Log Returns (lgr):
The indicator calculates log returns as math.log(close / close ) when both the current and previous close prices are positive. This measures the relative price change in a logarithmic scale, which is standard for financial time series analysis to stabilize variance.
Hurst Exponent Estimation (get_hurst_exponent):
Purpose: Estimates the Hurst exponent (H) to quantify the degree of long-term memory in the price series.
Method: Uses rescaled range (R/S) analysis:
For each lag from 2 to max_lag, the function calc_rescaled_range computes the rescaled range:
Calculate the mean of the log returns over the lag period.
Compute the cumulative deviation from the mean.
Find the range (max - min) of the cumulative deviation.
Divide the range by the standard deviation of the log returns to get the rescaled range.
The log of the rescaled range (log(R/S)) is regressed against the log of the lag (log(lag)) using the polyfit_slope function.
The slope of this regression is the Hurst exponent (H).
Interpretation:
H = 0.5: Random walk (no memory, like standard Brownian motion).
H > 0.5: Persistent behavior (trends tend to continue).
H < 0.5: Mean-reverting behavior (price tends to revert to the mean).
Fractional Brownian Motion (get_fbm):
Purpose: Generates a fractional Brownian motion series to model price movements with long-range dependence.
Inputs: n (array size 2^n), H (Hurst exponent), L (length scale), cum (cumulative sum toggle).
Method:
Computes covariance for fBm using the formula: 0.5 * (|i+1|^(2H) - 2 * |i|^(2H) + |i-1|^(2H)).
Uses Hosking’s method (referenced from Columbia University’s implementation) to generate fBm:
Initializes arrays for covariance (cov), intermediate calculations (phi, psi), and output.
Iteratively computes the fBm series by incorporating a random term scaled by the variance (v) and covariance structure.
Applies scaling based on L / N^H to adjust the amplitude.
Optionally applies cumulative summation if cum = 1 to produce a path with memory.
Output: An array of 2^n values representing the fBm series.
Binomial Cascade (get_binomial_cascade):
Purpose: Models trading time (theta) to account for non-uniform market activity (e.g., bursts of volatility).
Inputs: n (array size 2^n), m (multiplier), T (trading time scale).
Method:
Initializes an array of size 2^n with values of 1.0.
Iteratively applies a binomial cascade:
For each block (from 0 to n-1), splits the array into segments.
Randomly assigns a multiplier (m or 2.0 - m) to each segment, redistributing mass.
Normalizes the array by dividing by its sum and scales by T.
Checks for array size limits to prevent Pine Script errors.
Output: An array (theta) representing the trading time, which warps the fBm to reflect market activity.
Interpolation (interpolate_fbm):
Purpose: Maps the fBm series to the trading time scale to produce a forecast.
Method:
Computes the cumulative sum of theta and normalizes it to .
Interpolates the fBm series linearly based on the normalized trading time.
Ensures the output aligns with the trading time scale (T).
Output: An array of interpolated fBm values representing log returns over the forecast horizon.
Price Path Generation:
For each simulation (up to num_simulations):
Generates an fBm series using get_fbm.
Interpolates it with the trading time (theta) using interpolate_fbm.
Converts log returns to price levels:
Starts with the current close price.
For each step i in the forecast horizon (T), computes the price as prev_price * exp(log_return).
Output: An array of price levels for each simulation.
Visualization:
Trigger: Updates every T bars when the bar state is confirmed (barstate.isconfirmed).
Process:
Clears previous lines from line_array.
For each simulation, plots a line from the current bar’s close price to the forecasted price at bar_index + T.
Colors the line using a gradient (color.from_gradient) based on the final forecasted price relative to the minimum and maximum forecasted prices across all simulations (red for lower prices, teal for higher prices).
Output: Multiple colored lines on the chart, each representing a possible price path over the next T bars.
How It Works on the Chart
Initialization: On each bar, the indicator calculates the Hurst exponent (H) using historical log returns and prepares the trading time (theta) using the binomial cascade.
Forecast Generation: Every T bars, it generates num_simulations price paths:
Each path starts at the current close price.
Uses fBm to model log returns, warped by the trading time.
Converts log returns to price levels.
Plotting: Draws lines from the current bar to the forecasted price T bars ahead, with colors indicating relative price levels.
Dynamic Updates: The forecast updates every T bars, replacing old lines with new ones based on the latest price data and calculations.
Key Features
Multifractal Modeling: Captures complex market dynamics by combining fBm (long-range dependence) with a binomial cascade (non-uniform time).
Customizable Parameters: Allows users to adjust the forecast horizon, model resolution, scaling, and number of simulations.
Probabilistic Forecast: Multiple simulations provide a range of possible price outcomes, helping traders assess uncertainty.
Visual Clarity: Gradient-colored lines make it easy to distinguish bullish (teal) and bearish (red) forecasts.
Potential Use Cases
Trend Analysis: Identify potential price trends or reversals based on the direction and spread of forecast lines.
Risk Assessment: Evaluate the range of possible price outcomes to gauge market uncertainty.
Volatility Analysis: The Hurst exponent and binomial cascade provide insights into market persistence and volatility clustering.
Limitations
Computational Intensity: Large values of n or num_simulations may slow down execution or hit Pine Script’s array size limits.
Randomness: The binomial cascade and fBm rely on random terms (math.random), which may lead to variability between runs.
Assumptions: The model assumes log-normal price movements and fractal behavior, which may not always hold in extreme market conditions.
Adjusting Inputs:
Set max_lag based on the desired depth of historical analysis.
Adjust n for model resolution (start with 4–6 to avoid performance issues).
Tune m to control trading time variability (0.5–1.5 is typical).
Set L to scale the forecast amplitude (experiment with values like 10,000–1,000,000).
Choose T based on your trading horizon (20 for short-term, 50 for longer-term for example).
Select num_simulations for the number of forecast paths (5–10 is reasonable for visualization).
Interpret Output:
Teal lines suggest bullish scenarios, red lines suggest bearish scenarios.
A wide spread of lines indicates high uncertainty; convergence suggests a stronger trend.
Monitor Updates: Forecasts update every T bars, so check the chart periodically for new projections.
Chart Examples
This is a daily AMEX:SPY chart with default settings. We see the simulations being done every T bars and they provide a range for us to analyze with a few simulations still in the range.
On this intraday PEPPERSTONE:COCOA chart I modified the Length Scale for fBm, L, parameter to be 1000 from 100000. Adjusting the parameter as you switch between timeframes can give you more contextual simulations.
On BITSTAMP:ETHUSD I modified the L to be 1000000 to have a more contextual set of simulations with crypto's volatile nature.
With L at 100000 we see the range for NASDAQ:TLT is correctly simulated. The recent pop stays within the bounds of the highest simulation. Note this is a cherry picked example to show the power and potential of these simulations.
Technical Notes
Error Handling: The script includes checks for array size limits and division by zero (math.abs(denominator) > 1e-10, v := math.max(v, 1e-10)).
External Reference: The fBm implementation is based on Hosking’s method (www.columbia.edu), ensuring a robust algorithm.
Conclusion
The Multifractal Forecast is a powerful tool for traders seeking to model complex market dynamics using a multifractal framework. By combining fBm, binomial cascades, and Hurst exponent analysis, it generates probabilistic price forecasts that account for long-range dependence and non-uniform market activity. Its customizable inputs and clear visualizations make it suitable for both technical analysis and strategy development, though users should be mindful of its computational demands and parameter sensitivity. For optimal use, experiment with input settings and validate forecasts against other technical indicators or market conditions.
Eliora Phase 4.2.2 – Precision Bloom Mode | DAX 5minPhase shifts and market cohesion using math. Sure! Let’s break down the **simple trading bot concept** for **TradingView** step by step, focusing on the logic, purpose, and key elements of the strategy. This bot uses a **trend-following strategy** combined with **risk management** to automate trades based on moving averages and the RSI indicator.
---
### **Trading Bot Concept:**
#### **Objective:**
The primary objective of this bot is to **identify trends** and **execute buy and sell orders** based on those trends, while also ensuring **risk management** through stop-loss and take-profit levels.
The bot uses two **core indicators**:
* **Exponential Moving Averages (EMAs)**: To identify the trend direction.
* **Relative Strength Index (RSI)**: To filter out overbought and oversold conditions, helping avoid entering trades during extreme market conditions.
---
### **Key Components:**
#### 1. **Exponential Moving Averages (EMA)**
* **50-period EMA** (Short-Term Trend): Tracks the price's movement in the recent past, offering more weight to recent prices. This helps the bot react quicker to short-term market shifts.
* **200-period EMA** (Long-Term Trend): Represents the broader market trend, helping the bot assess the overall market direction.
**Buy Signal**:
* A buy signal is triggered when the **50-period EMA crosses above** the **200-period EMA** (a **bullish crossover**), suggesting that the market is entering an uptrend.
**Sell Signal**:
* A sell signal is triggered when the **50-period EMA crosses below** the **200-period EMA** (a **bearish crossover**), indicating that the market might be reversing into a downtrend.
#### 2. **Relative Strength Index (RSI)**
* **RSI** is a momentum oscillator that measures the speed and change of price movements, indicating whether an asset is overbought or oversold.
* **Buy Condition**: The bot only takes buy trades if the **RSI is above 30**. This ensures that the market isn't in an **oversold** condition, which could indicate a potential reversal.
* **Sell Condition**: The bot will only take sell actions if the **RSI is below 70**, avoiding trades during **overbought** conditions where prices might be excessively high.
---
### **How the Bot Works:**
1. **Buy Signal Conditions:**
* The **50-period EMA** crosses **above** the **200-period EMA** (bullish crossover), indicating the potential start of an uptrend.
* The **RSI is above 30**, ensuring that the market isn’t oversold and a reversal isn’t imminent.
* If both of these conditions are true, the bot will **enter a long (buy) position**.
2. **Sell Signal Conditions:**
* The **50-period EMA** crosses **below** the **200-period EMA** (bearish crossover), signaling that the market might be transitioning into a downtrend.
* The **RSI is below 70**, meaning the market isn’t in an overbought state and the sell-off is not due to excessive bullish momentum.
* If both of these conditions are met, the bot will **exit** any long position (i.e., sell).
---
### **Risk Management:**
To protect against significant losses, the bot includes two essential features of **risk management**:
1. **Stop-Loss**:
* The bot will automatically **exit the trade if the price moves against it by 2%** (or another user-defined percentage). This minimizes potential losses in case the market moves unfavorably after entry.
2. **Take-Profit**:
* The bot will automatically **exit the trade once it reaches a profit of 5%** (or another user-defined percentage). This locks in profits if the market moves favorably.
---
### **Script Breakdown:**
Here’s the **key flow** of the Pine Script:
1. **Define Parameters**: The script begins by defining input values for the **EMA periods** and **RSI length**. It also defines the **RSI overbought (70)** and **RSI oversold (30)** levels.
2. **Calculate the EMAs and RSI**:
* The 50-period and 200-period **EMAs** are calculated using the `ta.ema()` function.
* The **RSI** is calculated using `ta.rsi()`, and it helps determine if the asset is overbought or oversold.
3. **Trading Conditions**:
* A buy signal is generated when the **short-term EMA crosses above** the **long-term EMA** and the RSI is **above 30**.
* A sell signal is triggered when the **short-term EMA crosses below** the **long-term EMA** and the RSI is **below 70**.
4. **Strategy Execution**:
* When the buy condition is met, the bot **enters a long position** using `strategy.entry()`.
* When the sell condition is met, the bot **closes the position** using `strategy.close()`.
5. **Risk Management**:
* The `strategy.exit()` function is used to set **stop-loss** and **take-profit** values. If the price moves **2% against** the trade, the bot will exit. If it moves **5% in favor**, it will lock in profits.
---
### **Visual Elements**:
1. **EMAs**:
* The **50-period EMA** is plotted in **green**.
* The **200-period EMA** is plotted in **red**.
2. **RSI**:
* The **RSI line** is plotted in **blue** on a separate pane below the main chart.
* Horizontal lines mark the **overbought** (70) and **oversold** (30) levels, helping visualize potential reversal zones.
3. **Buy and Sell Signals**:
* When the bot triggers a buy, a **green arrow** appears on the chart.
* When it triggers a sell, a **red arrow** appears on the chart.
---
### **How to Use the Bot on TradingView:**
1. **Go to TradingView** and open a chart of the asset you want to trade.
2. **Click on the "Pine Editor"** tab at the bottom.
3. **Paste the script** provided into the editor.
4. **Click "Add to Chart"** to see the strategy in action.
5. The bot will begin executing trades based on the logic described and display buy/sell signals directly on the chart.
---
### **Advantages of This Strategy**:
* **Trend-Following**: This bot is based on the classic moving average crossover strategy, which is effective in trending markets.
* **Simple and Clear**: The logic is easy to follow and understand, making it beginner-friendly.
* **Built-in Risk Management**: The stop-loss and take-profit functionality ensures that the bot limits potential losses and locks in profits automatically.
* **Customizable**: You can easily tweak the parameters (e.g., EMA periods, RSI levels, stop-loss, take-profit) to fit different timeframes or market conditions.
---
### **Limitations**:
* **Sideways Markets**: The bot might struggle in flat or sideways markets because moving average crossovers can produce false signals.
* **No Advanced Features**: It doesn’t incorporate more advanced strategies like **momentum indicators**, **news sentiment**, or **machine learning models** for decision-making.
---
### **In Conclusion:**
This is a **basic but effective trend-following trading bot** that you can deploy on TradingView with minimal effort. It provides a great foundation for traders who want to automate a simple strategy with **risk management**, while offering plenty of room for customization and improvement.
Let me know if you want to explore more complex features or strategies, or if you need help tweaking the bot for specific assets or markets!
4-EMA Signals 3.04-EMA Signals: Multi-Timeframe Trading Indicator
Overview
4-EMA Signals 3.0 is a trading indicator that combines exponential moving averages, volume analysis, and multi-timeframe trend assessment to provide high-probability entry and exit signals. Designed for both day traders and swing traders, it offers a comprehensive approach to market analysis.
Key Features:
EMA System
-- our Configurable EMAs: Fast (7), Medium-Short (25), Medium-Long (70), and Slow (200)
-- Preset Configurations: Choose between Custom, Conservative (9/20/50/200), Aggressive (5/10/20/50), or Fibonacci (8/21/55/144)
-- Visual Clarity: Color-coded EMAs for quick trend identification
-- Non-Repainting Signals: All signals use confirmed bars only, ensuring reliability for back-testing
-- Signal Generation
Six Crossover Combinations: Detects all possible crossovers between the four EMAs
-- Buy/Sell Visualization: Green triangles (buy) and red triangles (sell) clearly mark entry points
-- Volume Confirmation: Optional volume filter with adjustable sensitivity (0.1-3.0)
-- Alert System: Customizable alerts for all signal types
Multi-Timeframe Analysis
-- Three Timeframe Analysis: 5-minute, 1-hour, and 4-hour trend detection
-- Higher Timeframe Bias: Overall market direction assessment based on EMA alignment
--Visual Table Display: Color-coded table showing trend status across all timeframes
Trading Session Tracking
-- Major Sessions: London (08:00-17:00), New York (13:00-22:00), Asia (22:00-08:00), Sydney (22:00-07:00)
-- Session Indicators: Background colors distinguish active trading sessions
-- GMT+1 Timezone: Optimized for European trading schedule
Volume Analytics
-- Volume Filter: Compare current volume against 20-period SMA with adjustable sensitivity
-- Per Candle Volume: Real-time volume data for the current candle
-- Daily Volume: Track total daily volume in thousands
Trading Applications
-- Trend Following: Use EMA alignment to identify strong directional moves
-- Scalping: Fast EMA crosses provide quick entry and exit points
-- Swing Trading: Higher timeframe analysis helps identify broader market bias
-- Session Trading: Optimize entries based on specific market sessions
-- Risk Management: Volume filter helps avoid low-liquidity, high-risk trades
Technical Details
-- Pine Script Version: v5
-- Chart Compatibility: Works on all timeframes and markets
-- Performance Optimized: Efficient code with max_labels_count limit
-- Non-Repainting: Reliable signals that don't change after formation
The 4-EMA Signals indicator combines the simplicity of moving average crossovers with the depth of multi-timeframe analysis and volume confirmation, creating a powerful yet easy-to-use trading tool for traders of all experience levels.
Math by Thomas - SMC OB + FVG📄 Description
This script is designed for traders following the Smart Money Concepts (SMC) methodology. It automatically detects:
✅ Bullish and Bearish Order Blocks (OBs) based on structural breakouts, displacement, and volume conditions.
✅ Fair Value Gaps (FVGs) using a 3-candle price imbalance model.
🔄 Both OBs and FVGs clean up dynamically when invalidated by price action.
Built with institutional logic, this tool helps identify areas of interest for potential reversals, liquidity grabs, or mitigation plays.
⚙️ How It Works
🔷 Order Blocks (OB)
A Bullish OB is marked after a Break of Structure (BOS) to the upside.
A Bearish OB is marked after BOS to the downside.
Filters like displacement candle and volume spike can be toggled in settings.
Boxes are drawn from the opposing candle in the move, and will disappear once broken or expired.
🟥 Fair Value Gaps (FVG)
FVGs are detected when the middle candle leaves a price imbalance between the first and third candle.
Zones are marked with transparent boxes.
Labels (FVG) appear only once every 20 bars to reduce clutter.
Gaps are removed only after a full candle closes through the zone (conservative logic).
🛠️ User Settings
Choose volume multiplier and ATR period for OB displacement logic.
Set box extension, label transparency, and cleanup behavior.
Full control over colors and midline display.
📈 How to Use
Apply the indicator to any chart (works best on indices, forex, crypto).
Use OBs as points of interest for potential reaction zones or mitigation setups.
Use FVGs to identify imbalances that may attract price.
Watch for confluence between OBs and FVGs for high-probability entries.
📚 Best Practice
Use on 15m–1h timeframe for clean structure.
Align with higher TF bias for direction.
Combine with liquidity sweeps, EQH/EQL, or breaker blocks for refinement.
Futures Margin Lookup TableThis script applies a table to your chart, which provides the intraday and overnight margin requirements of the currently selected symbol.
In this indicator the user must provide the broker data in the form of specifically formatted text blocks. The data for which should be found on the broker website under futures margin requirements.
The purpose for it's creation is due to the non-standard way each individual broker may price their margins and lack of information within TradingView when connected to some (maybe all) brokers, including during paper trading, as the flat percentage rule is not accurate.
An example of information could look like this
MES;Micro S&P;$50;$2406
ES;E-Mini S&P;$500;$24,053
GC;Gold;$500;$16500
NQ;E-Mini Nasdaq;$1,000;$34,810
FDAX;Dax Index;€2,000;€44,311
Each symbol begins a new line, and the values on that line are separated by semicolons (;)
Each line consists of the following...
SYMBOL : Search string used to match to the beginning of the current chart symbol.
NAME: Human readable name
INTRA: Intraday trading margin requirement per contract
OVERNIGHT: Overnight trading margin requirement per contract
The script simply finds a matching line within your provided information using the current chart symbol.
So for example the continuous chart for
NQ1!
would match to the user specified line starting with NQ... as would the individual contract dates such as NQM2025, NQK2025, etc.
NOTES:
There is a possibility that symbols with similar starting characters could match. If this is the case put the longer symbol higher in the list.
There is also a line / character limit to the text input fields within pinescript. Ensure the text you enter / paste into them is not truncated. If so there are 3 input fields for just this purpose. Find the last complete line and continue the remaining symbol lines on the subsequent inputs.
VWAP ORB StrategyPlots the 15-min Opening Range for NY (9:30–9:45 AM ET) and London (3:00–3:15 AM ET), with breakout levels and range-based targets. Includes VWAP and EMA for trend confirmation.
Ichimoku Ervin Ichimoku Ervin Indicator Version 2.47
This advanced Ichimoku indicator, version 2.47, is presented with a special design and settings that help improve the accuracy of technical analysis. The most important features of this version are:
Dual Ichimoku Plotting with Different Periods:
This indicator simultaneously draws two Ichimoku sets:
First set with a period of 26 (26-period cloud)
Second set with a period of 0 (0 cloud)
The 0 cloud feature allows the analyst to shift the position of this cloud forward or backward at will (e.g., 9 or 18 periods ahead or behind the current candle), depending on their trading strategy, to identify more sensitive areas of the chart for analyzing the market’s future or reviewing its past. This capability provides the user with a deeper understanding of trend behavior and its strength.
Period Settings:
The main periods of this indicator are defined as:
103, 216, 63, and 540
Additionally, the value 540 performs with higher sensitivity specifically on the 1-hour (H1) time frame and lower, providing the analyst with faster and more accurate signals.
Time Cycles:
This indicator includes three key time cycles: 9, 26, and 52 periods, each representing different phases of the market and potential points for trend reversal.
accurately identify both short-term and long-term trends Two Exponential Moving Averages (EMA):
It uses two EMAs with periods of 50 and 1440, where 1440 operates more sensitively on the 1-hour time frame and lower, helping the analyst to.
Order Block (OB):
One of the key features of this version is the display of Order Block (OB) zones. These are areas on the chart where high trading volumes and major decision-making by large traders (such as banks and financial institutions) have occurred.
Accurate identification of these zones helps traders choose more optimal entry and exit points and significantly reduce their trading risk.
This indicator has been released on the occasion of Eid al-Ghadir Khumm, and version 2.47 comes with special features. A professional tool for more precise market analysis. Happy Eid! 🌸
Hme Rolling VolumeThis indicator allows you to display volume in a continious rolling time frame.
Instead of starting at zero for each new bar, it displays, for example, the cumulative volume of the last 120 seconds on a 2-minute chart.
This helps you track volume trends even more quickly and interpret their behavior without the break between bars.
Fibonacci Entry Bands [AlgoAlpha]OVERVIEW
This script plots Fibonacci Entry Bands, a trend-following and mean-reversion hybrid system built around dynamic volatility-adjusted bands scaled using key Fibonacci levels. It calculates a smoothed basis line and overlays multiple bands at fixed Fibonacci multipliers of either ATR or standard deviation. Depending on the trend direction, specific upper or lower bands become active, offering a clear framework for entry timing, trend identification, and profit-taking zones.
CONCEPTS
The core idea is to use Fibonacci levels—0.618, 1.0, 1.618, and 2.618—as multipliers on a volatility measure to form layered price bands around a trend-following moving average. Trends are defined by whether the basis is rising or falling. The trend determines which side of the bands is emphasized: upper bands for downtrends, lower bands for uptrends. This approach captures both directional bias and extreme price extensions. Take-profit logic is built in via crossovers relative to the outermost bands, scaled by user-selected aggressiveness.
FEATURES
Basis Line – A double EMA smoothing of the source defines trend direction and acts as the central mean.
Volatility Bands – Four levels per side (based on selected ATR or stdev) mark the Fibonacci bands. These become visible only when trend direction matches the side (e.g., only lower bands plot in an uptrend).
Bar Coloring – Bars are shaded with adjustable transparency depending on distance from the basis, with color intensity helping gauge overextension.
Entry Arrows – A trend shift triggers either a long or short signal, with a marker at the outermost band with ▲/▼ signs.
Take-Profit Crosses – If price rejects near the outer band (based on aggressiveness setting), a cross appears marking potential profit-taking.
Bounce Signals – Minor pullbacks that respect the basis line are marked with triangle arrows, hinting at continuation setups.
Customization – Users can toggle bar coloring, signal markers, and select between ATR/stdev as well as take-profit aggressiveness.
Alerts – All major signals, including entries, take-profits, and bounces, are available as alert conditions.
USAGE
To use this tool, load it on your chart, adjust the inputs for volatility method and aggressiveness, and wait for entries to form on trend changes. Use TP crosses and bounce arrows as potential exit or scale-in signals.
Magnificent 7 OscillatorThe Magnificent 7 Oscillator is a sophisticated momentum-based technical indicator designed to analyze the collective performance of the seven largest technology companies in the U.S. stock market (Apple, Microsoft, Alphabet, Amazon, NVIDIA, Tesla, and Meta). This indicator incorporates established momentum factor research and provides three distinct analytical modes: absolute momentum tracking, equal-weighted market comparison, and relative performance analysis. The tool integrates five different oscillator methodologies and includes advanced breadth analysis capabilities.
Theoretical Foundation
Momentum Factor Research
The indicator's foundation rests on seminal momentum research in financial markets. Jegadeesh and Titman (1993) demonstrated that stocks with strong price performance over 3-12 month periods tend to continue outperforming in subsequent periods¹. This momentum effect was later incorporated into formal factor models by Carhart (1997), who extended the Fama-French three-factor model to include a momentum factor (UMD - Up Minus Down)².
The momentum calculation methodology follows the academic standard:
Momentum(t) = / P(t-n) × 100
Where P(t) is the current price and n is the lookback period.
The focus on the "Magnificent 7" stocks reflects the increasing market concentration observed in recent years. Fama and French (2015) noted that a small number of large-cap stocks can drive significant market movements due to their substantial index weights³. The combined market capitalization of these seven companies often exceeds 25% of the total S&P 500, making their collective momentum a critical market indicator.
Indicator Architecture
Core Components
1. Data Collection and Processing
The indicator employs robust data collection with error handling for missing or invalid security data. Each stock's momentum is calculated independently using the specified lookback period (default: 14 periods).
2. Composite Oscillator Calculation
Following Fama-French factor construction methodology, the indicator offers two weighting schemes:
- Equal Weight: Each active stock receives identical weighting (1/n)
- Market Cap Weight: Reserved for future enhancement
3. Oscillator Transformation Functions
The indicator provides five distinct oscillator types, each with established technical analysis foundations:
a) Momentum Oscillator (Default)
- Pure rate-of-change calculation
- Centered around zero
- Direct implementation of Jegadeesh & Titman methodology
b) RSI (Relative Strength Index)
- Wilder's (1978) relative strength methodology
- Transformed to center around zero for consistency
- Scale: -50 to +50
c) Stochastic Oscillator
- George Lane's %K methodology
- Measures current position within recent range
- Transformed to center around zero
d) Williams %R
- Larry Williams' range-based oscillator
- Inverse stochastic calculation
- Adjusted for zero-centered display
e) CCI (Commodity Channel Index)
- Donald Lambert's mean reversion indicator
- Measures deviation from moving average
- Scaled for optimal visualization
Operational Modes
Mode 1: Magnificent 7 Analysis
Tracks the collective momentum of the seven constituent stocks. This mode is optimal for:
- Technology sector analysis
- Growth stock momentum assessment
- Large-cap performance tracking
Mode 2: S&P 500 Equal Weight Comparison
Analyzes momentum using an equal-weighted S&P 500 reference (typically RSP ETF). This mode provides:
- Broader market momentum context
- Size-neutral market analysis
- Comparison baseline for relative performance
Mode 3: Relative Performance Analysis
Calculates the momentum differential between Magnificent 7 and S&P 500 Equal Weight. This mode enables:
- Sector rotation analysis
- Style factor assessment (Growth vs. Value)
- Relative strength identification
Formula: Relative Performance = MAG7_Momentum - SP500EW_Momentum
Signal Generation and Thresholds
Signal Classification
The indicator generates three signal states:
- Bullish: Oscillator > Upper Threshold (default: +2.0%)
- Bearish: Oscillator < Lower Threshold (default: -2.0%)
- Neutral: Oscillator between thresholds
Relative Performance Signals
In relative performance mode, specialized thresholds apply:
- Outperformance: Relative momentum > +1.0%
- Underperformance: Relative momentum < -1.0%
Alert System
Comprehensive alert conditions include:
- Threshold crossovers (bullish/bearish signals)
- Zero-line crosses (momentum direction changes)
- Relative performance shifts
- Breadth Analysis Component
The indicator incorporates market breadth analysis, calculating the percentage of constituent stocks with positive momentum. This feature provides insights into:
- Strong Breadth (>60%): Broad-based momentum
- Weak Breadth (<40%): Narrow momentum leadership
- Mixed Breadth (40-60%): Neutral momentum distribution
Visual Design and User Interface
Theme-Adaptive Display
The indicator automatically adjusts color schemes for dark and light chart themes, ensuring optimal visibility across different user preferences.
Professional Data Table
A comprehensive data table displays:
- Current oscillator value and percentage
- Active mode and oscillator type
- Signal status and strength
- Component breakdowns (in relative performance mode)
- Breadth percentage
- Active threshold levels
Custom Color Options
Users can override default colors with custom selections for:
- Neutral conditions (default: Material Blue)
- Bullish signals (default: Material Green)
- Bearish signals (default: Material Red)
Practical Applications
Portfolio Management
- Sector Allocation: Use relative performance mode to time technology sector exposure
- Risk Management: Monitor breadth deterioration as early warning signal
- Entry/Exit Timing: Utilize threshold crossovers for position sizing decisions
Market Analysis
- Trend Identification: Zero-line crosses indicate momentum regime changes
- Divergence Analysis: Compare MAG7 performance against broader market
- Volatility Assessment: Oscillator range and frequency provide volatility insights
Strategy Development
- Factor Timing: Implement growth factor timing strategies
- Momentum Strategies: Develop systematic momentum-based approaches
- Risk Parity: Use breadth metrics for risk-adjusted portfolio construction
Configuration Guidelines
Parameter Selection
- Momentum Period (5-100): Shorter periods (5-20) for tactical analysis, longer periods (50-100) for strategic assessment
- Smoothing Period (1-50): Higher values reduce noise but increase lag
- Thresholds: Adjust based on historical volatility and strategy requirements
Timeframe Considerations
- Daily Charts: Optimal for swing trading and medium-term analysis
- Weekly Charts: Suitable for long-term trend analysis
- Intraday Charts: Useful for short-term tactical decisions
Limitations and Considerations
Market Concentration Risk
The indicator's focus on seven stocks creates concentration risk. During periods of significant rotation away from large-cap technology stocks, the indicator may not represent broader market conditions.
Momentum Persistence
While momentum effects are well-documented, they are not permanent. Jegadeesh and Titman (1993) noted momentum reversal effects over longer time horizons (2-5 years).
Correlation Dynamics
During market stress, correlations among the constituent stocks may increase, reducing the diversification benefits and potentially amplifying signal intensity.
Performance Metrics and Backtesting
The indicator includes hidden plots for comprehensive backtesting:
- Individual stock momentum values
- Composite breadth percentage
- S&P 500 Equal Weight momentum
- Relative performance calculations
These metrics enable quantitative strategy development and historical performance analysis.
References
¹Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. Journal of Finance, 48(1), 65-91.
Carhart, M. M. (1997). On persistence in mutual fund performance. Journal of Finance, 52(1), 57-82.
Fama, E. F., & French, K. R. (2015). A five-factor asset pricing model. Journal of Financial Economics, 116(1), 1-22.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.
SPX Weekly Expected Moves# SPX Weekly Expected Moves Indicator
A professional Pine Script indicator for TradingView that displays weekly expected move levels for SPX based on real options data, with integrated Fibonacci retracement analysis and intelligent alerting system.
## Overview
This indicator helps options and equity traders visualize weekly expected move ranges for the S&P 500 Index (SPX) by plotting historical and current week expected move boundaries derived from weekly options pricing. Unlike theoretical volatility calculations, this indicator uses actual market-based expected move data that you provide from options platforms.
## Key Features
### 📈 **Expected Move Visualization**
- **Historical Lines**: Display past weeks' expected moves with configurable history (10, 26, or 52 weeks)
- **Current Week Focus**: Highlighted current week with extended lines to present time
- **Friday Close Reference**: Orange baseline showing the previous Friday's close price
- **Timeframe Independent**: Works consistently across all chart timeframes (1m to 1D)
### 🎯 **Fibonacci Integration**
- **Five Fibonacci Levels**: 23.6%, 38.2%, 50%, 61.8%, 76.4% between Friday close and expected move boundaries
- **Color-Coded Levels**:
- Red: 23.6% & 76.4% (outer levels)
- Blue: 38.2% & 61.8% (golden ratio levels)
- Black: 50% (midpoint - most critical level)
- **Current Week Only**: Fibonacci levels shown only for active trading week to reduce clutter
### 📊 **Real-Time Information Table**
- **Current SPX Price**: Live market price
- **Expected Move**: ±EM value for current week
- **Previous Close**: Friday close price (baseline for calculations)
- **100% EM Levels**: Exact upper and lower boundary prices
- **Current Location**: Real-time position within the EM structure (e.g., "Above 38.2% Fib (upper zone)")
### 🚨 **Intelligent Alert System**
- **Zone-Aware Alerts**: Separate alerts for upper and lower zones
- **Key Level Breaches**: Alerts for 23.6% and 76.4% Fibonacci level crossings
- **Bar Close Based**: Alerts trigger on confirmed bar closes, not tick-by-tick
- **Customizable**: Enable/disable alerts through settings
## How It Works
### Data Input Method
The indicator uses a **manual data entry approach** where you input actual expected move values obtained from options platforms:
```pinescript
// Add entries using the options expiration Friday date
map.put(expected_moves, 20250613, 91.244) // Week ending June 13, 2025
map.put(expected_moves, 20250620, 95.150) // Week ending June 20, 2025
```
### Weekly Structure
- **Monday 9:30 AM ET**: Week begins
- **Friday 4:00 PM ET**: Week ends
- **Lines Extend**: From Monday open to Friday close (historical) or current time + 5 bars (current week)
- **Timezone Handling**: Uses "America/New_York" for proper DST handling
### Calculation Logic
1. **Base Price**: Previous Friday's SPX close price
2. **Expected Move**: Market-derived ±EM value from weekly options
3. **Upper Boundary**: Friday Close + Expected Move
4. **Lower Boundary**: Friday Close - Expected Move
5. **Fibonacci Levels**: Proportional levels between Friday close and EM boundaries
## Setup Instructions
### 1. Data Collection
Obtain weekly expected move values from options platforms such as:
- **ThinkOrSwim**: Use thinkBack feature to look up weekly expected moves
- **Tastyworks**: Check weekly options expected move data
- **CBOE**: Reference SPX weekly options data
- **Manual Calculation**: (ATM Call Premium + ATM Put Premium) × 0.85
### 2. Data Entry
After each Friday close, update the indicator with the next week's expected move:
```pinescript
// Example: On Friday June 7, 2025, add data for week ending June 13
map.put(expected_moves, 20250613, 91.244) // Actual EM value from your platform
```
### 3. Configuration
Customize the indicator through the settings panel:
#### Visual Settings
- **Show Current Week EM**: Toggle current week display
- **Show Past Weeks**: Toggle historical weeks display
- **Max Weeks History**: Choose 10, 26, or 52 weeks of history
- **Show Fibonacci Levels**: Toggle Fibonacci retracement levels
- **Label Controls**: Customize which labels to display
#### Colors
- **Current Week EM**: Default yellow for active week
- **Past Weeks EM**: Default gray for historical weeks
- **Friday Close**: Default orange for baseline
- **Fibonacci Levels**: Customizable colors for each level type
#### Alerts
- **Enable EM Breach Alerts**: Master toggle for all alerts
- **Specific Alerts**: Four alert types for Fibonacci level breaches
## Trading Applications
### Options Trading
- **Straddle/Strangle Positioning**: Visualize breakeven levels for neutral strategies
- **Directional Plays**: Assess probability of reaching target levels
- **Earnings Plays**: Compare actual vs. expected move outcomes
### Equity Trading
- **Support/Resistance**: Use EM boundaries and Fibonacci levels as key levels
- **Breakout Trading**: Monitor for moves beyond expected ranges
- **Mean Reversion**: Look for reversals at extreme Fibonacci levels
### Risk Management
- **Position Sizing**: Gauge likely price ranges for the week
- **Stop Placement**: Use Fibonacci levels for logical stop locations
- **Profit Targets**: Set targets based on EM structure probabilities
## Technical Implementation
### Performance Features
- **Memory Managed**: Configurable history limits prevent memory issues
- **Timeframe Independent**: Uses timestamp-based calculations for consistency
- **Object Management**: Automatic cleanup of drawing objects prevents duplicates
- **Error Handling**: Robust bounds checking and NA value handling
### Pine Script Best Practices
- **v6 Compliance**: Uses latest Pine Script version features
- **User Defined Types**: Structured data management with WeeklyEM type
- **Efficient Drawing**: Smart line/label creation and deletion
- **Professional Standards**: Clean code organization and comprehensive documentation
## Customization Guide
### Adding New Weeks
```pinescript
// Add after market close each Friday
map.put(expected_moves, YYYYMMDD, EM_VALUE)
```
### Color Schemes
Customize colors for different trading styles:
- **Dark Theme**: Use bright colors for visibility
- **Light Theme**: Use contrasting dark colors
- **Minimalist**: Use single color with transparency
### Label Management
Control label density:
- **Show Current Week Labels Only**: Reduce clutter for active trading
- **Show All Labels**: Full information for analysis
- **Selective Display**: Choose specific label types
## Troubleshooting
### Common Issues
1. **No Lines Appearing**: Check that expected move data is entered for current/recent weeks
2. **Wrong Time Display**: Ensure "America/New_York" timezone is properly handled
3. **Duplicate Lines**: Restart indicator if drawing objects appear duplicated
4. **Missing Fibonacci Levels**: Verify "Show Fibonacci Levels" is enabled
### Data Validation
- **Expected Move Format**: Use positive numbers (e.g., 91.244, not ±91.244)
- **Date Format**: Use YYYYMMDD format (e.g., 20250613)
- **Reasonable Values**: Verify EM values are realistic (typically 50-200 for SPX)
## Version History
### Current Version
- **Pine Script v6**: Latest version compatibility
- **Fibonacci Integration**: Five-level retracement analysis
- **Zone-Aware Alerts**: Upper/lower zone differentiation
- **Dynamic Line Management**: Smart current week extension
- **Professional UI**: Comprehensive information table
### Future Enhancements
- **Multiple Symbols**: Extend beyond SPX to other indices
- **Automated Data**: Integration with options data APIs
- **Statistical Analysis**: Success rate tracking for EM predictions
- **Additional Levels**: Custom percentage levels beyond Fibonacci
## License & Usage
This indicator is designed for educational and trading purposes. Users are responsible for:
- **Data Accuracy**: Ensuring correct expected move values
- **Risk Management**: Proper position sizing and risk controls
- **Market Understanding**: Comprehending options-based expected move concepts
## Support
For questions, issues, or feature requests related to this indicator, please refer to the code comments and documentation within the Pine Script file.
---
**Disclaimer**: This indicator is for informational purposes only. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results.
Multi TF Oscillators Screener [TradingFinder] RSI / ATR / Stoch🔵 Introduction
The oscillator screener is designed to simplify multi-timeframe analysis by allowing traders and analysts to monitor one or multiple symbols across their preferred timeframes—all at the same time. Users can track a single symbol through various timeframes simultaneously or follow multiple symbols in selected intervals. This flexibility makes the tool highly effective for analyzing diverse markets concurrently.
At the core of this screener lie two essential oscillators: RSI (Relative Strength Index) and the Stochastic Oscillator. The RSI measures the speed and magnitude of recent price movements and helps identify overbought or oversold conditions.
It's one of the most reliable indicators for spotting potential reversals. The Stochastic Oscillator, on the other hand, compares the current price to recent highs and lows to detect momentum strength and potential trend shifts. It’s especially effective in identifying divergences and short-term reversal signals.
In addition to these two primary indicators, the screener also displays helpful supplementary data such as the dominant candlestick type (Bullish, Bearish, or Doji), market volatility indicators like ATR and TR, and the four key OHLC prices (Open, High, Low, Close) for each symbol and timeframe. This combination of data gives users a comprehensive technical view and allows for quick, side-by-side comparison of symbols and timeframes.
🔵 How to Use
This tool is built for users who want to view the behavior of a single symbol across several timeframes simultaneously. Instead of jumping between charts, users can quickly grasp the state of a symbol like gold or Bitcoin across the 15-minute, 1-hour, and daily timeframes at a glance. This is particularly useful for traders who rely on multi-timeframe confirmation to strengthen their analysis and decision-making.
The tool also supports simultaneous monitoring of multiple symbols. Users can select and track various assets based on the timeframes that matter most to them. For example, if you’re looking for entry opportunities, the screener allows you to compare setups across several markets side by side—making it easier to choose the most favorable trade. Whether you’re a scalper focused on low timeframes or a swing trader using higher ones, the tool adapts to your workflow.
The screener utilizes the widely-used RSI indicator, which ranges from 0 to 100 and highlights market exhaustion levels. Readings above 70 typically indicate potential pullbacks, while values below 30 may suggest bullish reversals. Viewing RSI across timeframes can reveal meaningful divergences or alignments that improve signal quality.
Another key indicator in the screener is the Stochastic Oscillator, which analyzes the closing price relative to its recent high-low range. When the %K and %D lines converge and cross within the overbought or oversold zones, it often signals a momentum reversal. This oscillator is especially responsive in lower timeframes, making it ideal for spotting quick entries or exits.
Beyond these oscillators, the table includes other valuable data such as candlestick type (bullish, bearish, or doji), volatility measures like ATR and TR, and complete OHLC pricing. This layered approach helps users understand both market momentum and structure at a glance.
Ultimately, this screener allows analysts and traders to gain a full market overview with just one look—empowering faster, more informed, and lower-risk decision-making. It not only saves time but also enhances the precision and clarity of technical analysis.
🔵 Settings
🟣 Display Settings
Table Size : Lets you adjust the table’s visual size with options such as: auto, tiny, small, normal, large, huge.
Table Position : Sets the screen location of the table. Choose from 9 possible positions, combining vertical (top, middle, bottom) and horizontal (left, center, right) alignments.
🟣 Symbol Settings
Each of the 10 symbol slots comes with a full set of customizable parameters :
Enable Symbol : A checkbox to activate or hide each symbol from the table.
Symbol : Define or select the asset (e.g., XAUUSD, BTCUSD, EURUSD, etc.).
Timeframe : Set your desired timeframe for each symbol (e.g., 15, 60, 240, 1D).
RSI Length : Defines the period used in RSI calculation (default is 14).
Stochastic Length : Sets the period for the Stochastic Oscillator.
ATR Length : Sets the length used to calculate the Average True Range, a key volatility metric.
🔵 Conclusion
By combining powerful oscillators like RSI and Stochastic with full customization over symbols and timeframes, this tool provides a fast, flexible solution for technical analysts. Users can instantly monitor one or several assets across multiple timeframes without opening separate charts.
Individual configuration for each symbol, along with the inclusion of key metrics like candlestick type, ATR/TR, and OHLC prices, makes the tool suitable for a wide range of trading styles—from scalping to swing and position trading.
In summary, this screener enables traders to gain a clear, high-level view of various markets in seconds and make quicker, smarter, and lower-risk decisions. It saves time, streamlines analysis, and boosts overall efficiency and confidence in trading strategies.
ATR-Stop-DominoDetailed description of the ATR-Stop-Domino indicator
Important notice:
The slopes of the stop loss lines should NOT be used as entry or exit signals. They are not reliable for that purpose. Always use other indicators like MACD, RSI, SMI, or others to confirm trade signals before making decisions.
Leverage:
If the indicator shows a stop loss of 2%, this means that without leverage you are willing to risk 2% of your capital on that trade. However, if you trade with 3x leverage, your potential loss is multiplied by 3, which means 6% of your total capital.
Remember your total capital represents 100%, so be very careful with leverage to avoid risking more than you can afford to lose.
Dear trader,
First, I do not promise profits or success in your trades, as that depends on many factors—mainly your chart interpretation and risk management. The ATR-Stop-Domino indicator was created to help traders operate with more safety and better loss control, especially those who want to trade small capital while still using stop loss.
Why use stop loss?
Trading without stop loss is very risky since losses can be large or even wipe out your capital. The ATR-Stop-Domino uses the ATR (Average True Range) to calculate dynamic stop loss levels based on asset volatility, providing an intelligent reference to limit losses.
Important settings:
Default ATR multiplier: 1.5 (balanced protection and room)
For tighter stops, use 1.0
For more aggressive assets, use 2.0 or higher
Default ATR period: 14
What you will see on the chart:
Green line: stop loss for long positions
Red line: stop loss for short positions
Blue line: “safe line” in the middle for better visualization
Labels showing stop loss percentage and optionally the exact price
How to interpret the percentages:
They show how much you are willing to lose if the price hits the stop loss, helping you visualize your risk.
Recommendations:
Avoid using on daily, weekly, or monthly charts (stop loss may be too far)
Ideal for 4h, 3h, 2h or lower timeframes
Consider leverage when calculating real risk
Adjust ATR Period and ATR Multiplier according to asset and strategy
Remember:
This indicator is a support tool and does not guarantee profits. Always confirm signals with other indicators and manage your risk.
Super Neema!🟧 Super Neema! — Multi-Timeframe EMA-9 Overlay
🔍 What is "Neema"?
The term "Neema" has recently emerged among traders at SMB Capital—a top proprietary trading firm—who colloquially use "Neema" as shorthand for the 9-period Exponential Moving Average (EMA). Due to its increasing popularity and reliability, the phrase caught on quickly as traders needed a quick, memorable name for such an essential tool.
📚 Why the 9-EMA?
Scalping around the 9-EMA is now one of the most widely used intraday trading techniques. Traders of various experience levels frequently rely on it because it effectively highlights short-term momentum shifts.
But there's a crucial nuance: traders across different assets or market periods don't always agree on which timeframe’s 9-EMA to follow. Depending on who's currently active in the market, the dominant "Neema" could be the 1-minute, 2-minute, 3-minute, or 5-minute 9-EMA. This variation arises naturally due to differences in trader populations, risk tolerance, style, and current market conditions.
👥 Social Convention & Normative Social Influence
Trading is fundamentally a social activity, and normative social influence plays a critical role in market behavior. Traders don’t operate in isolation; they follow patterns, respond to cues, and rely on shared conventions. The popularity of any given indicator—like the 9-EMA—is not just technical, but deeply social. Traders adapt to what's socially accepted, recognizable, and effective.
Over time, these conventions shift. What once was "the standard" timeframe can subtly evolve as dominant traders or institutions shift their preferred style or timeframe, creating "variants" of established trends. Understanding this dynamic is essential for market participants because recognizing where the majority of traders currently focus gives a critical edge.
📈 Why Does This Matter? (Market Evolution & Trader Adaptability)
Market trends aren't just technical—they're social constructs. As markets evolve, participants adapt their methods to fit new norms. Traders who recognize and adapt quickly to these evolving norms gain a decisive advantage.
By clearly visualizing multiple Neemas (9-EMAs across timeframes) simultaneously, you don't merely see EMA levels—you visually sense the current social convention of the market. This heightened awareness helps you stay adaptive and flexible, aligning your strategy dynamically with the broader community of traders.
🎨 Transparency Scheme (Visual Identification):
5-minute Neema: Most opaque, brightest line (slowest, most significant trend)
3-minute Neema: Slightly more transparent
2-minute Neema: Even more transparent
1-minute Neema: Most transparent, subtle background hint (fastest, quickest reaction)
This deliberate visual hierarchy makes it intuitive to identify immediately which timeframe is currently dominant, and therefore, which timeframe other traders are using most actively.
✅ Works on:
Any timeframe, any chart. Automatically plots the 1m–5m EMA-9 lines regardless of your current chart.
🧠 Key Insight:
Markets are driven by social trends and normative influence.
Identifying the currently dominant timeframe (the Neema most respected by traders at that moment) is a powerful, socially-informed edge.
Trader adaptability isn't just technical—it's social awareness in action.
Enjoy your trading, and welcome to Super Neema! ⚡