Deviation from Mid MA5 & MA10 (%)Title:
Deviation from Mid-Price MA5 & MA10 (%)
Description:
This script calculates and displays the percentage deviation of the current mid-price from its 5-day and 10-day simple moving averages.
The mid-price is defined as the average of the open and close prices: (Open + Close) / 2
Instead of relying on traditional close-based MAs, this version uses mid-price to better reflect actual price flow by incorporating both the opening and closing values.
Main features:
Displays % deviation from both 5-day and 10-day mid-price moving averages
Better alignment with intraday reality due to gap-sensitive mid-price base
Smooths out erratic closing spikes for clearer signals
Helps identify overextended moves and potential pullback zones
Included lines:
Deviation from 5-day Mid MA
Deviation from 10-day Mid MA
Zero baseline for reference
Recommended for:
Traders seeking a cleaner measure of price deviation
Short-term pullback or re-entry strategy users
Anyone analyzing steady, low-volatility uptrends
Indicators and strategies
Buy Sell Volume with delta value📄 Script Description
This indicator decomposes total traded volume into buying and selling volume, and displays their relative ratios.
🔎 Key Features
Buying vs. Selling Volume Separation
Uses the candle’s high, low, and close to split total volume into buying volume and selling volume.
Formula:
Buy = volume * (close - low) / (high - low)
Sell = volume * (high - close) / (high - low)
Volume Histogram Visualization
Plots overall volume (upper/lower) and separated buy/sell volumes as color-coded columns.
UPPER V / LOWER V: total volume
BUY V: buying volume (teal)
SELL V: selling volume (red)
Buy/Sell Ratio Calculation
Computes the percentage of buy and sell volume relative to total volume.
Buy Ratio = buyVolume / totalVolume * 100
Sell Ratio = sellVolume / totalVolume * 100
Ratio Display
Shows the latest Buy Ratio in a table (top-right corner of the chart).
Adds a label above the most recent bar displaying:
"Buy XX% / Sell YY%"
Historical ratios can be inspected through the TradingView Data Window or tooltip.
🛠️ Usage
Quickly identify whether volume during each candle is dominated by buyers or sellers.
Helps to assess market pressure and confirm potential trend direction, entries, or exits.
⚠️ Notes
Labels are shown only on the most recent bar (Pine cannot track mouse cursor events).
To see historical values, use the TradingView Data Window or hover tooltips.
This method provides an approximate split of volume and does not perfectly capture all market order flows.
Atr avg monthly by PanzerDisplay average ATR for 6 and 12 completed months in a text information table on the chart.
These values are handy for calculating options strategies.
Table can be display on several positions on chart.
Triple DEMA (Editable)3 Double exponential moving averages. (DEMA) are an improvement over Exponential Moving Average (EMA) because they allocate more weight to recent data points. The reduced lag results in a more responsive moving average, which helps short-term traders spot trend reversals quickly.
Auto-Fit Growth Trendline# **Theoretical Algorithmic Principles of the Auto-Fit Growth Trendline (AFGT)**
## **🎯 What Does This Algorithm Do?**
The Auto-Fit Growth Trendline is an advanced technical analysis system that **automates the identification of long-term growth trends** and **projects future price levels** based on historical cyclical patterns.
### **Primary Functionality:**
- **Automatically detects** the most significant lows in regular periods (monthly, quarterly, semi-annually, annually)
- **Constructs a dynamic trendline** that connects these historical lows
- **Projects the trend into the future** with high mathematical precision
- **Generates Fibonacci bands** that act as dynamic support and resistance levels
- **Automatically adapts** to different timeframes and market conditions
### **Strategic Purpose:**
The algorithm is designed to identify **fundamental value zones** where price has historically found support, enabling traders to:
- Identify optimal entry points for long positions
- Establish realistic price targets based on mathematical projections
- Recognize dynamic support and resistance levels
- Anticipate long-term price movements
---
## **🧮 Core Mathematical Foundations**
### **Adaptive Temporal Segmentation Theory**
The algorithm is based on **dynamic temporal partition theory**, where time is divided into mathematically coherent uniform intervals. It uses modular transformations to create bijective mappings between continuous timestamps and discrete periods, ensuring each temporal point belongs uniquely to a specific period.
**What does this achieve?** It allows the algorithm to automatically identify natural market cycles (annual, quarterly, etc.) without manual intervention, adapting to the inherent periodicity of each asset.
The temporal mapping function implements a **discrete affine transformation** that normalizes different frequencies (monthly, quarterly, semi-annual, annual) to a space of unique identifiers, enabling consistent cross-temporal comparative analysis.
---
## **📊 Local Extrema Detection Theory**
### **Multi-Point Retrospective Validation Principle**
Local minima detection is founded on **relative extrema theory with sliding window**. Instead of using a simple minimum finder, it implements a cross-validation system that examines the persistence of the extremum across multiple historical periods.
**What problem does this solve?** It eliminates false minima caused by temporal volatility, identifying only those points that represent true historical support levels with statistical significance.
This approach is based on the **statistical confirmation principle**, where a minimum is only considered valid if it maintains its extremum condition during a defined observation period, significantly reducing false positives caused by transitory volatility.
---
## **🔬 Robust Interpolation Theory with Outlier Control**
### **Contextual Adaptive Interpolation Model**
The mathematical core uses **piecewise linear interpolation with adaptive outlier correction**. The key innovation lies in implementing a **contextual anomaly detector** that identifies not only absolute extreme values, but relative deviations to the local context.
**Why is this important?** Financial markets contain extreme events (crashes, bubbles) that can distort projections. This system identifies and appropriately weights them without completely eliminating them, preserving directional information while attenuating distortions.
### **Implicit Bayesian Smoothing Algorithm**
When an outlier is detected (deviation >300% of local average), the system applies a **simplified Kalman filter** that combines the current observation with a local trend estimation, using a weight factor that preserves directional information while attenuating extreme fluctuations.
---
## **📈 Stabilized Extrapolation Theory**
### **Exponential Growth Model with Dampening**
Extrapolation is based on a **modified exponential growth model with progressive dampening**. It uses multiple historical points to calculate local growth ratios, implements statistical filtering to eliminate outliers, and applies a dampening factor that increases with extrapolation distance.
**What advantage does this offer?** Long-term projections in finance tend to be exponentially unrealistic. This system maintains short-to-medium term accuracy while converging toward realistic long-term projections, avoiding the typical "exponential explosions" of other methods.
### **Asymptotic Convergence Principle**
For long-term projections, the algorithm implements **controlled asymptotic convergence**, where growth ratios gradually converge toward pre-established limits, avoiding unrealistic exponential projections while preserving short-to-medium term accuracy.
---
## **🌟 Dynamic Fibonacci Projection Theory**
### **Continuous Proportional Scaling Model**
Fibonacci bands are constructed through **uniform proportional scaling** of the base curve, where each level represents a linear transformation of the main curve by a constant factor derived from the Fibonacci sequence.
**What is its practical utility?** It provides dynamic resistance and support levels that move with the trend, offering price targets and profit-taking points that automatically adapt to market evolution.
### **Topological Preservation Principle**
The system maintains the **topological properties** of the base curve in all Fibonacci projections, ensuring that spatial and temporal relationships are consistently preserved across all resistance/support levels.
---
## **⚡ Adaptive Computational Optimization**
### **Multi-Scale Resolution Theory**
It implements **automatic multi-resolution analysis** where data granularity is dynamically adjusted according to the analysis timeframe. It uses the **adaptive Nyquist principle** to optimize the signal-to-noise ratio according to the temporal observation scale.
**Why is this necessary?** Different timeframes require different levels of detail. A 1-minute chart needs more granularity than a monthly one. This system automatically optimizes resolution for each case.
### **Adaptive Density Algorithm**
Calculation point density is optimized through **adaptive sampling theory**, where calculation frequency is adjusted according to local trend curvature and analysis timeframe, balancing visual precision with computational efficiency.
---
## **🛡️ Robustness and Fault Tolerance**
### **Graceful Degradation Theory**
The system implements **multi-level graceful degradation**, where under error conditions or insufficient data, the algorithm progressively falls back to simpler but reliable methods, maintaining basic functionality under any condition.
**What does this guarantee?** That the indicator functions consistently even with incomplete data, new symbols with limited history, or extreme market conditions.
### **State Consistency Principle**
It uses **mathematical invariants** to guarantee that the algorithm's internal state remains consistent between executions, implementing consistency checks that validate data structure integrity in each iteration.
---
## **🔍 Key Theoretical Innovations**
### **A. Contextual vs. Absolute Outlier Detection**
It revolutionizes traditional outlier detection by considering not only the absolute magnitude of deviations, but their relative significance within the local context of the time series.
**Practical impact:** It distinguishes between legitimate market movements and technical anomalies, preserving important events like breakouts while filtering noise.
### **B. Extrapolation with Weighted Historical Memory**
It implements a memory system that weights different historical periods according to their relevance for current prediction, creating projections more adaptable to market regime changes.
**Competitive advantage:** It automatically adapts to fundamental changes in asset dynamics without requiring manual recalibration.
### **C. Automatic Multi-Timeframe Adaptation**
It develops an automatic temporal resolution selection system that optimizes signal extraction according to the intrinsic characteristics of the analysis timeframe.
**Result:** A single indicator that functions optimally from 1-minute to monthly charts without manual adjustments.
### **D. Intelligent Asymptotic Convergence**
It introduces the concept of controlled asymptotic convergence in financial extrapolations, where long-term projections converge toward realistic limits based on historical fundamentals.
**Added value:** Mathematically sound long-term projections that avoid the unrealistic extremes typical of other extrapolation methods.
---
## **📊 Complexity and Scalability Theory**
### **Optimized Linear Complexity Model**
The algorithm maintains **linear computational complexity** O(n) in the number of historical data points, guaranteeing scalability for extensive time series analysis without performance degradation.
### **Temporal Locality Principle**
It implements **temporal locality**, where the most expensive operations are concentrated in the most relevant temporal regions (recent periods and near projections), optimizing computational resource usage.
---
## **🎯 Convergence and Stability**
### **Probabilistic Convergence Theory**
The system guarantees **probabilistic convergence** toward the real underlying trend, where projection accuracy increases with the amount of available historical data, following **law of large numbers** principles.
**Practical implication:** The more history an asset has, the more accurate the algorithm's projections will be.
### **Guaranteed Numerical Stability**
It implements **intrinsic numerical stability** through the use of robust floating-point arithmetic and validations that prevent overflow, underflow, and numerical error propagation.
**Result:** Reliable operation even with extreme-priced assets (from satoshis to thousand-dollar stocks).
---
## **💼 Comprehensive Practical Application**
**The algorithm functions as a "financial GPS"** that:
1. **Identifies where we've been** (significant historical lows)
2. **Determines where we are** (current position relative to the trend)
3. **Projects where we're going** (future trend with specific price levels)
4. **Provides alternative routes** (Fibonacci bands as alternative targets)
This theoretical framework represents an innovative synthesis of time series analysis, approximation theory, and computational optimization, specifically designed for long-term financial trend analysis with robust and mathematically grounded projections.
Rainbow EMAs by PaulPogBeerFollow the trend for medium trend and long trend.
EMA 26-55 for medium trend.
EMA 200-275 for Long term trend.
Support Vs Reward RvCSupport Vs Reward RvC
The Support Vs Reward RvC indicator is a simple yet effective tool that analyzes candle strength relative to both price movement and trading volume. Highlights candles where both body size and volume expand or contract, helping traders spot momentum shifts and weakening moves.
📌 How it works:
- “C” expect a Continuation of Trend in the next one or two candles;
- “R” expect a Reverse of Trend in the next one or two candles.
Works well on bigger time candles like 10-15 minutes but also gives important info in day-trading or scalping.
Marks candles where both body size and volume increase or decrease, making momentum shifts easy to spot. This smart candle analyzer reveals momentum surges and fading moves through body size and volume dynamics.
It compares each candle’s body size (open-to-close range) and its volume against the previous candle.
If both the body and volume are greater than the previous candle, a green “C” from Continuation of Trend is displayed under the bar.
If both the body and volume are smaller than the previous candle, a red “R” from Reverse of Trend is displayed under the bar.
Custom filters allow users to ignore insignificant moves by setting a minimum body size (as % of price) and a minimum volume threshold.
📌 Use cases:
Spot momentum shifts when price and volume expand together.
Identify weakening moves when both price action and volume contract.
Can be combined with other strategies for confirmation of entries or exits.
⚙️ Inputs:
Minimum Body Size % (of price): Filters out small candles.
Minimum Volume: Ensures only significant moves are marked.
This indicator is best used as a confirmation tool within a larger trading strategy, rather than as a standalone buy/sell signal.
Market Outlook Score (MOS)Overview
The "Market Outlook Score (MOS)" is a custom technical indicator designed for TradingView, written in Pine Script version 6. It provides a quantitative assessment of market conditions by aggregating multiple factors, including trend strength across different timeframes, directional movement (via ADX), momentum (via RSI changes), volume dynamics, and volatility stability (via ATR). The MOS is calculated as a weighted score that ranges typically between -1 and +1 (though it can exceed these bounds in extreme conditions), where positive values suggest bullish (long) opportunities, negative values indicate bearish (short) setups, and values near zero imply neutral or indecisive markets.
This indicator is particularly useful for traders seeking a holistic "outlook" score to gauge potential entry points or market bias. It overlays on a separate pane (non-overlay mode) and visualizes the score through horizontal threshold lines and dynamic labels showing the numeric MOS value along with a simple trading decision ("Long", "Short", or "Neutral"). The script avoids using the plot function for compatibility reasons (e.g., potential TradingView bugs) and instead relies on hline for static lines and label.new for per-bar annotations.
Key features:
Multi-Timeframe Analysis: Incorporates slope data from 5-minute, 15-minute, and 30-minute charts to capture short-term trends.
Trend and Strength Integration: Uses ADX to weight trend bias, ensuring stronger signals in trending markets.
Momentum and Volume: Includes RSI momentum impulses and volume deviations for added confirmation.
Volatility Adjustment: Factors in ATR changes to assess market stability.
Customizable Inputs: Allows users to tweak periods for lookback, ADX, and ATR.
Decision Labels: Automatically classifies the MOS into actionable categories with visual labels.
This indicator is best suited for intraday or swing trading on volatile assets like stocks, forex, or cryptocurrencies. It does not generate buy/sell signals directly but can be combined with other tools (e.g., moving averages or oscillators) for comprehensive strategies.
Inputs
The script provides three user-configurable inputs via TradingView's input panel:
Lookback Period (lookback):
Type: Integer
Default: 20
Range: Minimum 10, Maximum 50
Purpose: Defines the number of bars used in slope calculations for trend analysis. A shorter lookback makes the indicator more sensitive to recent price action, while a longer one smooths out noise for longer-term trends.
ADX Period (adxPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Sets the smoothing period for the Average Directional Index (ADX) and its components (DI+ and DI-). Standard value is 14, but shorter periods increase responsiveness, and longer ones reduce false signals.
ATR Period (atrPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Determines the period for the Average True Range (ATR) calculation, which measures volatility. Adjust this to match your trading timeframe—shorter for scalping, longer for positional trading.
These inputs allow customization without editing the code, making the indicator adaptable to different market conditions or user preferences.
Core Calculations
The MOS is computed through a series of steps, blending trend, momentum, volume, and volatility metrics. Here's a breakdown:
Multi-Timeframe Slopes:
The script fetches data from higher timeframes (5m, 15m, 30m) using request.security.
Slope calculation: For each timeframe, it computes the linear regression slope of price over the lookback period using the formula:
textslope = correlation(close, bar_index, lookback) * stdev(close, lookback) / stdev(bar_index, lookback)
This measures the rate of price change, where positive slopes indicate uptrends and negative slopes indicate downtrends.
Variables: slope5m, slope15m, slope30m.
ATR (Average True Range):
Calculated using ta.atr(atrPeriod).
Represents average volatility over the specified period. Used later to derive volatility stability.
ADX (Average Directional Index):
A detailed, manual implementation (not using built-in ta.adx for customization):
Computes upward movement (upMove = high - high ) and downward movement (downMove = low - low).
Derives +DM (Plus Directional Movement) and -DM (Minus Directional Movement) by filtering non-relevant moves.
Smooths true range (trur = ta.rma(ta.tr(true), adxPeriod)).
Calculates +DI and -DI: plusDI = 100 * ta.rma(plusDM, adxPeriod) / trur, similarly for minusDI.
DX: dx = 100 * abs(plusDI - minusDI) / max(plusDI + minusDI, 0.0001).
ADX: adx = ta.rma(dx, adxPeriod).
ADX values above 25 typically indicate strong trends; here, it's normalized (divided by 50) to influence the trend bias.
Volume Delta (5m Timeframe):
Fetches 5m volume: volume_5m = request.security(syminfo.tickerid, "5", volume, lookahead=barmerge.lookahead_on).
Computes a 12-period SMA of volume: avgVolume = ta.sma(volume_5m, 12).
Delta: (volume_5m - avgVolume) / avgVolume (or 0 if avgVolume is zero).
This measures relative volume spikes, where positive deltas suggest increased interest (bullish) and negative suggest waning activity (bearish).
MOS Components and Final Calculation:
Trend Bias: Average of the three slopes, normalized by close price and scaled by 100, then weighted by ADX influence: (slope5m + slope15m + slope30m) / 3 / close * 100 * (adx / 50).
Emphasizes trends in strong ADX conditions.
Momentum Impulse: Change in 5m RSI(14) over 1 bar, divided by 50: ta.change(request.security(syminfo.tickerid, "5", ta.rsi(close, 14), lookahead=barmerge.lookahead_on), 1) / 50.
Captures short-term momentum shifts.
Volatility Clarity: 1 - ta.change(atr, 1) / max(atr, 0.0001).
Measures ATR stability; values near 1 indicate low volatility changes (clearer trends), while lower values suggest erratic markets.
MOS Formula: Weighted average:
textmos = (0.35 * trendBias + 0.25 * momentumImpulse + 0.2 * volumeDelta + 0.2 * volatilityClarity)
Weights prioritize trend (35%) and momentum (25%), with volume and volatility at 20% each. These can be adjusted in code for experimentation.
Trading Decision:
A variable mosDecision starts as "Neutral".
If mos > 0.15, set to "Long".
If mos < -0.15, set to "Short".
Thresholds (0.15 and -0.15) are hardcoded but can be modified.
Visualization and Outputs
Threshold Lines (using hline):
Long Threshold: Horizontal dashed green line at +0.15.
Short Threshold: Horizontal dashed red line at -0.15.
Neutral Line: Horizontal dashed gray line at 0.
These provide visual reference points for MOS interpretation.
Dynamic Labels (using label.new):
Placed at each bar's index and MOS value.
Text: Formatted MOS value (e.g., "0.2345") followed by a newline and the decision (e.g., "Long").
Style: Downward-pointing label with gray background and white text for readability.
This replaces a traditional plot line, showing exact values and decisions per bar without cluttering the chart.
The indicator appears in a separate pane below the main price chart, making it easy to monitor alongside price action.
Usage Instructions
Adding to TradingView:
Copy the script into TradingView's Pine Script editor.
Save and add to your chart via the "Indicators" menu.
Select a symbol and timeframe (e.g., 1-minute for intraday).
Interpretation:
Long Signal: MOS > 0.15 – Consider bullish positions if supported by other indicators.
Short Signal: MOS < -0.15 – Potential bearish setups.
Neutral: Between -0.15 and 0.15 – Avoid trades or wait for confirmation.
Watch for MOS crossings of thresholds for momentum shifts.
Combine with price patterns, support/resistance, or volume for better accuracy.
Limitations and Considerations:
Lookahead Bias: Uses barmerge.lookahead_on for multi-timeframe data, which may introduce minor forward-looking bias in backtesting (use with caution).
No Alerts Built-In: Add custom alerts via TradingView's alert system based on MOS conditions.
Performance: Tested for compatibility; may require adjustments for illiquid assets or extreme volatility.
Backtesting: Use TradingView's strategy tester to evaluate historical performance, but remember past results don't guarantee future outcomes.
Customization: Edit weights in the MOS formula or thresholds to fit your strategy.
This indicator distills complex market data into a single score, aiding decision-making while encouraging users to verify signals with additional analysis. If you need modifications, such as restoring plot functionality or adding features, provide details for further refinement.
MMA, Mid-Price Moving Averages (Open + Close Based MAs)📝 Script Description
This script introduces a custom set of moving averages based on the mid-price, calculated as the average of the open and close prices:
Mid Price = (Open + Close) / 2
Instead of traditional close-based MAs, this approach reflects the average sentiment throughout the trading session, offering a smoother and more realistic view of price action.
🔍 Key Features:
✅ Gap-aware smoothing
Captures opening gaps, offering a better representation of intraday shifts.
✅ Reduced noise
Less vulnerable to sharp closing moves or one-off spikes, making it easier to identify true trend breaks or supports.
✅ Closer to actual flow
Reflects a more natural midline of price movement, ideal for traders who prioritize clean, sustained trends.
✅ Better support/resistance alignment
Especially useful for identifying stable uptrends and minimizing false breakout signals.
📐 Included Moving Averages:
MA 5
MA 10
MA 20
MA 60
MA 120
MA 200
(All based on mid-price, not close)
🎯 Recommended For:
Traders seeking smoother and more reliable trendlines
Those who want a more realistic depiction of support and resistance
Ideal for filtering out noisy movements while focusing on clean, straight-moving charts
VWAP For Loop [BackQuant]VWAP For Loop
What this tool does—in one sentence
A volume-weighted trend gauge that anchors VWAP to a calendar period (day/week/month/quarter/year) and then scores the persistence of that VWAP trend with a simple for-loop “breadth” count; the result is a clean, threshold-driven oscillator plus an optional VWAP overlay and alerts.
Plain-English overview
Instead of judging raw price alone, this indicator focuses on anchored VWAP —the market’s average price paid during your chosen institutional period. It then asks a simple question across a configurable set of lookback steps: “Is the current anchored VWAP higher than it was i bars ago—or lower?” Each “yes” adds +1, each “no” adds −1. Summing those answers creates a score that reflects how consistently the volume-weighted trend has been rising or falling. Extreme positive scores imply persistent, broad strength; deeply negative scores imply persistent weakness. Crossing predefined thresholds produces objective long/short events and color-coded context.
Under the hood
• Anchoring — VWAP using hlc3 × volume resets exactly when the selected period rolls:
Day → session change, Week → new week, Month → new month, Quarter/Year → calendar quarter/year.
• For-loop scoring — For lag steps i = , compare today’s VWAP to VWAP .
– If VWAP > VWAP , add +1.
– Else, add −1.
The final score ∈ , where N = (end − start + 1). With defaults (1→45), N = 45.
• Signal logic (stateful)
– Long when score > upper (e.g., > 40 with N = 45 → VWAP higher than ~89% of checked lags).
– Short on crossunder of lower (e.g., dropping below −10).
– A compact state variable ( out ) holds the current regime: +1 (long), −1 (short), otherwise unchanged. This “stickiness” avoids constant flipping between bars without sufficient evidence.
Why VWAP + a breadth score?
• VWAP aggregates both price and volume—where participants actually traded.
• The breadth-style count rewards consistency of the anchored trend, not one-off spikes.
• Thresholds give you binary structure when you need it (alerts, automation), without complex math.
What you’ll see on the chart
• Sub-pane oscillator — The for-loop score line, colored by regime (long/short/neutral).
• Main-pane VWAP (optional) — Even though the indicator runs off-chart, the anchored VWAP can be overlaid on price (toggle visibility and whether it inherits trend colors).
• Threshold guides — Horizontal lines for the long/short bands (toggle).
• Cosmetics — Optional candle painting and background shading by regime; adjustable line width and colors.
Input map (quick reference)
• VWAP Anchor Period — Day, Week, Month, Quarter, Year.
• Calculation Start/End — The for-loop lag window . With 1→45, you evaluate 45 comparisons.
• Long/Short Thresholds — Default upper=40, lower=−10 (asymmetric by design; see below).
• UI/Style — Show thresholds, paint candles, background color, line width, VWAP visibility and coloring, custom long/short colors.
Interpreting the score
• Near +N — Current anchored VWAP is above most historical VWAP checkpoints in the window → entrenched strength.
• Near −N — Current anchored VWAP is below most checkpoints → entrenched weakness.
• Between — Mixed, choppy, or transitioning regimes; use thresholds to avoid reacting to noise.
Why the asymmetric default thresholds?
• Long = score > upper (40) — Demands unusually broad upside persistence before declaring “long regime.”
• Short = crossunder lower (−10) — Triggers only on downward momentum events (a fresh breach), not merely being below −10. This combination tends to:
– Capture sustained uptrends only when they’re very strong.
– Flag downside turns as they occur, rather than waiting for an extreme negative breadth.
Tuning guide
Choose an anchor that matches your horizon
– Intraday scalps : Day anchor on intraday charts.
– Swing/position : Month or Quarter anchor on 1h/4h/D charts to capture institutional cycles.
Pick the for-loop window
– Larger N (bigger end) = stronger evidence requirement, smoother oscillator.
– Smaller N = faster, more reactive score.
Set achievable thresholds
– Ensure upper ≤ N and lower ≥ −N ; if N=30, an upper of 40 can never trigger.
– Symmetric setups (e.g., +20/−20) are fine if you want balanced behavior.
Match visuals to intent
– Enabling VWAP coloring lets you see regime directly on price.
– Background shading is useful for discretionary reading; turn it off for cleaner automation displays.
Playbook examples
• Trend confirmation with disciplined entries — On Month anchor, N=45, upper=38–42: when the long regime engages, use pullbacks toward anchored VWAP on the main pane for entries, with stops just beyond VWAP or a recent swing.
• Downside transition detection — Keep lower around −8…−12 and watch for crossunders; combine with price losing anchored VWAP to validate risk-off.
• Intraday bias filter — Day anchor on a 5–15m chart, N=20–30, upper ~ 16–20, lower ~ −6…−10. Only take longs while score is positive and above a midline you define (e.g., 0), and shorts only after a genuine crossunder.
Behavior around resets (important)
Anchored VWAP is hard-reset each period. Immediately after a reset, the series can be young and comparisons to pre-reset values may span two periods. If you prefer within-period evaluation only, choose end small enough not to bridge typical period length on your timeframe, or accept that the breadth test intentionally spans regimes.
Alerts included
• VWAP FL Long — Fires when the long condition is true (score > upper and not in short).
• VWAP FL Short — Fires on crossunder of the lower threshold (event-driven).
Messages include {{ticker}} and {{interval}} placeholders for routing.
Strengths
• Simple, transparent math — Easy to reason about and validate.
• Volume-aware by construction — Decisions reference VWAP, not just price.
• Robust to single-bar noise — Needs many lags to agree before flipping state (by design, via thresholds and the stateful output).
Limitations & cautions
• Threshold feasibility — If N < upper or |lower| > N, signals will never trigger; always cross-check N.
• Path dependence — The state variable persists until a new event; if you want frequent re-evaluation, lower thresholds or reduce N.
• Regime changes — Calendar resets can produce early ambiguity; expect a few bars for the breadth to mature.
• VWAP sensitivity to volume spikes — Large prints can tilt VWAP abruptly; that behavior is intentional in VWAP-based logic.
Suggested starting profiles
• Intraday trend bias : Anchor=Day, N=25 (1→25), upper=18–20, lower=−8, paint candles ON.
• Swing bias : Anchor=Month, N=45 (1→45), upper=38–42, lower=−10, VWAP coloring ON, background OFF.
• Balanced reactivity : Anchor=Week, N=30 (1→30), upper=20–22, lower=−10…−12, symmetric if desired.
Implementation notes
• The indicator runs in a separate pane (oscillator), but VWAP itself is drawn on price using forced overlay so you can see interactions (touches, reclaim/loss).
• HLC3 is used for VWAP price; that’s a common choice to dampen wick noise while still reflecting intrabar range.
• For-loop cap is kept modest (≤50) for performance and clarity.
How to use this responsibly
Treat the oscillator as a bias and persistence meter . Combine it with your entry framework (structure breaks, liquidity zones, higher-timeframe context) and risk controls. The design emphasizes clarity over complexity—its edge is in how strictly it demands agreement before declaring a regime, not in predicting specific turns.
Summary
VWAP For Loop distills the question “How broadly is the anchored, volume-weighted trend advancing or retreating?” into a single, thresholded score you can read at a glance, alert on, and color through your chart. With careful anchoring and thresholds sized to your window length, it becomes a pragmatic bias filter for both systematic and discretionary workflows.
Trading Rules Panel BJTRADESFXA Simple Panel for Your Trading Rules
Trading can quickly get overwhelming if you’re juggling multiple strategies, indicators, and market conditions. A simple Trading Rules Panel on your chart helps you stay disciplined by keeping your strategy visible at all times. Instead of relying on memory or flipping through notes, the panel displays your personal trading checklist right where you need it — on your screen.
The panel can be customized to show:
✅ Entry conditions (e.g., trend direction, candle patterns, breakout levels)
✅ Exit rules (take profit, stop loss, or trailing stop logic)
✅ Risk management (lot size, max risk %, reward-to-risk ratio)
✅ Trading session reminders (only trade London/New York overlap, etc.)
✅ Personal rules (no revenge trading, stop after 2 losses, follow your plan)
This kind of panel doesn’t place trades for you; rather, it acts as a visual reminder to keep you consistent and accountable. It prevents emotional decisions and reinforces your discipline, especially during high-pressure moments.
A well-placed panel can also:
Reduce mistakes caused by forgetting steps
Keep your focus on the bigger picture
Improve backtesting and journaling since your rules are clearly visible
Help new traders stick to structure instead of chasing trades
Multi Ticker Price Percentage Change TrackerThis script is used to track percentage change of price of selected tickers and raise alert when it passes beyond certain threshold. It is useful for those who want to closely track a few selected tickers.
Composite TECH Line (Debug) – v0.2The Composite TECH Line is a multi-layered trading framework that blends RSI, MACD, and EMA logic into a single synthetic trend line. Instead of relying on one isolated indicator, this tool dynamically weights three complementary technical factors and creates a smoothed, adaptive signal line that aims to better capture momentum, mean-reversion, and exit dynamics.
🔹 Core Concept
Traditional technical indicators often generate conflicting signals. This script resolves that by:
Scoring RSI, MACD, and EMA individually across a 5-state classification system (from strongly bearish −2 to strongly bullish +2).
Assigning coefficients (customizable multipliers) to each state to quantify the strength of the signal.
Weighting the three indicators (RSI, MACD, EMA) and normalizing their contributions into a unified multiplier.
Synthesizing price by applying this multiplier to close price and smoothing it with an EMA filter.
The result is a Synthetic EMA-like Line, plotted alongside a reference EMA, that adapts its sensitivity based on the joint RSI-MACD-EMA context.
🔹 Technical Structure
1. RSI Layer
Uses fixed thresholds (30/40/60/70 by default).
Each RSI zone is mapped to a discrete state (oversold → neutral → overbought).
Multipliers (e.g., 0.90, 0.96, 1.00, 1.06, 1.12) adjust the contribution of RSI depending on regime.
2. MACD Layer
Evaluates both line polarity (above/below zero) and signal interaction (crossovers, histogram slope).
Produces five discrete states ranging from strong bearish to strong bullish.
Each state is mapped to tunable coefficients, allowing traders to calibrate aggressiveness.
3. EMA Layer (Dual Modes)
Ribbon Mode: Analyzes EMA21/EMA50/EMA100 stack alignment (trend-following).
Distance Mode: Evaluates deviation from a base EMA, normalized either by ATR or relative %.
Two policies: Mean-Revert (extremes expected to reverse) and Momentum (extremes expected to extend).
Produces a coefficient for incorporation into the composite multiplier.
4. Combination Layer
Weighted normalization ensures RSI, MACD, and EMA sum to ~1.
Produces mult_raw → clipped between a configurable Min/Max multiplier.
Final synthetic line = close × mult, smoothed by EMA.
🔹 Signal & Trade Logic
Buy Signal: Triggered when the synthetic line crosses under price with sufficient separation.
Exit System (multi-stage):
TP1 & TP2: Generated by combinations of mean-revert signals and ATR-based Chandelier triggers.
TSL (Trailing Stop): Activates after TP2, tracking new highs with a tighter ATR multiple until stopout.
One-Shot Gate: Prevents repeated signal spam by enforcing alternating buy/sell sequences.
Each event generates a distinct alert message (BUY, TP1, TP2, SL) for automated strategies or notifications.
🔹 Key Features
Unified RSI–MACD–EMA framework.
Configurable coefficients, thresholds, and smoothing.
Two EMA interpretation modes (trend ribbon vs. distance/ATR deviation).
Built-in multi-stage exit system with TP1, TP2, and trailing stops.
Clear labeling on chart + dedicated alert messages for automation.
Debug mode available for transparency of internal calculations.
🔹 Use Cases
As a trend-adaptive signal line for discretionary traders.
As a signal source for automated strategies (via alerts).
As an educational tool to understand how composite signals improve robustness over single indicators.
Disclaimer: This script is for educational and analytical purposes only. Past performance of any strategy or indicator is not a guarantee of future results. Always backtest thoroughly and use proper risk management.
Please subscribe to the weekly bulletin: www.patreon.com
samc's - Keltner OscillatorThe KELTNER CHANNEL is a widely used technical indicator developed in the 60's by Chester W. Keltner who described it in his 1960 book How To Make Money in Commodities.
so i took the logic, simplified the code and made into an oscillator.
to add a flavor of modern times you can choose among 10 different colorways themes in the settings. (so traders can adjust it for dark or light charts)
Although the initial idea was developed for stocks and commodities, I've carefully back tested this as an oscillator across FX MAJORS , MINORS and high liquidity stocks for the use case of scalping and Medium term trade ideas.
now, this indicator works successfully over all time frames, custom time frames and all assets.
This script builds on the same approach as my earlier session tool — keeping things clean, visual, and easy to read.
I intend to publish more of my work as i develop them from Beta ideas into stable scripts, and i welcome feedback.
RK RSI TIMEFRAME// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © rk2007
//@version=6
indicator("My script")
plot(close)
samc's FX SESSIONS - on candles So, based on my 8 yrs of experience and over a 2 decade worth of back testing on FX majors pairs one thing i can univocally affirm to the fact that Timing is everything especially in the currency markets.
so i made this indicator to help reduce the noise and focus on signals which is coded by time,
now i made this as GMT+8 in focus but you can adjust based on your requirements.
I classified my indicator colors according to the inter-SESSION High Impact areas only as following :
Primary session colors:
ASIAN - YELLOW
EU - BLUE
US - Magenta (light)
and every first 10 mins of the hour (Great for scalping)
i marked them in a shade of grey.
secondary sessions i marked them as minor sessions.
PRE-EU 1hr of expected trend i marked in color green
and
after hours in a shade of color violet.
so i usually make my candles into light grey by default and remove the body and wicks to minimize the visual stimulus so that this indicator will work great with both dark and light themes and does not obstruct other indicators.
also i made an option to uncheck my naming scheme of session on the top right.
Smart BOS & FVG Signal IndicatorDescription:
This script is designed to help traders identify high-probability trade setups using a combination of Break of Structure (BOS) detection, Fair Value Gaps (FVGs), and an EMA retest filter.
How It Works
Break of Structure (BOS): The indicator automatically detects BOS events when price takes out previous highs/lows. Users can choose between strict or equal-high/low comparisons with the Comparison Mode setting.
Fair Value Gaps (FVGs): Highlighted zones show areas of imbalance in price. You can choose whether signals require the FVG to still be open.
EMA Retest Filter: A dynamic EMA check confirms whether price retests a moving average after BOS, helping filter out weaker setups.
Trade Signals
Green Arrows (Buy Signals): Trigger when a bullish BOS aligns with FVG and EMA retest conditions.
Red Arrows (Sell Signals): Trigger when a bearish BOS aligns with FVG and EMA retest conditions.
Key Features
Toggle “Require FVG Still Open at Signal” for stricter setups.
Adjust BOS Comparison Mode between standard and allowEqual for different market structures.
Clean visualization: arrows and highlights mark where valid trade opportunities occur.
How to Use
Apply the indicator to your chart.
Use BOS + FVG confluence to spot continuation or reversal opportunities.
Filter signals with the EMA retest option to reduce noise.
Best paired with strong risk management and confirmation from your overall strategy.
Range Percent Histogram📌 Range Percent Histogram – Indicator Description
The Range Percent Histogram is a custom indicator that behaves like a traditional volume histogram, but instead of showing traded volume it displays the percentage range of each candle.
In other words, the height of each bar represents how much the price moved (in percentage terms) within that candle, from its low to its high.
🔧 What it shows
The indicator has two main components:
Component Description
Histogram Bars Columns plotted in red or green depending on the candle direction (green = bullish candle, red = bearish). The height of each bar = (high - low) / low * 100. That means a candle that moved, for example, 1 % from its lowest point to its highest point will show a bar with 1 % height.
Moving Average (optional) A 20-period Simple Moving Average applied directly to the bar values. It can be turned ON/OFF via a checkbox and helps you detect whether current range activity is above or below the average range of the past candles.
⚙️ How it works
Every time a new candle closes, the indicator calculates its range and converts it into a percentage.
This value is drawn as a column under the chart.
If the closing price is above the opening price → the bar is green (bullish range).
If the closing price is below the opening price → the bar is red (bearish range).
When the Show Moving Average option is enabled, a smooth line is plotted on top of the histogram representing the average percentage range of the last 20 candles.
📈 How to use it
This indicator is very helpful for detecting moments of range expansion or contraction.
One powerful way to use it is similar to a volume exhaustion / low-volume pattern:
Situation Interpretation
Consecutive bars with very low height Price is in a period of low volatility → possible accumulation or "pause" phase.
A sudden large bar after a series of small ones Indicates a strong pickup in volatility → often marks the start of a new impulse in the direction of the breakout.
ICT Killzones + HTF FVG [JewlsTagara]This indicator plots the high and low (h/l) of every kill
zone period included with HTF FVG's.
Best use;
- 15m, 30m, 1hr, 4h FVG
- Adjust lunch to end at 1:30pm EST and NYPM 17:00 EST
Strategy:
- When price sweeps kill zone h/l into/in a HTF FVG
- Enter a 1 - 3m iFVG.
- Target 1:1 or 1:2 RR
note: you make use whatever entry model you like.
9 Sequential for Stock Screener9 Sequential for Stock Screener. Use this to forecast the buy/sell signal for your stocks. It can be integrated into the stock screener to scan the stocks in the market. green arrow means buy signal, red arrow means sell signal.
ICT Killzones + HTF FVG [JewlsTagara]This indicator plots the hits and lows of every kill
zone period included with HTF FVG's.
Best use;
- 15m, 30m, 1hr, 4h FVG
- Adjust lunch to end at 1:30pm EST and NYPM 17:00 EST
Strategy:
- When price sweeps kill zone h/l into a HTF FVG
- Enter a 1 - 3m iFVG.
note: you make user whatever entry model you like.
Trading Macro Windows by BW v2
Trading Macros by BW: Integrating ICT Concepts for Session Analysis
This indicator combines two key Inner Circle Trader (ICT) concepts—Change in State of Delivery (CISD) or Inverted Fair Value Gap (IFVG) signals with Macro Time Windows—to provide a unified tool for analyzing intraday price action, particularly during Pacific Time (PT) sessions. Rather than simply merging existing scripts, this integration creates a cohesive visual framework that highlights how macro consolidation periods interact with potential reversal or continuation signals like CISD or IFVG. By overlaying macro candle styling and borders on the chart alongside selectable signal lines, traders can better contextualize setups within ICT's macro narrative, where price often manipulates liquidity during these windows before displacing toward higher-timeframe objectives.
Core Components and How They Work Together:
Macro Time Windows (Inspired by ICT's Macro Periods):
ICT emphasizes "macro" as 30-minute windows (e.g., 06:45–07:15 PT, 07:45–08:15 PT, up to 11:45–12:15 PT) where price tends to consolidate, sweep liquidity, or form key structures like Fair Value Gaps (FVGs). These periods set the stage for the session's directional bias.
The indicator styles candles within these windows using a user-defined color for wicks, borders, and bodies (translucent for visibility). This visual emphasis helps traders focus on activity inside macros, where reversals or continuations often originate.
Borders are drawn as vertical lines at the start and end of each window (with a +5 minute buffer to capture related activity), using a dotted style by default. This creates a "study zone" that encapsulates macro events, allowing traders to assess if price is respecting or violating these zones in alignment with broader ICT models like the Power of 3 (AMD cycle).
Toggle: "Macro Candles Enabled" (default: true) – Turn off to disable styling and borders if focusing solely on signals.
CISD or IFVG Signals (Selectable Mode):
Mode Selection: Choose between "Change in the State of Delivery" (CISD) or "IFVG" (default: IFVG). Both detect shifts in market delivery during specific 30-minute slices (15–45 or 17–45 minutes past the hour in PT sessions).
CISD Mode: Based on ICT's definition of a sudden directional shift, this identifies aggressive displacements after sweeping recent highs/lows. It uses a rolling reference high/low over 6 bars, checks for sweeps (penetrating by at least 2 ticks in the last 2-3 bars), reclamation (closing beyond the reference with at least 50% body), and displacement (50% of prior range or an immediate FVG of 6+ ticks). Signals plot a horizontal line from the close, extending 24 bars right, labeled "CISD."
IFVG Mode: Focuses on Inverted Fair Value Gaps, where a bullish FVG (low > high by 13+ ticks) forms but is inverted (closed below) in the same slice, signaling bearish intent (or vice versa). This targets violations against opposing liquidity, often leading to raids on external ranges. Signals plot similarly, labeled "IFVG."
Shared Logic: Both modes enforce a 55-bar cooldown to prevent clustering, operate only during PT sessions (06:30–13:00), and use tick-based thresholds for precision across instruments. The integration with macros allows traders to see if signals occur within or at the edges of macro windows, enhancing confirmation—for example, a CISD inside a macro might indicate a manipulated reversal toward the session's true objective.
Toggle: "Signals Enabled" (default: true) – Turn off to hide all signal lines and labels, isolating the macro visualization.
How Components Interact:
Macro windows provide the "narrative context" (consolidation/manipulation), while CISD/IFVG signals detect the "delivery shift" (displacement). Together, they form a mashup that justifies publication: isolated signals can be noisy, but when filtered by macro periods, they align with ICT's session model. For instance, an IFVG inversion during a macro might confirm a liquidity sweep before targeting PD arrays or order blocks.
No external dependencies; all calculations are self-contained using Pine's built-in functions like ta.highest/lowest for references and time-based sessions for windows.
Usage Guidelines:
Apply to intraday charts (e.g., 1-5 min) or stocks during PT hours.
Look for confluence: A bull IFVG signal post-macro low sweep might target the next macro high or daily bias.
Customize colors/styles for signals (solid/dashed/dotted lines) and macros to suit your chart.
Backtest in replay mode to observe how macros frame signals—e.g., price often respects macro borders as S/R.
Limitations: Timezone-fixed to PT (America/Los_Angeles); signals are directional hints, not trade entries. Combine with ICT tools like order blocks or liquidity pools for full setups.
This script draws from community ICT implementations but refines them into a single, purpose-built tool for macro-driven trading, reducing chart clutter while emphasizing interconnected concepts. Feedback welcome!
Volatility Squeeze (Bollinger BW + 16 SMA + 8 EMA of 16 SMA )Can't take any credit for this, thank you Steve Strazza for putting me on to this