Custom 6H Candle HighlightHighlights a certain 6H candle on the chart. Input which 6H Candle in the settings for the indicator.
Statistics
30-Minute Candle Breakout with Fibonacci and Stop Loss a code that just indicates a 30-minute candle.
broken after 15 minutes, if these criteria are present in the candle, choose the candle's top with a line in 30 minutes and its bottom with a line.
ADX BoxDescription:
The ADX Box indicator provides traders with a quick and intuitive way to monitor the current trend strength based on the Average Directional Index (ADX), calculated with a customisable period (default: 7 periods).
This compact indicator neatly displays the current ADX value rounded to one decimal place, along with a clear directional arrow:
Green upward triangle (▲): Indicates that ADX is rising above its moving average, signaling increasing trend strength.
Red downward triangle (▼): Indicates that ADX is declining below its moving average, signaling weakening trend strength.
Key Features:
Small and clean visual representation.
Dynamically updates in real-time directly on the chart.
Ideal for quick trend strength assessment without cluttering your workspace.
Recommended Usage:
Quickly identifying whether market trends are strengthening or weakening.
Enhancing decision-making for trend-following or breakout trading strategies.
Complementing other indicators such as ATR boxes for volatility measurement.
Feel free to use, share, and incorporate this indicator into your trading setups for clearer insights and more confident trading decisions!
Correlation TableThis indicator displays a vertical table that shows the correlation between the asset currently loaded on the chart and up to 32 selected trading pairs. It offers the following features:
Chart-Based Correlation: Correlations are calculated based on the asset you have loaded in your chart, providing relevant insights for your current market focus.
Configurable Pairs: Choose from a list of 32 symbols (e.g., AUDUSD, EURUSD, GBPUSD, etc.) with individual checkboxes to include or exclude each pair in the correlation analysis.
Custom Correlation Length: Adjust the lookback period for the correlation calculation to suit your analysis needs.
Optional EMA Smoothing: Enable an Exponential Moving Average (EMA) on the price data, with a configurable EMA length, to smooth the series before calculating correlations.
Color-Coded Output: The table cells change color based on the correlation strength and direction—neutral, bullish (green), or bearish (red)—making it easy to interpret at a glance.
Clear Table Layout: The indicator outputs a neatly organized vertical table with headers for "Pair" and "Correlation," ensuring the information is displayed cleanly and is easy to understand.
Ideal for traders who want a quick visual overview of how different instruments correlate with their current asset, this tool supports informed multi-asset analysis
ITALIANO:
Questo indicatore visualizza una tabella verticale che mostra la correlazione tra l'asset attualmente caricato sul grafico e fino a 32 coppie di trading selezionate. Offre le seguenti funzionalità:
Correlazione basata sul grafico: le correlazioni vengono calcolate in base all'asset caricato nel grafico, fornendo informazioni pertinenti per il tuo attuale focus di mercato.
Coppie configurabili: scegli da un elenco di 32 simboli (ad esempio, AUDUSD, EURUSD, GBPUSD, ecc.) con caselle di controllo individuali per includere o escludere ciascuna coppia nell'analisi della correlazione.
Lunghezza di correlazione personalizzata: regola il periodo di lookback per il calcolo della correlazione in base alle tue esigenze di analisi.
Smoothing EMA opzionale: abilita una media mobile esponenziale (EMA) sui dati dei prezzi, con una lunghezza EMA configurabile, per smussare la serie prima di calcolare le correlazioni.
Output codificato a colori: le celle della tabella cambiano colore in base alla forza e alla direzione della correlazione, neutra, rialzista (verde) o ribassista (rosso), rendendola facile da interpretare a colpo d'occhio.
Clear Table Layout: l'indicatore genera una tabella verticale ordinatamente organizzata con intestazioni per "Coppia" e "Correlazione", assicurando che le informazioni siano visualizzate in modo chiaro e siano facili da comprendere.
Ideale per i trader che desiderano una rapida panoramica visiva di come diversi strumenti siano correlati con il loro asset corrente, questo strumento supporta un'analisi multi-asset informata
ALPHATOTAL1Library "ALPHATOTAL1"
TODO: add library description here
alpha(beta, asset)
Parameters:
beta (float)
asset (float)
BetaTOTAL1Library "BetaTOTAL1"
TODO: add library description here
beta(x, y)
Parameters:
x (int)
y (float)
Trade size calculatorOverview
The Trade Size Calculator helps traders determine optimal trade sizes based on risk management principles. It calculates the number of shares to buy, stop-loss levels, and target prices while analyzing market trends and volatility.
How It Works
Risk & Allocation: Users input their account size, risk percentage per trade, and allocation percentage to determine capital exposure. ATR-based stop-loss can be enabled for volatility-adjusted risk management.
Market Trend Detection: Uses 9 & 21 EMA to identify short-term trend direction. Bollinger Bands and ATR help detect consolidation phases (low volatility).
Trade Calculations: Computes position size, stop-loss, shares to buy, and target price (2:1 Risk-Reward Ratio).
On-Chart Table: Displays key trading metrics:
Current Price
Shares to Buy
Stop-Loss Price
Target Price (2:1 RRR)
Short-Term Trend
How to Use
Add to Chart: Paste this script into TradingView's Pine Script Editor and click Add to Chart.
Adjust Settings: Modify account size, risk percentage, and ATR stop-loss multiplier as needed.
Use the Table Data: Follow the trade size, stop-loss, target price, and trend indicator to plan trades effectively.
Standard Deviation (fadi)The Standard Deviation indicator uses standard deviation to map out price movements. Standard deviation measures how much prices stray from their average—small values mean steady trends, large ones mean wild swings. Drawing from up to 20 years of data, it plots key levels using customizable Fibonacci lines tied to that standard deviation, giving traders a snapshot of typical price behavior.
These levels align with a bell curve: about 68% of price moves stay within 1 standard deviation, 95% within roughly 2, and 99.7% within roughly 3. When prices break past the 1 StDev line, they’re outliers—only 32% of moves go that far. Prices often snap back to these lines or the average, though the reversal might not happen the same day.
How Traders Use It
If prices surge past the 1 StDev line, traders might wait for momentum to fade, then trade the pullback to that line or the average, setting a target and stop.
If prices dip below, they might buy, anticipating a bounce—sometimes a day or two later. It’s a tool to spot overstretched prices likely to revert and/or measure the odds of continuation.
Settings
Higher Timeframe: Sets the Higher Timeframe to calculate the Standard Deviation for
Show Levels for the Last X Days: Displays levels for the specified number of days.
Based on X Period: Number of days to calculate standard deviation (e.g., 20 years ≈ 5,040 days). Larger periods smooth out daily level changes.
Mirror Levels on the Other Side: Plots symmetric positive and negative levels around the average.
Fibonacci Levels Settings: Defines which levels and line styles to show. With mirroring, negative values aren’t needed.
Background Transparency: Turn on Background color derived from the level colors with the specified transparency
Overrides: Lets advanced users input custom standard deviations for specific tickers (e.g., NQ1! at 0.01296).
Crypto Breakout Screener (1H)The Crypto Breakout Screener (1H) identifies coins showing early signs of bullish momentum after testing bottom support levels. It combines gap percentage, volume surge, RSI range, and MACD crossover to highlight potential breakout setups. Designed for the 1-hour timeframe, this tool helps traders catch moves before they fully develop.
StatPivot- Dynamic Range Analyzer - indicator [PresentTrading]Hello everyone! In the following few open scripts, I would like to share various statistical tools that benefit trading. For this time, it is a powerful indicator called StatPivot- Dynamic Range Analyzer that brings a whole new dimension to your technical analysis toolkit.
This tool goes beyond traditional pivot point analysis by providing comprehensive statistical insights about price movements, helping you identify high-probability trading opportunities based on historical data patterns rather than subjective interpretations. Whether you're a day trader, swing trader, or position trader, StatPivot's real-time percentile rankings give you a statistical edge in understanding exactly where current price action stands within historical contexts.
Welcome to share your opinions! Looking forward to sharing the next tool soon!
█ Introduction and How it is Different
StatPivot is an advanced technical analysis tool that revolutionizes retracement analysis. Unlike traditional pivot indicators that only show static support/resistance levels, StatPivot delivers dynamic statistical insights based on historical pivot patterns.
Its key innovation is real-time percentile calculation - while conventional tools require new pivot formations before updating (often too late for trading decisions), StatPivot continuously analyzes where current price stands within historical retracement distributions.
Furthermore, StatPivot provides comprehensive statistical metrics including mean, median, standard deviation, and percentile distributions of price movements, giving traders a probabilistic edge by revealing which price levels represent statistically significant zones for potential reversals or continuations. By transforming raw price data into statistical insights, StatPivot helps traders move beyond subjective price analysis to evidence-based decision making.
█ Strategy, How it Works: Detailed Explanation
🔶 Pivot Point Detection and Analysis
The core of StatPivot's functionality begins with identifying significant pivot points in the price structure. Using the parameters left and right, the indicator locates pivot highs and lows by examining a specified number of bars to the left and right of each potential pivot point:
Copyp_low = ta.pivotlow(low, left, right)
p_high = ta.pivothigh(high, left, right)
For a point to qualify as a pivot low, it must have left higher lows to its left and right higher lows to its right. Similarly, a pivot high must have left lower highs to its left and right lower highs to its right. This approach ensures that only significant turning points are recognized.
🔶 Percentage Change Calculation
Once pivot points are identified, StatPivot calculates the percentage changes between consecutive pivot points:
For drops (when a pivot low is lower than the previous pivot low):
CopydropPercent = (previous_pivot_low - current_pivot_low) / previous_pivot_low * 100
For rises (when a pivot high is higher than the previous pivot high):
CopyrisePercent = (current_pivot_high - previous_pivot_high) / previous_pivot_high * 100
These calculations quantify the magnitude of each market swing, allowing for statistical analysis of historical price movements.
🔶 Statistical Distribution Analysis
StatPivot computes comprehensive statistics on the historical distribution of drops and rises:
Average (Mean): The arithmetic mean of all recorded percentage changes
CopyavgDrop = array.avg(dropValues)
Median: The middle value when all percentage changes are arranged in order
CopymedianDrop = array.median(dropValues)
Standard Deviation: Measures the dispersion of percentage changes from the average
CopystdDevDrop = array.stdev(dropValues)
Percentiles (25th, 75th): Values below which 25% and 75% of observations fall
Copyq1 = array.get(sorted, math.floor(cnt * 0.25))
q3 = array.get(sorted, math.floor(cnt * 0.75))
VaR95: The maximum expected percentage drop with 95% confidence
Copyvar95D = array.get(sortedD, math.floor(nD * 0.95))
Coefficient of Variation (CV): Measures relative variability
CopycvD = stdDevDrop / avgDrop
These statistics provide a comprehensive view of market behavior, enabling traders to understand the typical ranges and extreme moves.
🔶 Real-time Percentile Ranking
StatPivot's most innovative feature is its real-time percentile calculation. For each current price, it calculates:
The percentage drop from the latest pivot high:
CopycurrentDropPct = (latestPivotHigh - close) / latestPivotHigh * 100
The percentage rise from the latest pivot low:
CopycurrentRisePct = (close - latestPivotLow) / latestPivotLow * 100
The percentile ranks of these values within the historical distribution:
CopyrealtimeDropRank = (count of historical drops <= currentDropPct) / total drops * 100
This calculation reveals exactly where the current price movement stands in relation to all historical movements, providing crucial context for decision-making.
🔶 Cluster Analysis
To identify the most common retracement zones, StatPivot performs a cluster analysis by dividing the range of historical drops into five equal intervals:
CopyrangeSize = maxVal - minVal
For each interval boundary:
Copyboundaries = minVal + rangeSize * i / 5
By counting the number of observations in each interval, the indicator identifies the most frequently occurring retracement zones, which often serve as significant support or resistance areas.
🔶 Expected Price Targets
Using the statistical data, StatPivot calculates expected price targets:
CopytargetBuyPrice = close * (1 - avgDrop / 100)
targetSellPrice = close * (1 + avgRise / 100)
These targets represent statistically probable price levels for potential entries and exits based on the average historical behavior of the market.
█ Trade Direction
StatPivot functions as an analytical tool rather than a direct trading signal generator, providing statistical insights that can be applied to various trading strategies. However, the data it generates can be interpreted for different trade directions:
For Long Trades:
Entry considerations: Look for price drops that reach the 70-80th percentile range in the historical distribution, suggesting a statistically significant retracement
Target setting: Use the Expected Sell price or consider the average rise percentage as a reasonable target
Risk management: Set stop losses below recent pivot lows or at a distance related to the statistical volatility (standard deviation)
For Short Trades:
Entry considerations: Look for price rises that reach the 70-80th percentile range, indicating an unusual extension
Target setting: Use the Expected Buy price or average drop percentage as a target
Risk management: Set stop losses above recent pivot highs or based on statistical measures of volatility
For Range Trading:
Use the most common drop and rise clusters to identify probable reversal zones
Trade bounces between these statistically significant levels
For Trend Following:
Confirm trend strength by analyzing consecutive higher pivot lows (uptrend) or lower pivot highs (downtrend)
Use lower percentile retracements (20-30th percentile) as entry opportunities in established trends
█ Usage
StatPivot offers multiple ways to integrate its statistical insights into your trading workflow:
Statistical Table Analysis: Review the comprehensive statistics displayed in the data table to understand the market's behavior. Pay particular attention to:
Average drop and rise percentages to set reasonable expectations
Standard deviation to gauge volatility
VaR95 for risk assessment
Real-time Percentile Monitoring: Watch the real-time percentile display to see where the current price movement stands within the historical distribution. This can help identify:
Extreme movements (90th+ percentile) that might indicate reversal opportunities
Typical retracements (40-60th percentile) that might continue further
Shallow pullbacks (10-30th percentile) that might represent continuation opportunities in trends
Support and Resistance Identification: Utilize the plotted pivot points as key support and resistance levels, especially when they align with statistically significant percentile ranges.
Target Price Setting: Use the expected buy and sell prices calculated from historical averages as initial targets for your trades.
Risk Management: Apply the statistical measurements like standard deviation and VaR95 to set appropriate stop loss levels that account for the market's historical volatility.
Pattern Recognition: Over time, learn to recognize when certain percentile levels consistently lead to reversals or continuations in your specific market, and develop personalized strategies based on these observations.
█ Default Settings
The default settings of StatPivot have been carefully calibrated to provide reliable statistical analysis across a variety of markets and timeframes, but understanding their effects allows for optimal customization:
Left Bars (30) and Right Bars (30): These parameters determine how pivot points are identified. With both set to 30 by default:
A pivot low must be the lowest point among 30 bars to its left and 30 bars to its right
A pivot high must be the highest point among 30 bars to its left and 30 bars to its right
Effect on performance: Larger values create fewer but more significant pivot points, reducing noise but potentially missing important market structures. Smaller values generate more pivot points, capturing more nuanced movements but potentially including noise.
Table Position (Top Right): Determines where the statistical data table appears on the chart.
Effect on performance: No impact on analytical performance, purely a visual preference.
Show Distribution Histogram (False): Controls whether the distribution histogram of drop percentages is displayed.
Effect on performance: Enabling this provides visual insight into the distribution of retracements but can clutter the chart.
Show Real-time Percentile (True): Toggles the display of real-time percentile rankings.
Effect on performance: A critical setting that enables the dynamic analysis of current price movements. Disabling this removes one of the key advantages of the indicator.
Real-time Percentile Display Mode (Label): Chooses between label display or indicator line for percentile rankings.
Effect on performance: Labels provide precise information at the current price point, while indicator lines show the evolution of percentile rankings over time.
Advanced Considerations for Settings Optimization:
Timeframe Adjustment: Higher timeframes generally benefit from larger Left/Right values to identify truly significant pivots, while lower timeframes may require smaller values to capture shorter-term swings.
Volatility-Based Tuning: In highly volatile markets, consider increasing the Left/Right values to filter out noise. In less volatile conditions, lower values can help identify more potential entry and exit points.
Market-Specific Optimization: Different markets (forex, stocks, commodities) display different retracement patterns. Monitor the statistics table to see if your market typically shows larger or smaller retracements than the current settings are optimized for.
Trading Style Alignment: Adjust the settings to match your trading timeframe. Day traders might prefer settings that identify shorter-term pivots (smaller Left/Right values), while swing traders benefit from more significant pivots (larger Left/Right values).
By understanding how these settings affect the analysis and customizing them to your specific market and trading style, you can maximize the effectiveness of StatPivot as a powerful statistical tool for identifying high-probability trading opportunities.
Time Marker Pro: Vertical Line at Key Times)Smart Vertical Line at Specific Time (with Timezone, Color, and Width Controls)
This script draws a vertical line on your chart at a user-defined time once per day, based on the selected timezone.
🕒 Key Features:
Set your target hour and minute
Choose from a list of common timezones (Tehran, UTC, New York, etc.)
Customize the line color and thickness
Works across all intraday timeframes (1min, 5min, 15min, etc.)
Adjusts automatically to bar intervals — no need for exact time matching
This is perfect for traders who want to:
Highlight the start of a session
Mark specific news times, breakouts, or routine entries
Visualize key time-based levels on the chart
EMA 5/13/20/50/100/200Dieses TradingView-Skript zeigt sechs Exponentielle Gleitende Durchschnitte (EMAs) mit unterschiedlichen Perioden auf dem Chart an. EMAs sind ein beliebtes technisches Analysetool, das dabei hilft, Trends und mögliche Umkehrpunkte zu identifizieren.
Enthaltene EMAs:
EMA 5 (rot): Sehr kurzfristiger Trendindikator
EMA 13 (aqua): Kurzfristiger Trendindikator
EMA 20 (schwarz): Mittelfristiger Trendindikator
EMA 50 (blau): Längerfristiger Trendindikator
EMA 100 (grün, dicke Linie): Langfristiger Trendindikator
EMA 200 (orange, dicke Linie): Sehr langfristiger Trendindikator
Die EMA 100 und EMA 200 werden mit einer dickeren Linie dargestellt, da sie häufig als starke Unterstützungs- oder Widerstandszonen dienen. Dieses Skript eignet sich für verschiedene Trading-Strategien, insbesondere für Trendfolge-Strategien und zur Identifikation von Trendwenden.
🔹 Skalptrading:
Die EMAs sind besonders gut für das Skalptrading im 3- und 5-Minuten-Chart geeignet. Trader können schnelle Marktbewegungen nutzen, indem sie auf kurzfristige Kreuzungen und Abpraller an den EMAs achten.
Lot Size Calculator (Gold, BTC, Forex)//@version=5
indicator("Lot Size Calculator (Gold, BTC, Forex)", overlay=false)
// User Inputs
account_size = input.float(10000, title="Account Size ($)")
asset_type = input.string("Gold", title="Select Asset", options= )
gold_price = input.float(3000, title="Gold Price ($)", group="Asset Prices")
btc_price = input.float(60000, title="Bitcoin Price ($)", group="Asset Prices")
forex_price = input.float(1.1, title="Forex Price (EUR/USD, GBP/USD etc.)", group="Asset Prices")
// Leverage Based on Asset Type
gold_leverage = 10 // 1:10 for Gold
btc_leverage = 2 // 1:2 for Bitcoin
forex_leverage = 50 // 1:50 for Forex
// Determine Leverage & Price Based on Selected Asset
leverage = asset_type == "Gold" ? gold_leverage : asset_type == "BTC" ? btc_leverage : forex_leverage
market_price = asset_type == "Gold" ? gold_price : asset_type == "BTC" ? btc_price : forex_price
// Standard Lot Sizes
gold_lot_size = 100 // 1 Standard Lot = 100 Ounces
btc_lot_size = 1 // 1 Standard Lot = 1 BTC
forex_lot_size = 100000 // 1 Standard Lot = 100,000 Units
lot_size = asset_type == "Gold" ? gold_lot_size : asset_type == "BTC" ? btc_lot_size : forex_lot_size
// Calculation
max_margin_requirement = account_size / 1.5
max_lot_size_units = (max_margin_requirement * leverage) / market_price
max_standard_lots = max_lot_size_units / lot_size
// Displaying Histogram
plot(max_standard_lots, title="Max Standard Lots", color=color.blue, style=plot.style_histogram)
// Table for Displaying Results
var table results = table.new(position=position.top_right, columns=1, rows=5, border_width=2)
if bar_index == last_bar_index
table.cell(results, 0, 0, "📊 Lot Size Calculator", text_color=color.white, bgcolor=color.blue)
table.cell(results, 0, 1, "🔵 Account Size: $" + str.tostring(account_size), text_color=color.blue, bgcolor=color.white)
table.cell(results, 0, 2, "🟢 Selected Asset: " + asset_type, text_color=color.green, bgcolor=color.white)
table.cell(results, 0, 3, "🔴 Market Price: $" + str.tostring(market_price), text_color=color.red, bgcolor=color.white)
table.cell(results, 0, 4, "🟡 Max Lots: " + str.tostring(max_standard_lots, "#.##"), text_color=color.rgb(23, 187, 187), bgcolor=color.white)
MA Smoothed RSI For LoopMA Smoothed Source For RSI Loop
Conceptual Foundation and Innovation
The "MA Smoothed Source For RSI Loop" indicator innovates by smoothing the source data used for RSI calculation with various moving averages before feeding it into a for-loop scoring system. Rather than smoothing the RSI itself, this approach focuses on pre-processing the price data to reduce noise, thereby providing a cleaner input for RSI computation. The for-loop then evaluates this smoothed RSI to generate momentum signals, offering traders a refined method for detecting market trends and potential reversals.
Technical Composition and Calculation
The indicator's functionality is divided into two main parts:
Source Smoothing: Before calculating RSI, the source data (typically close price) is smoothed using one of several moving averages (EMA, SMA, WMA, VWMA, HMA, RMA, DEMA, or none) as selected by the user. This smoothing aims to filter out short-term volatility, providing a more consistent base for RSI calculation.
RSI Calculation and For-Loop Scoring:
RSI: Calculated using the smoothed source data over a user-defined length.
For-Loop Mechanism: A loop runs from a to b, comparing the current RSI value with past values of this smoothed RSI. A score (counter) is generated, which increases or decreases based on whether the current RSI exceeds or falls below past values. If the weighted option is activated, this comparison gives more weight to recent data points, adjusting the score accordingly.
The final score is then potentially normalized for better interpretation, compared against thresholds to determine market momentum signals.
Features and User Inputs
This indicator is highly customizable, allowing traders to tailor its behavior:
Weighted Calculation: Option to adjust scoring to favor recent price action.
RSI Length: Sets the period for RSI calculation.
Source: The price data to be smoothed before RSI calculation, default is close.
MA Type: Choice from various moving averages to smooth the source data.
Smooth Length: Length of the moving average used for smoothing.
For Loop Range: Defines the historical range (a to b) for the scoring loop.
Thresholds: Custom thresholds to define when signals for uptrends or downtrends are generated.
Practical Applications
This indicator is particularly beneficial for:
Identifying Momentum Shifts: The scoring system helps in detecting potential changes in market momentum.
Noise Reduction: By smoothing the source data, it aims to provide more reliable RSI signals in volatile markets.
Trend Analysis: Assists in confirming or challenging the current market trend based on the smoothed RSI's performance.
Advantages and Strategic Value
The "MA Smoothed Source For RSI Loop" offers an advantage by focusing on cleaning the input data for RSI, which can lead to more accurate momentum readings. Its flexibility in configuration allows traders to adapt the indicator to different market conditions or asset volatilities, enhancing its strategic value in trading decisions.
Alerts and Visual Cues
Visual Signals: The indicator plots the loop score, with colors indicating uptrends (gold) or downtrends (blue). Horizontal lines at thresholds and shaded areas between them provide visual aids for trend analysis.
**No explicit alerts in the script, but users can set up custom alerts based on the signals.
Summary and Usage Tips
The "MA Smoothed Source For RSI Loop" provides a nuanced approach to RSI by smoothing the price data before its calculation, resulting in potentially more reliable signals. Traders can use this indicator to gain a clearer picture of market momentum, adjusting parameters to fit different market behaviors or trading strategies. Remember, the effectiveness of this tool largely depends on its customization to the specific market context.
Note: Backtests are based on past results and do not guarantee future performance.
MF Global Money Supply M2 by MigueFinanceglobal m2 offset 70/aspdoifcjapsodifjpa oswedf pxaciswfpmqonvjswdf
Coinbase 比特币溢价指数The "Coinbase Bitcoin Premium Index" indicator is designed to measure the price difference between Bitcoin on the Coinbase exchange and the Binance exchange, presented as a percentage premium. Here's a detailed explanation of its meaning and function:
Gap-Down ReversalThis indicator is designed to identify potential reversal opportunities following gap-down opens, based on statistical principles and observed market behavior. (Use only stocks.)
📈 What It Does?
The script calculates standard deviation of daily log (logarithm) returns over a user-defined period (default: 90 days). It then detects when the opening price gaps down significantly (beyond a user-defined Z-score threshold, default: 1.0), potentially indicating an overreaction in the market.
When such a condition is met, the indicator plots (at the open) a green triangle below the bar, signaling a potential area where mean reversion may occur.
🧠 Why Gap-Downs Might Reverse?
This indicator is based on well-studied market behaviors:
Panic Selling: Many traders and investors react emotionally to overnight news, “tweets“ leading to excessive selling at the open.
Liquidity Imbalances: Institutional traders often delay large buy orders, allowing early price movements to be exaggerated.
Lack of Stock-Specific News: Many gap-downs happen due to broad market movements rather than stock-specific bad news.
These events can lead to temporary mispricings, which often mean revert once rational price discovery resumes.
📚 A similar mean-reversion concept is discussed in Ernest P. Chan’s book, " Algorithmic Trading: Winning Strategies and Their Rationale " (2013).
⚙️ How It Works
Standard Deviation Length: Determines the historical volatility used for calculating significant gaps.
Z-Score Threshold: Defines how large the gap-down must be (relative to volatility) to trigger a signal.
Gap-Down Return: Measured from today’s open vs. yesterday’s low.
⚠️ Important Note
This indicator is designed for use in normal market conditions. It may produce unreliable signals during extreme volatility events, such as black swan scenarios, flash crashes, or major macroeconomic shocks. During such periods, market dynamics deviate from statistical norms, and price behavior may not revert as expected.
This script is for educational and informational purposes only.
Correlation X macroeconomicsFind the correlation between financial assets and the main Brazilian macroeconomic variables:
SELIC rate (Red)
PIB (Green)
Inflation (Blue)
Employment and income (Yellow)
Unlike other indicators that measure the correlation between two assets, the indicator "Correlation X macroeconomics" measures, for example, the correlation that the VALE3 asset has with the SELIC rate.
The correlation is obtained by calculating the variation suffered by a given asset on the day a given Brazilian macroeconomic variable is released.
This indicator can be used on any financial asset.
Use time frame chart = 1 day.
To calculate the correlation, data published by IBGE and the Central Bank of Brazil over a period of time are used. This time period is different depending on the selected macroeconomic variable. Namely:
16 PIB disclosures (4 years)
24 SELIC rate disclosures (3 years)
24 disclosures of IPCA and employment and income data (2 years)
You can select one or more macroeconomic variables to check the effect of correlation separately on each of them.
This indicator "Correlation X macroeconomics" will be updated monthly, as detailed below:
At the end of the day on which the PIB is released
At the end of the day on which employment and income data are released
At the end of the day following the day on which the SELIC rate is published
On the last business day of the month if none of the aforementioned disclosures occur