Support & Resistance Automated📌 Support and Resistance Automated (Pivot-Based)
Support and Resistance Automated is a lightweight and fully automated indicator that plots key support and resistance levels using pivot highs and pivot lows. It helps traders quickly identify important price reaction zones without manual drawing.
This indicator is especially useful for price-action traders, swing traders, and intraday traders who rely on clean charts and objective levels.
🔍 How It Works
Pivot Highs → Resistance Levels
Pivot Lows → Support Levels
Each detected pivot creates a horizontal dotted line that extends forward, allowing you to observe how price reacts over time.
Once a level is formed, it is kept permanently on the chart — no repainting, no disappearing levels.
⚙️ Customizable Settings
You can easily adjust:
Left & Right Pivot Bars – control how strong a pivot must be
Line Extension Length
Line Width
Support & Resistance Colors
Show / Hide Pivot Highs and Pivot Lows independently
This flexibility allows the indicator to adapt to intraday, swing, or higher-timeframe analysis.
✅ Key Features
✔ Fully automatic support & resistance detection
✔ Based on proven pivot-point logic
✔ No repainting
✔ Clean, minimal chart appearance
✔ Unlimited support & resistance levels
✔ Works on all timeframes & instruments
📈 Best Use Cases
Identifying key demand and supply zones
Planning entries, targets, and stop-losses
Confluence with price action, RSI, moving averages
Breakout and rejection-based strategies
インジケーターとストラテジー
Value Area PRO (TPO/Volume Session VAH/VAL/POC) 📌 AP Capital Value Area PRO (TPO / Volume)
AP Capital Value Area PRO is a session-based value area indicator designed for Gold (XAUUSD), NASDAQ (NAS100), and other CFD instruments.
It focuses on where the market has accepted price during the current session and highlights high-probability interaction zones used by professional traders.
Unlike rolling lookback volume profiles, this indicator builds a true session value area and provides actionable signals around VAH, VAL, and POC.
🔹 Core Features
Session-Anchored Value Area
Value Area is built only during the selected session
Resets cleanly at session start
Levels develop during the session and can be extended forward
No repainting or shifting due to lookback changes
TPO or Volume Mode
TPO (Time-at-Price) mode – ideal for CFDs and tick-volume data
Volume mode – uses broker volume if preferred
Same logic, different weighting method
Fixed Price Bin Size
Uses a fixed bin size (e.g. 0.10 for Gold, 0.25–0.50 for NAS100)
Produces cleaner, more realistic VAH/VAL levels
Avoids distorted profiles caused by dynamic bin scaling
VAH / VAL / POC Levels
VAH (Value Area High)
VAL (Value Area Low)
POC (Point of Control) (optional)
Lines can be extended to act as forward reference levels
🔹 Trading Signals & Alerts
Value Re-Entry
Identifies false breakouts where price:
Trades outside value
Then closes back inside
Often seen before strong mean-reversion or continuation moves.
Acceptance
Detects initiative activity using:
Multiple consecutive closes outside value
Filters out weak single-candle breaks
Rejection
Flags strong rejection candles:
Large candle body
Wick outside value
Close back inside the value area
These conditions are especially effective on Gold intraday.
🔹 Optional Profile Histogram
Right-side volume/TPO histogram
Buy/sell imbalance visualization
Fully optional to reduce chart clutter and improve performance
🔹 Best Use Cases
Recommended markets
XAUUSD (Gold)
NAS100 / US100
Other index or metal CFDs
Recommended timeframes
5m, 15m, 30m
Suggested settings
Mode: TPO
Value Area: 70%
Bin size:
Gold: 0.10
NAS100: 0.25 or 0.50
🔹 How Traders Use It
Trade rejections at VAH / VAL
Look for acceptance to confirm trend days
Use re-entries to fade failed breakouts
Combine with trend filters, EMA structure, or session context
⚠️ Disclaimer
This indicator is provided for educational and analytical purposes only and does not constitute financial advice. Always manage risk appropriately.
Session VWAP Cumulative BiasThe Session VWAP Cumulative Bias indicator is designed to differentiate between "choppy" price action and true "institutional" trend days. Unlike standard VWAP indicators that only show where price is now, this tool tracks the cumulative sentiment of the entire session.
Core Functions:
Cumulative Z-Score Logic: It calculates the distance between price and VWAP (in Standard Deviations) and sums it up over the course of the day. This reveals the "weight" of the market bias—the longer price stays pinned away from the VWAP, the more extreme the histogram becomes.
Scale Protection: It includes a "Capping" mechanism that prevents morning gaps or low-volume outliers from distorting the scale, ensuring the histogram remains readable from open to close.
Momentum vs. Regime Toggles: Users can switch between VWAP Slope (measuring the speed of the average's movement) and Cumulative Bias (measuring total session dominance).
Visual price Overlay: It automatically colors the price candles and plots a session-anchored VWAP line on the main chart, providing a clear visual of when price is "fair" versus "overextended."
How to read it:
Trend Confirmation: A steadily growing "mountain" in the histogram confirms an institutional trend day where dips are being bought (or rips sold).
Mean Reversion: When price hits a new high but the Cumulative Histogram begins to round off or diverge, it signals that the "elastic band" is stretched and price is likely to return to the orange VWAP line.
Regime Shifts: A cross of the zero-line on the histogram indicates a total shift in session control from buyers to sellers (or vice versa).
4 Period Momentum Composite IndicatorThe 4‑Period Momentum Indicator blends four lookback windows (1m, 3m, 6m, 12m) into a single zero‑centered momentum line. The value recalculates from whatever candle you anchor on, giving you full control when scrolling through historical price action. Positive readings reflect upward momentum, negative readings show weakness, and zero‑line crossovers highlight potential trend shifts. Designed for multi‑timeframe use and ETF relative‑strength comparison.
Auto Fib Prev-Week Only for [4H+ Swing]Maps the previous week Fib levels:
Captures real supply & demand.
Defines where price was accepted or rejected.
Creates levels that current price must respect.
This indicator locks those levels in place and extends them forward.
What the levels represent:
- Previous Week High / Low
- Major boundaries. Breaks require momentum.
- 50% Level
- Balance point. Chop and indecision are common here.
- 61.8% Levels (Bull & Bear)
- Primary mean-reversion zones.
- Most reliable reaction levels.
- 78.6% Levels
- Last defense before trend failure or expansion.
- Extensions (1.214 → 2.618 / negatives)
- Exhaustion and target zones.
Working....
Dashboard (bottom-right)
- Nearest Sup / Res – Closest actionable level
- On Level? – Price is currently reacting at a level
- UpBreak% / DnBreak% – Probability of breaking vs rejecting
- Bias – Market posture (UP / DOWN / NEUTRAL)
- Tol – Sensitivity used for level detection
BLUF: Maps last week’s structure forward to identify high-probability reaction zones and whether price is more likely to revert or break.
Relative Strength SpreadSPY vs IWM Relative Strength Spread Indicator
The SPY vs IWM Relative Strength Spread indicator measures leadership between large-cap and small-cap equities by comparing the percent performance of SPY (S&P 500) against IWM (Russell 2000) over a user-defined lookback period.
The indicator plots a zero-centered histogram in a separate pane, making relative strength shifts immediately visible.
How It Works
The indicator calculates the percent change of SPY and IWM over the same lookback window.
It then subtracts IWM’s percent change from SPY’s percent change.
The result is plotted as a histogram pinned to the 0% line.
This design removes long-term drift and ensures that:
Positive values indicate SPY is outperforming IWM
Negative values indicate IWM is outperforming SPY
How to Read the Histogram
Above Zero (Green Bars)
Large-cap stocks are leading → typically associated with risk-on stability and institutional flow into SPY-weighted names.
Below Zero (Red Bars)
Small-cap stocks are leading → often signals risk appetite expansion and speculative participation.
Crosses of the Zero Line
Mark potential leadership transitions between large caps and small caps.
Why This Indicator Is Useful
Identifies market regime shifts (risk-on vs risk-off behavior)
Confirms or filters trend strength in equities
Helps time rotations between large-cap and small-cap exposure
Works consistently across all timeframes
Because the calculation is based on percent change, the histogram remains normalized and comparable regardless of price level or timeframe.
Best Use Cases
As a market internals / breadth confirmation tool
As a bias filter for SPY, IWM, or index futures
To spot early leadership changes before price trends fully develop
John Trade AlertsImagine you are watching a ball bounce up and down on a graph.
This script is like a set of rules that says:
When to start playing
When to stop playing
When you got some prize levels
and it yells to you (alerts) when those things happen.
The main ideas
Breakout Buy (ball jumps high)
There is a line drawn high on the chart called the breakout level.
If the price (the ball) closes above that line, and some extra “good conditions” are true (enough volume, uptrend, etc.),
the script says: “We entered a Breakout trade now.”
Pullback Buy (ball dips into a box)
There is a zone (a small box) between a low line and a high line: the pullback zone.
If the price closes inside that zone, and the pullback looks “healthy” (not too much volume, still above a moving average, etc.),
the script says: “We entered a Pullback trade now.”
Stops (when to get out if it goes wrong)
For each entry type (Breakout or Pullback), there is a red stop line under the price.
If the price falls below that stop line, the script says:
“Stop hit, we’re out of the trade.”
Hard Support / Invalidation (big no‑no level)
There is a special hard support line.
The script also looks at the 1‑hour chart in the background.
If a 1‑hour candle closes below that hard support, it says:
“Hard invalidation – idea is broken, get out.”
Targets (prize levels)
Above the current price there are several orange lines: Target 1, 2, 3A, 3B, 4A, 4B.
If the price goes up and crosses one of these lines, the script says:
“Target X reached!”
Trend and Volume “health checks”
It checks if the short‑term average price (SMA20) is going up → “uptrend.”
It can check if price is above a long‑term average (SMA200).
For breakouts, it checks if volume is stronger than usual (good push).
For pullbacks, it prefers quieter than usual volume (calm dip).
It can also check an Anchored VWAP line (a special average price from a chosen starting time) and only trade if price is above that too.
Remembering if you are “in a trade”
The script keeps a little memory:
Are we currently in a position (inPos) or not?
Was it a Breakout or a Pullback entry?
What is our entry price and active stop?
When it gets a new entry signal, it turns inPos to true, picks the right stop, and draws that stop line.
When a stop or hard invalidation happens, it sets inPos to false again.
It can also “forget” and reset at the start of a new trading day if you want.
Alerts
When:
you get a Breakout entry
or a Pullback entry
or a Stop is hit
or the hard support is broken on 1‑hour
or a Target is reached
the script sends a message you can use in TradingView alerts (pop‑ups, email, webhook, etc.).
Things you see on the chart
Teal line: Breakout level
Green lines: Pullback zone low & high
Red line: Active stop (only when you’re “in” a trade)
Orange lines: Targets 1, 2, 3A, 3B, 4A, 4B
Blue line: Anchored VWAP (if you turn it on)
Purple faint line: SMA20 (short‑term trend)
Gray faint line: SMA200 (long‑term trend)
Little label near the last bar that says:
if you’re IN or Flat
which type of entry (Breakout/Pullback)
what your current stop is
So in kid words:
It draws important lines on the chart.
It watches the price move like a ball.
When the ball does something special (jump above, fall below, hit a prize line),
it shouts to you with alerts.
It remembers if you’re in the game or not, and where your safety line (stop) is.
Daily Inputs - The Prometheus InitiativeDaily ES inputs from the Prometheus Initiative is a clean, customizable overlay indicator designed specifically for ES (S&P 500 E-mini futures) day traders who rely on manually selected key price levels each session.
Instead of spending time manually drawing horizontal lines every day, this tool lets you quickly input the daily price levels directly in the settings and instantly see them plotted as horizontal lines across your chart.
Key Features:
• 15 fully editable price inputs with customizable settings.
Why this indicator was created:
Manually drawing 10–15 lines each morning is time-consuming. This indicator was developed to eliminate that friction — allowing fast, accurate plotting of levels so you can focus on execution rather than drawing tools. The largest benefit is that you can toggle the indicator on/off to keep a clean chart as to not interfere with your existing visual levels.
Perfect for:
- ES / NQ futures traders
- Anyone who wants a clean, no-nonsense way to visualize custom horizontal levels
How to use:
1. Add to your chart
2. Open Settings → Enter the daily levels provided
3. Watch price interact with the levels!
Note: This is a manual input tool. Levels do NOT auto-calculate. It's meant to reflect the exact levels posted each day.
Happy trading! 📈
Feel free to leave feedback or suggestions in the comments.
Disclaimer: This indicator is for educational/visual purposes only. Trading futures involves substantial risk of loss and is not suitable for all investors.
Dynamic Zone TraderDynamic Zone Trader - MACD-based trading system with adaptive stop loss and take profit zones.
This indicator generates buy/sell signals from MACD histogram crossovers and automatically adjusts position sizing based on market conditions.
Key Features:
Detects breakout trades and expands targets to capture larger moves
Identifies choppy/ranging conditions and tightens stops to reduce risk
Shows supply and demand zones based on pivot highs/lows
Displays three take profit levels (TP1, TP2, TP3) that scale with trade quality
Entry signals filtered by 50 EMA to trade with the trend
Signal strength score displayed on each entry marker
How It Works:
The indicator analyzes recent price structure and movement to classify each trade:
Breakout trades (breaking recent highs/lows) get 1.6x larger zones
Normal trades get standard 1.0x sizing
Choppy weak signals get 0.75x smaller zones
This allows you to take bigger positions on high-conviction setups while limiting risk during low-quality trades.
Settings:
MACD parameters (default 8/21/5)
Base stop loss: 60 ticks
Base take profit: 80 ticks
EMA filter: 50 period
Optional ADX trend filter
Adjustable breakout detection sensitivity
Works on any timeframe and instrument, but optimized for index futures like NQ/MNQ.
RSI Swing Indicator// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
//
// DESCRIPTION:
// This is an improved version of the original RSI Swing Indicator created by BalintDavid.
// It highlights swing moves between RSI overbought/oversold extremes and updates swing labels
// as price pushes to new highs or lows inside the same RSI regime.
//
// HOW TO USE:
// 1) Set the RSI source, length, and overbought/oversold levels in Inputs.
// 2) Watch the swing lines connect the last oversold to overbought (and vice-versa).
// 3) Labels show structure: HH (higher high), LH (lower high), HL (higher low), LL (lower low).
// 4) Enable "Show only last connecting line" to keep just the most recent connection.
//
// CONTACT:
// ronbelson@gmail.com
//
Week High/LowThis indicator plots the Previous Week High and Low as two horizontal dashed lines.
It is designed to appear only on the Daily (D) and Weekly (W) timeframes, ensuring a clean higher-timeframe context without lower-timeframe noise.
The levels are calculated from the completed weekly candle and automatically update at the start of each new week.
These levels serve as weekly liquidity references, commonly used to assess premium/discount zones, potential stop-run areas, and higher-timeframe market reactions.
Chart This in GoldProduces a historical line chart in the bottom pane to reflect how many units of spot gold (XAU) could be exchanged for one unite of the underlying asset.
HTB Reversal Pattern - RSI DivergenceHow this Script Works
Pivot Points: The script looks for "peaks" and "valleys" in the RSI indicator.
Divergence Logic: * Bullish: If the current price low is lower than the previous low, but the RSI low is higher than the previous RSI low, it indicates the selling pressure is fading despite the price drop.
Bearish: If the current price high is higher than the previous high, but the RSI high is lower than the previous RSI high, it suggests buying momentum is weakening.
The "Lookback" Offset: Because pivot points require a few bars to the right to be confirmed (defined by lbR), the labels will appear on the chart with a small delay (default is 5 bars). This is necessary to prevent "repainting" (signals that disappear after they appear).
Smart Scalper Pro Template + VWAP
📌 Author
Garry Evans
Independent system developer focused on:
Risk-first automation
Market structure & liquidity behavior
Discipline, consistency, and capital preservation
“The edge isn’t the market — it’s the man who survives it.”
⚙️ Risk Management & Position Sizing
The script is built around capital protection, not signal frequency.
Risk logic includes:
Fixed or dynamic risk per trade
Market-adaptive position sizing
Session-based trade limits
Daily trade caps and auto-lockout protection
Volatility-aware sizing (futures & crypto)
⚠️ Profit is pursued only after risk is controlled.
📊 Track Record
Backtested across multiple market environments
Forward-tested and actively used by the author
Real-account trades are logged where platform rules allow
Results vary by market, timeframe, and user-defined risk settings.
🌍 Supported Markets
Designed to work across all liquid markets, including:
Stocks
Crypto (spot & futures)
Options (signal-based framework)
Futures (indices, metals, crypto futures)
The system adapts to volatility and structure — it is not market-specific.
⚖️ Leverage
Leverage is not required
If used, leverage is fully user-controlled
Risk logic scales exposure conservatively
No martingale.
No revenge sizing.
No over-exposure logic.
🧪 Backtesting
✔ Yes
Strategy logic has been backtested
Filters reduce chop, noise, and forced trades
Focus on drawdown control over curve-fitting
🛠 Support
✔ Yes
Direct author support
Ongoing improvements and updates
Feature refinement based on real usage and feedback
👥 Community
✔ Yes
Private user access
High-quality feedback environment
No public signal spam or hype-driven chat rooms
⏳ Trial Period
✔ Yes
Limited trial access available
Designed for evaluation only
Trial users do not receive full feature access
🚫 Who This Script Is NOT For
This system is not for:
Traders looking for guaranteed profits
Users expecting copy-paste “signal calls”
Over-leveraged gamblers
Those unwilling to follow risk rules
Anyone seeking overnight results
This is a discipline and automation tool, not a shortcut.
🧠 Final Positioning
This is not a signal service.
This is a risk-controlled execution framework designed to:
Enforce discipline
Reduce emotional trading
Protect capital during bad market conditions
Scale responsibly during favorable ones
Risk Manager & ATR TS Strategy📌 Overview
This script is not a simple indicator mashup. It is a Risk & Trade Planning Engine that combines a strategy-based signal generator with a snapshot-based risk, sizing, and expectancy model. It is designed to support real trading decisions, not just to generate cosmetic signals or overfitted backtests.
The core idea is to separate market logic from risk logic, evaluating each trade only at the moment it becomes actionable using fixed reference points that do not change afterward.
🎯 What makes this script original Unlike most tools that merely combine indicators or visualize entries, this script introduces several non-standard design choices:
Snapshot-based risk sizing (The "Time Machine" logic).
Expected Value (EV) calculation in both Money and R-multiples.
Kelly Criterion applied with weighted multi-target logic.
Strict architectural separation between the signal engine and the risk engine.
Decision-oriented dashboard instead of decorative plots.
These components are not merged for convenience; they are architecturally dependent on each other.
🧠 Conceptual Architecture
1️⃣ Signal Engine (Market Context) The signal engine is based on an ATR Trailing Stop system combined with trend regime filters (ADX and Choppiness Index). Its only responsibility is to answer one question: "Is this a valid directional opportunity right now?" It does not manage risk; it only identifies the opportunity.
2️⃣ Snapshot Logic (Key Design Choice) When a valid signal occurs, the script captures a Snapshot of the Entry price, Initial Stop-Loss, and Risk Distance. This snapshot is frozen at signal time. It is never updated, even if the trailing stop moves later. This avoids the most common error in TradingView scripts: recalculating position size using a moving stop, which falsifies the risk data.
3️⃣ Risk Engine (Sizing & Control) Using the snapshot values, the script computes:
Monetary risk per trade (capped at your user-defined max).
Position size derived from the fixed stop distance.
Effective leverage (informational).
4️⃣ Multi-Target Reward Model Instead of assuming a single take-profit, the script supports multiple targets with user-defined probability weights. From this, it derives a Weighted Risk/Reward Ratio, which feeds directly into the EV and Kelly calculations.
5️⃣ Expected Value (EV) in Money & R The script calculates EV in your account currency (real impact) and normalized in R-multiples (statistical quality). This allows you to compare trade quality across different assets and timeframes objectively.
6️⃣ Kelly Criterion (Conservative) The Kelly Criterion is applied using the weighted reward model and is always subordinated to your hard risk cap. If Kelly suggests a negative value, the script advises "NO TRADE". It is used as a filter, not a leverage amplifier.
📊 Dashboard & Alerts The on-chart dashboard summarizes everything you need at the moment of the signal:
Risk % and Position Size
Expected Value (Money + R)
Kelly Suggestion
Signal Strength
Alerts are triggered once per signal (on bar close) using snapshot data, ensuring no repainting and no spam.
🔍 How this is NOT a mashup Each component exists because another component depends on it. Snapshot logic is required for valid risk sizing; Risk sizing is required for EV normalization; Weighted RR is required for meaningful Kelly. Removing any part breaks the system’s logic.
📘 How to use
Choose your account size and risk parameters in the settings.
Configure your stop logic and reward targets.
Wait for a valid signal.
Evaluate the dashboard: Decide if the trade quality (EV, R, Risk) justifies participation.
⚖️ Open-Source Notice This script is published under the Mozilla Public License 2.0 (MPL-2.0). It does not copy or replicate any single public script. Standard concepts (ATR, ADX) are used as building blocks, but the architecture and calculations are original.
🚫 Disclaimer This script is a planning and evaluation engine designed to help traders think in terms of risk, expectancy, and discipline. It does not guarantee profitability.
✅ Summary This is a professional-grade framework built to answer one core question: “Is this trade worth taking, given my risk and my expectations?” Not every signal is a trade, and not every trade deserves capital. This script helps you make that distinction.
DayTradeMind Combined High Win Rate StrategyThe DayTradeMind Combined High Win Rate Strategy is a trend-following system that relies on confluence—the idea that a trade signal is stronger when multiple independent indicators agree. Instead of entering on a single indicator's whim, it uses a "voting" system to qualify entries and a strict risk-to-reward ratio to manage exits.Here is a breakdown of the three main layers of this strategy:1. The Voting Engine (Confluence Model)The strategy tracks four indicators and assigns a "point" for a bullish or bearish bias. It requires a minimum number of points (set by minConfirmations, usually 2/4) before it even considers a trade.IndicatorBullish Condition (1 point)Bearish Condition (1 point)PurposeMACDMACD Line > Signal LineMACD Line < Signal LineMeasures short-term momentum.DonchianPrice > 20-period MedianPrice < 20-period MedianIdentifies price relative to recent range.SuperTrendPrice above trend linePrice below trend lineFilters for the "Macro" trend direction.%B (Bollinger)Price in lower-mid range (0.2–0.5)Price in upper-mid range (0.5–0.8)Prevents buying when overextended.2. The Entry TriggerHaving enough "votes" (confirmations) isn't enough to enter. The strategy waits for a trigger event to ensure you aren't entering a stale trend. An entry only occurs if the minimum confirmations are met AND one of the following happens on the current bar:MACD Cross: The MACD line crosses over the signal line.Structural Break: The price crosses over the Donchian Middle (Median) line.This "Confirmation + Trigger" approach is designed to catch the start of a momentum push rather than buying a flat market.3. Mathematical Risk ManagementThe performance you see in your backtest (like the 46.86% return) is largely driven by the 2:1 Reward-to-Risk (RR) Ratio.Stop Loss (SL): Fixed at 2% below entry.Take Profit (TP): Fixed at 4% above entry.By aiming for a target twice as large as the risk, the strategy can remain profitable even with a win rate as low as 35%–40%. Mathematically, your winning trades compensate for more than two losing trades.Visualizing the SystemTriangles: Small green (up) and red (down) triangles appear on your chart only when the Votes + Trigger align perfectly.Background Shading: Faint green or red bands show you exactly when the "Confluence" is active. If the background is gray, the indicators are in conflict.Dashboard: The table in the top-right summarizes the current "score" for each indicator, letting you know how close you are to a potential trade signal.
Auto Fibonacci Lines Depending on ZigZag %In the world of technical analysis, few tools are as powerful—or as misused—as Fibonacci Retracements. The Auto Fibonacci Lines Depending on ZigZag % is not just an indicator; it is a complete, automated trading system designed to eliminate subjectivity and bring institutional-grade precision to your charts.
This script automates the identification of significant market structures using a ZigZag algorithm. Once a market swing is mathematically confirmed (based on your deviation settings), it instantly projects a complete suite of Retracement and Extension levels. This allows you to stop guessing where to draw your lines and start focusing on price action.
🧠 The Logic Behind the Indicator
Understanding how your tools work is the first step to trusting them. This script operates on a three-step logic loop:
ZigZag Identification:
The script continuously monitors price action relative to the last known pivot point. It uses a user-defined Deviation % to filter out market noise. A new "Leg" is only confirmed when price reverses by this specific percentage. This ensures that the Fibonacci lines are only drawn on significant market moves, not random chop.
Automated Anchor Points:
Once a downward trend is confirmed (e.g., price drops 30% from the top), the script automatically anchors the Fibonacci tool to the Swing High (Start) and the Swing Low (End). It does this without you needing to click or drag anything.
Dynamic Cleanup:
Markets evolve. A key feature of this script is its self-cleaning mechanism. As soon as a new trend leg is confirmed, the script automatically deletes the old, invalidated Fibonacci lines and draws a fresh set for the new structure. This keeps your chart clean and focused on the now.
🎓 How to Trade This System
This indicator is color-coded to simplify your decision-making process. It moves beyond standard "rainbow" charts by categorizing price levels into three distinct actionable zones.
1. The "Reload Zone" (White Lines: 0.618 - 0.786) ⚪
Role: High-Probability Support / Entry
In institutional trading, the 0.618 (Golden Ratio) to 0.786 region is often where algorithms step in to defend a trend.
Why it works : This is the "discount" area where smart money re-accumulates positions before the next leg up.
2. The "Decision Wall" (Blue Lines: 1.382 - 1.5) 🔵
Role: Strong Resistance / Trend Check
This is a unique feature of this suite. The 1.382 and 1.5 levels often act as a "ceiling" for weak breakouts.
Strategy : If you entered in the White Zone, the Blue Zone is your first major hurdle. If price stalls here, consider securing partial profits.
Warning : A rejection from the Blue Lines often leads to a double-top formation. However, a clean break above the Blue Lines usually signals a parabolic move is beginning.
3. The "Extension Zone" (Yellow, Red, Purple > 1.618) 🟡🔴
Role : Take Profit / Exhaustion
Levels above 1.5 (starting with the 1.618 Golden Extension) are statistical extremes.
Strategy : These are Strict Take Profit levels. Do not FOMO (Fear Of Missing Out) into new long positions here. The probability of a reversal increases drastically as price climbs through these levels (2.618, 3.618, 4.618).
📐 The Mathematical Edge: Logarithmic vs. Linear
One of the most critical features of this script is the ability to toggle between Logarithmic and Linear calculations.
Why use Logarithmic?
If you are trading Crypto (Bitcoin, Altcoins) or high-growth Tech Stocks, linear Fibonacci levels are mathematically incorrect over large moves. A 50% drop from $100 is different than a 50% drop from $10.
This script calculates the percentage difference (Log Scale), ensuring your targets are accurate even during 100%+ parabolic runs.
Why use Linear?
For mature markets like Forex (EURUSD) or Indices (SPX500) where volatility is lower, Linear scaling is the industry standard.
🛠️ Configuration & Best Practices
Deviation % : This is the heartbeat of the indicator.
Swing Trading : Set to 20-30%. This filters out noise and only draws Fibs on major macro moves.
Scalping : Set to 3-5%. This will catch smaller intraday waves.
Text Place : Keeps your chart clean by pushing labels to the right, ensuring they don't overlap with the current price action.
👤 Who Is This Indicator For?
The Disciplined Trader : Who wants to remove emotional bias from their charting.
The Crypto Investor : Who needs accurate Logarithmic targets for long-term holding.
The Confluence Trader : Who combines these automated levels with Order Blocks, RSI, or Volume to find the perfect entry.
⚠️ RISK DISCLAIMER & TERMS OF USE
For Educational Purposes Only:
This script and the strategies described herein are provided strictly for educational and informational purposes. They do not constitute financial, investment, or trading advice. The "Auto Fibonacci Lines" indicator is a tool for technical analysis and should not be used as the sole basis for any trading decision.
No Guarantees:
Past performance of any trading system or methodology is not necessarily indicative of future results. Financial markets are inherently volatile, and trading involves a high level of risk. You could lose some or all of your capital.
User Responsibility:
By using this script, you acknowledge that you are solely responsible for your own trading decisions and risk management. The author assumes no liability for any losses or damages resulting from the use of this tool or the information provided. Always consult with a qualified financial advisor before making investment decisions.
MLMatrixLibOverview
MLMatrixLib is a comprehensive Pine Script v6 library implementing machine learning algorithms using native matrix operations. This library provides traders and developers with a toolkit of statistical and ML methods for building quantitative trading systems, performing data analysis, and creating adaptive indicators.
How It Works
The library leverages Pine Script's native matrix type to perform efficient linear algebra operations. Each algorithm is implemented from first principles, using matrix decomposition, iterative optimization, and statistical estimation techniques. All functions are designed for numerical stability with careful handling of edge cases.
---
Library Contents (34 Sections)
Section 1: Utility Functions & Matrix Operations
Core building blocks including:
• identity(n) - Creates n×n identity matrix
• diagonal(values) - Creates diagonal matrix from array
• ones(rows, cols) / zeros(rows, cols) - Matrix constructors
• frobeniusNorm(m) / l1Norm(m) - Matrix norm calculations
• hadamard(m1, m2) - Element-wise multiplication
• columnMeans(m) / rowMeans(m) - Statistical aggregations
• standardize(m) - Z-score normalization (zero mean, unit variance)
• minMaxNormalize(m) - Scale values to range
• fitStandardScaler(m) / fitMinMaxScaler(m) - Reusable scaler parameters
• addBiasColumn(m) - Prepend column of ones for regression
• arrayMedian(arr) / arrayPercentile(arr, p) - Array statistics
Section 2: Activation Functions
Numerically stable implementations:
• sigmoid(x) / sigmoidMatrix(m) - Logistic function with overflow protection
• tanhActivation(x) / tanhMatrix(m) - Hyperbolic tangent
• relu(x) / reluMatrix(m) - Rectified Linear Unit
• leakyRelu(x, alpha) - Leaky ReLU with configurable slope
• elu(x, alpha) - Exponential Linear Unit
• Derivatives for backpropagation: sigmoidDerivative, tanhDerivative, reluDerivative
Section 3: Linear Regression (OLS)
Ordinary Least Squares implementation using the normal equation (X'X)⁻¹X'y:
• fitLinearRegression(X, y) - Fits model, returns coefficients, R², standard error
• fitSimpleLinearRegression(x, y) - Single-variable regression
• predictLinear(model, X) - Generate predictions
• predictionInterval(model, X, confidence) - Confidence intervals using t-distribution
• Model type stores: coefficients, R-squared, residuals, standard error
Section 4: Weighted Linear Regression
Generalized least squares with observation weights:
• fitWeightedLinearRegression(X, y, weights) - Solves (X'WX)⁻¹X'Wy
• Useful for downweighting outliers or emphasizing recent data
Section 5: Polynomial Regression
Fits polynomials of arbitrary degree:
• fitPolynomialRegression(x, y, degree) - Constructs Vandermonde matrix
• predictPolynomial(model, x) - Evaluate polynomial at points
Section 6: Ridge Regression (L2 Regularization)
Adds penalty term λ||β||² to prevent overfitting:
• fitRidgeRegression(X, y, lambda) - Solves (X'X + λI)⁻¹X'y
• Lambda parameter controls regularization strength
Section 7: LASSO Regression (L1 Regularization)
Coordinate descent algorithm for sparse solutions:
• fitLassoRegression(X, y, lambda, maxIter, tolerance) - Iterative soft-thresholding
• Produces sparse coefficients by driving some to exactly zero
• softThreshold(x, lambda) - Core shrinkage operator
Section 8: Elastic Net (L1 + L2 Regularization)
Combines LASSO and Ridge penalties:
• fitElasticNet(X, y, lambda, alpha, maxIter, tolerance)
• Alpha balances L1 vs L2: alpha=1 is LASSO, alpha=0 is Ridge
Section 9: Huber Robust Regression
Iteratively Reweighted Least Squares (IRLS) for outlier resistance:
• fitHuberRegression(X, y, delta, maxIter, tolerance)
• Delta parameter defines transition between L1 and L2 loss
• Downweights observations with large residuals
Section 10: Quantile Regression
Estimates conditional quantiles using linear programming approximation:
• fitQuantileRegression(X, y, tau, maxIter, tolerance)
• Tau specifies quantile (0.5 = median, 0.25 = lower quartile, etc.)
Section 11: Logistic Regression (Binary Classification)
Gradient descent optimization of cross-entropy loss:
• fitLogisticRegression(X, y, learningRate, maxIter, tolerance)
• predictProbability(model, X) - Returns probabilities
• predictClass(model, X, threshold) - Returns binary predictions
Section 12: Linear SVM (Support Vector Machine)
Sub-gradient descent with hinge loss:
• fitLinearSVM(X, y, C, learningRate, maxIter)
• C parameter controls regularization (higher = harder margin)
• predictSVM(model, X) - Returns class predictions
Section 13: Recursive Least Squares (RLS)
Online learning with exponential forgetting:
• createRLSState(nFeatures, lambda, delta) - Initialize state
• updateRLS(state, x, y) - Update with new observation
• Lambda is forgetting factor (0.95-0.99 typical)
• Useful for adaptive indicators that update incrementally
Section 14: Covariance and Correlation
Matrix statistics:
• covarianceMatrix(m) - Sample covariance
• correlationMatrix(m) - Pearson correlations
• pearsonCorrelation(x, y) - Single correlation coefficient
• spearmanCorrelation(x, y) - Rank-based correlation
Section 15: Principal Component Analysis (PCA)
Dimensionality reduction via eigendecomposition:
• fitPCA(X, nComponents) - Power iteration method
• transformPCA(X, model) - Project data onto principal components
• Returns components, explained variance, and mean
Section 16: K-Means Clustering
Lloyd's algorithm with k-means++ initialization:
• fitKMeans(X, k, maxIter, tolerance) - Cluster data points
• predictCluster(model, X) - Assign new points to clusters
• withinClusterVariance(model) - Measure cluster compactness
Section 17: Gaussian Mixture Model (GMM)
Expectation-Maximization algorithm:
• fitGMM(X, k, maxIter, tolerance) - Soft clustering with probabilities
• predictProbaGMM(model, X) - Returns membership probabilities
• Models data as mixture of Gaussian distributions
Section 18: Kalman Filter
Linear state estimation:
• createKalman1D(processNoise, measurementNoise, ...) - 1D filter
• createKalman2D(processNoise, measurementNoise) - Position + velocity tracking
• kalmanStep(state, measurement) - Predict-update cycle
• Optimal filtering for noisy measurements
Section 19: K-Nearest Neighbors (KNN)
Instance-based learning:
• fitKNN(X, y) - Store training data
• predictKNN(model, X, k) - Classify by majority vote
• predictKNNRegression(model, X, k) - Average of k neighbors
• predictKNNWeighted(model, X, k) - Distance-weighted voting
Section 20: Neural Network (Feedforward)
Multi-layer perceptron:
• createNeuralNetwork(architecture) - Define layer sizes
• trainNeuralNetwork(nn, X, y, learningRate, epochs) - Backpropagation
• predictNN(nn, X) - Forward pass
• Supports configurable hidden layers
Section 21: Naive Bayes Classifier
Gaussian Naive Bayes:
• fitNaiveBayes(X, y) - Estimate class-conditional distributions
• predictNaiveBayes(model, X) - Maximum a posteriori classification
• Assumes feature independence given class
Section 22: Anomaly Detection
Statistical outlier detection:
• fitAnomalyDetector(X, contamination) - Mahalanobis distance-based
• detectAnomalies(model, X) - Returns anomaly scores
• isAnomaly(model, X, threshold) - Binary classification
Section 23: Dynamic Time Warping (DTW)
Time series similarity:
• dtw(series1, series2) - Compute DTW distance
• Handles sequences of different lengths
• Useful for pattern matching
Section 24: Markov Chain / Regime Detection
Discrete state transitions:
• fitMarkovChain(states, nStates) - Estimate transition matrix
• predictNextState(transitionMatrix, currentState) - Most likely next state
• stationaryDistribution(transitionMatrix) - Long-run probabilities
Section 25: Hidden Markov Model (Simple)
Baum-Welch algorithm:
• fitHMM(observations, nStates, maxIter) - EM training
• viterbi(model, observations) - Most likely state sequence
• Useful for regime detection
Section 26: Exponential Smoothing & Holt-Winters
Time series smoothing:
• exponentialSmooth(data, alpha) - Simple exponential smoothing
• holtWinters(data, alpha, beta, gamma, seasonLength) - Triple smoothing
• Captures trend and seasonality
Section 27: Entropy and Information Theory
Information measures:
• entropy(probabilities) - Shannon entropy in bits
• conditionalEntropy(jointProbs, marginalProbs) - H(X|Y)
• mutualInformation(probsX, probsY, jointProbs) - I(X;Y)
• kldivergence(p, q) - Kullback-Leibler divergence
Section 28: Hurst Exponent
Long-range dependence measure:
• hurstExponent(data) - R/S analysis
• H < 0.5: mean-reverting, H = 0.5: random walk, H > 0.5: trending
Section 29: Change Detection (CUSUM)
Cumulative sum control chart:
• cusumChangeDetection(data, threshold, drift) - Detect regime changes
• cusumOnline(value, prevCusumPos, prevCusumNeg, target, drift) - Streaming version
Section 30: Autocorrelation
Serial dependence analysis:
• autocorrelation(data, maxLag) - ACF for all lags
• partialAutocorrelation(data, maxLag) - PACF via Durbin-Levinson
• Useful for time series model identification
Section 31: Ensemble Methods
Model combination:
• baggingPredict(models, X) - Average predictions
• votingClassify(models, X) - Majority vote
• Improves robustness through aggregation
Section 32: Model Evaluation Metrics
Performance assessment:
• mse(actual, predicted) / rmse / mae / mape - Regression metrics
• accuracy(actual, predicted) - Classification accuracy
• precision / recall / f1Score - Binary classification metrics
• confusionMatrix(actual, predicted, nClasses) - Multi-class evaluation
• rSquared(actual, predicted) / adjustedRSquared - Goodness of fit
Section 33: Cross-Validation
Model validation:
• trainTestSplit(X, y, trainRatio) - Random split
• Foundation for walk-forward validation
Section 34: Trading Convenience Functions
Trading-specific utilities:
• priceMatrix(length) - OHLC data as matrix
• logReturns(length) - Log return series
• rollingSlope(src, length) - Linear trend strength
• kalmanFilter(src, processNoise, measurementNoise) - Filtered price
• kalmanFilter2D(src, ...) - Price with velocity estimate
• adaptiveMA(src, sensitivity) - Kalman-based adaptive moving average
• volAdjMomentum(src, length) - Volatility-normalized momentum
• detectSRLevels(length, nLevels) - K-means based S/R detection
• buildFeatures(src, lengths) - Multi-timeframe feature construction
• technicalFeatures(length) - Standard indicator feature set (RSI, MACD, BB, ATR, etc.)
• lagFeatures(src, lags) - Time-lagged features
• sharpeRatio(returns) - Risk-adjusted return measure
• sortinoRatio(returns) - Downside risk-adjusted return
• maxDrawdown(equity) - Maximum peak-to-trough decline
• calmarRatio(returns, equity) - Return/drawdown ratio
• kellyCriterion(winRate, avgWin, avgLoss) - Optimal position sizing
• fractionalKelly(...) - Conservative Kelly sizing
• rollingBeta(assetReturns, benchmarkReturns) - Market exposure
• fractalDimension(data) - Market complexity measure
---
Usage Example
```
import YourUsername/MLMatrixLib/1 as ml
// Create feature matrix
matrix X = ml.priceMatrix(50)
X := ml.standardize(X)
// Fit linear regression
ml.LinearRegressionModel model = ml.fitLinearRegression(X, y)
float prediction = ml.predictLinear(model, X_new)
// Kalman filter for smoothing
float smoothedPrice = ml.kalmanFilter(close, 0.01, 1.0)
// Detect support/resistance levels
array levels = ml.detectSRLevels(100, 3)
// K-means clustering for regime detection
ml.KMeansModel km = ml.fitKMeans(features, 3)
int cluster = ml.predictCluster(km, newFeature)
```
---
Technical Notes
• All matrix operations use Pine Script's native matrix type
• Numerical stability ensured through:
- Clamping exponential arguments to prevent overflow
- Division by zero protection with epsilon thresholds
- Iterative algorithms with convergence tolerance
• Designed for bar-by-bar execution in Pine Script's event-driven model
• Compatible with Pine Script v6
---
Disclaimer
This library provides mathematical tools for quantitative analysis. It does not constitute financial advice. Past performance of any algorithm does not guarantee future results. Users are responsible for validating models on their specific use cases and understanding the limitations of each method.
Elite Risk-On/Risk-Off Oscillator (6 pairs) The Elite Risk-On / Risk-Off Oscillator is a market-regime indicator designed to determine whether conditions favor aggressive risk-taking or defensive capital preservation rather than to predict price direction.
It combines six carefully selected relative-strength pairs that measure risk appetite across the most important parts of the market:
IEI/HYG (credit stress, weighted most heavily because credit often leads equities)
SPHB/SPLV (equity risk appetite via high-beta versus low-volatility stocks)
IWM/SPY (liquidity and growth sensitivity through small-caps versus large-caps)
MTUM/QUAL (trend durability versus balance-sheet quality)
XLY/XLP (consumer cyclicality, wants versus needs)
EEM/SPY (global risk and dollar-sensitive capital flows)
Each pair is evaluated using relative performance against a moving-average and slope filter to classify it as risk-on (+1), neutral (0), or risk-off (-1), with defensive ratios inverted so that positive readings always indicate risk-on conditions; the weighted signals are then aggregated, normalized to a -100 to +100 scale, and smoothed into a single oscillator. Readings above approximately +40 indicate a supportive risk-on environment where trends are more likely to persist, readings between -40 and +40 reflect transitional or choppy conditions with lower conviction, and readings below -40 signal a risk-off regime where capital preservation and defense should be prioritized.
The indicator is intended as a context and position-sizing tool, helping traders align strategy aggressiveness with underlying market conditions rather than relying on forecasts or narratives.
WatchmenThe Watchmen Indicator tracks potential market maker breakeven zones using dynamic open/close ranges (no wicks in Fib calc). It expands the range until the 50% level is breached by the full candle range, then resets. Green = long/down setups (buy retrace), Red = short/up setups (sell retrace). Uses only open/close for levels, high/low for breaches. Ideal for mean-reversion in trends.



















