PolyFilter [BackQuant]PolyFilter
A flexible, low-lag trend filter with three smoothing engines—optimized for clean bias, fewer whipsaws, and clear alerting.
What it does
PolyFilter draws a single “intelligent” baseline that adapts to price while suppressing noise. You choose the engine— Fractional MA , Ehlers 2-Pole Super Smoother , or a Multi-Kernel blend . The line can color itself by slope (trend) or by position vs price (above/below), and you get four ready-made alerts for flips and crosses.
What it plots
PolyFilter line — your smoothed trend baseline (width set by “Line Width”).
Optional candle & background coloring — choose: color by trend slope or by whether price is above/below the filter.
Signal markers — Arrows with L/S when the slope flips or when price crosses the line (if you enable shapes/alerts).
How the three engines differ
Fractional MA (experimental) — A power-law weighting of past bars (heavier focus on the most recent samples without throwing away history). The Adaptation Speed acts like the “fraction” exponent (default 0.618). Lower values lean more on recent bars; higher values spread weight further back.
Ehlers 2-Pole Super Smoother — Classic low-lag IIR smoother that aggressively reduces high-frequency noise while preserving turns. Great default when you want a steady, responsive baseline with minimal parameter fuss.
Multi-Kernel — A 70/30 blend of a Gaussian window and an exponential kernel. The Gaussian contributes smooth structure; the exponential adds a hint of responsiveness. Useful for assets that oscillate but still trend.
Reading the colors
Trend mode (default) — Line & candles turn green while the filter is rising (signal > signal ) and red while it’s falling.
Above/Below mode — Line & candles reflect price’s position relative to the filter: green when price > filter, red when price < filter. This is handy if you treat the filter like a dynamic “fair value” or bias line.
Inputs you’ll actually use
Calculation Settings
Price Source — Default HLC/3. Switch to Close for stricter trend, or HLC3/HL2 to soften single-print spikes.
Filter Length — Window/period for all engines. Shorter = snappier turns; longer = smoother line.
Adaptation Speed — Only affects Fractional MA . Lower it for faster, more local weighting; raise it for smoother, more global weighting.
Filter Type — Pick one of: Fractional MA, Ehlers 2-Pole, Multi-Kernel.
UI & Plotting
Color based off… — Choose Trend (slope) or > or < Close (position vs price).
Long/Short Colors — Customize bull/bear hues to your theme.
Show Filter Line / Paint candles / Color background — Visual toggles for the line, bars, and backdrop.
Line Width — Make the filter stand out (2–3 works well on most charts).
Signals & Alerts
PolyFilter Trend Up — Slope flips upward (the filter crosses above its prior value). Good for early continuation entries or stop-tightening on shorts.
PolyFilter Trend Down — Slope flips downward. Often used to scale out longs or rotate bias.
PolyFilter Above Price — The filter line crosses up through price (filter > price). This can confirm that mean has “caught up” after a pullback.
PolyFilter Below Price — The filter line crosses down through price (filter < price). Useful to confirm momentum loss on bounces.
Quick starts (suggested presets)
Intraday (5–15m, crypto or indices) — Ehlers 2-Pole, Length 55–80. Trend coloring ON, candle paint ON. Look for pullbacks to a rising filter; avoid fading a falling one.
Swing (1H–4H) — Multi-Kernel, Length 80–120. Background color OFF (cleaner), candle paint ON. Add a higher-TF confirmation (e.g., 4H filter rising when you trade 1H).
Range-prone FX — Fractional MA, Length 70–100, Adaptation ~0.55–0.70. Consider Above/Below mode to trade mean reversion to the line with a strict risk cap.
How to use it in practice
Bias line — Trade in the direction of the filter slope; stand aside when it flattens and color chops back and forth.
Dynamic support/resistance — Treat the line as a moving value area. In trends, entries often appear on shallow tags of the line with structure confluence.
Regime switch — When the filter flips and holds color for several bars, tighten stops on the opposing side and look for first pullback in the new color.
Stacking filters — Many users run PolyFilter on the active chart and a slower instance (longer length) on a higher timeframe as a “macro bias” guardrail.
Tuning tips
If you see too many flips, lengthen the filter or switch to Multi-Kernel.
If turns feel late, shorten the filter or try Ehlers 2-Pole for lower lag.
On thin or very noisy symbols, prefer HLC3 as the source and longer lengths.
Performance note: very large lengths increase computation time for the Multi-Kernel and Fractional engines. Start moderate and scale up only if needed.
Summary
PolyFilter gives you a single, trustworthy baseline that you can read at a glance—either as a pure trend line (slope coloring) or as a dynamic “above/below fair value” reference. Pick the engine that matches your market’s personality, set a sensible length, and let the color and alerts guide bias, entries on pullbacks, and risk on reversals.
Volatilidade
Structural Liquidity Signals [BullByte]Structural Liquidity Signals (SFP, FVG, BOS, AVWAP)
Short description
Detects liquidity sweeps (SFPs) at pivots and PD/W levels, highlights the latest FVG, tracks AVWAP stretch, arms percentile extremes, and triggers after confirmed micro BOS.
Full description
What this tool does
Structural Liquidity Signals shows where price likely tapped liquidity (stop clusters), then waits for structure to actually change before it prints a trigger. It spots:
Liquidity sweeps (SFPs) at recent pivots and at prior day/week highs/lows.
The latest Fair Value Gap (FVG) that often “pulls” price or serves as a reaction zone.
How far price is stretched from two VWAP anchors (one from the latest impulse, one from today’s session), scaled by ATR so it adapts to volatility.
A “percentile” extreme of an internal score. At extremes the script “arms” a setup; it only triggers after a small break of structure (BOS) on a closed bar.
Originality and design rationale, why it’s not “just a mashup”
This is not a mashup for its own sake. It’s a purpose-built flow that links where liquidity is likely to rest with how structure actually changes:
- Liquidity location: We focus on areas where stops commonly cluster—recent pivots and prior day/week highs/lows—then detect sweeps (SFPs) when price wicks beyond and closes back inside.
- Displacement context: We track the last Fair Value Gap (FVG) to account for recent inefficiency that often acts as a magnet or reaction zone.
- Stretch measurement: We anchor VWAP to the latest N-bar impulse and to the Daily session, then normalize stretch by ATR to assess dislocation consistently across assets/timeframes.
- Composite exhaustion: We combine stretch, wick skew, and volume surprise, then bend the result with a tanh transform so extremes are bounded and comparable.
- Dynamic extremes and discipline: Rather than triggering on every sweep, we “arm” at statistical extremes via percent-rank and only fire after a confirmed micro Break of Structure (BOS). This separates “interesting” from “actionable.”
Key concepts
SFP (liquidity sweep): A candle briefly trades beyond a level (where stops sit) and closes back inside. We detect these at:
Pivots (recent swing highs/lows confirmed by “left/right” bars).
Prior Day/Week High/Low (PDH/PDL/PWH/PWL).
FVG (Fair Value Gap): A small 3‑bar gap (bar2 high vs bar1 low, or vice versa). The latest gap often acts like a magnet or reaction zone. We track the most recent Up/Down gap and whether price is inside it.
AVWAP stretch: Distance from an Anchored VWAP divided by ATR (volatility). We use:
Impulse AVWAP: resets on each new N‑bar high/low.
Daily AVWAP: resets each new session.
PR (Percentile Rank): Where the current internal score sits versus its own recent history (0..100). We arm shorts at high PR, longs at low PR.
Micro BOS: A small break of the recent high (for longs) or low (for shorts). This is the “go/no‑go” confirmation.
How the parts work together
Find likely liquidity grabs (SFPs) at pivots and PD/W levels.
Add context from the latest FVG and AVWAP stretch (how far price is from “fair”).
Build a bounded score (so different markets/timeframes are comparable) and compute its percentile (PR).
Arm at extremes (high PR → short candidate; low PR → long candidate).
Only print a trigger after a micro BOS, on a closed bar, with spacing/cooldown rules.
What you see on the chart (legend)
Lines:
Teal line = Impulse AVWAP (resets on new N‑bar extreme).
Aqua line = Daily AVWAP (resets each session).
PDH/PDL/PWH/PWL = prior day/week levels (toggle on/off).
Zones:
Greenish box = latest Up FVG; Reddish box = latest Down FVG.
The shading/border changes after price trades back through it.
SFP labels:
SFP‑P = SFP at Pivot (dotted line marks that pivot’s price).
SFP‑L = SFP at Level (at PDH/PDL/PWH/PWL).
Throttle: To reduce clutter, SFPs are rate‑limited per direction.
Triggers:
Triangle up = long trigger after BOS; triangle down = short trigger after BOS.
Optional badge shows direction and PR at the moment of trigger.
Optional Trigger Zone is an ATR‑sized box around the trigger bar’s close (for visualization only).
Background:
Light green/red shading = a long/short setup is “armed” (not a trigger).
Dashboard (Mini/Pro) — what each item means
PR: Percentile of the internal score (0..100). Near 0 = bullish extreme, near 100 = bearish extreme.
Gauge: Text bar that mirrors PR.
State: Idle, Armed Long (with a countdown), or Armed Short.
Cooldown: Bars remaining before a new setup can arm after a trigger.
Bars Since / Last Px: How long since last trigger and its price.
FVG: Whether price is in the latest Up/Down FVG.
Imp/Day VWAP Dist, PD Dist(ATR): Distance from those references in ATR units.
ATR% (Gate), Trend(HTF): Status of optional regime filters (volatility/trend).
How to use it (step‑by‑step)
Keep the Safety toggles ON (default): triggers/visuals on bar‑close, optional confirmed HTF for trend slope.
Choose timeframe:
Intraday (5m–1h) or Swing (1h–4h). On very fast/thin charts, enable Performance mode and raise spacing/cooldown.
Watch the dashboard:
When PR reaches an extreme and an SFP context is present, the background shades (armed).
Wait for the trigger triangle:
It prints only after a micro BOS on a closed bar and after spacing/cooldown checks.
Use the Trigger Zone box as a visual reference only:
This script never tells you to buy/sell. Apply your own plan for entry, stop, and sizing.
Example:
Bullish: Sweep under PDL (SFP‑L) and reclaim; PR in lower tail arms long; BOS up confirms → long trigger on bar close (ATR-sized trigger zone shown).
Bearish: Sweep above PDH/pivot (SFP‑L/P) and reject; PR in upper tail arms short; BOS down confirms → short trigger on bar close (ATR-sized trigger zone shown).
Settings guide (with “when to adjust”)
Safety & Stability (defaults ON)
Confirm triggers at bar close, Draw visuals at bar close: Keep ON for clean, stable prints.
Use confirmed HTF values: Applies to HTF trend slope only; keeps it from changing until the HTF bar closes.
Performance mode: Turn ON if your chart is busy or laggy.
Core & Context
ATR Length: Bigger = smoother distances; smaller = more reactive.
Impulse AVWAP Anchor: Larger = fewer resets; smaller = resets more often.
Show Daily AVWAP: ON if you want session context.
Use last FVG in logic: ON to include FVG context in arming/score.
Show PDH/PDL/PWH/PWL: ON to see prior day/week levels that often attract sweeps.
Liquidity & Microstructure
Pivot Left/Right: Higher values = stronger/rarer pivots.
Min Wick Ratio (0..1): Higher = only more pronounced SFP wicks qualify.
BOS length: Larger = stricter BOS; smaller = quicker confirmations.
Signal persistence: Keeps SFP context alive for a few bars to avoid flicker.
Signal Gating
Percent‑Rank Lookback: Larger = more stable extremes; smaller = more reactive extremes.
Arm thresholds (qHi/qLo): Move closer to 0.5 to see more arms; move toward 0/1 to see fewer arms.
TTL, Cooldown, Min bars and Min ATR distance: Space out triggers so you’re not reacting to minor noise.
Regime Filters (optional)
ATR percentile gate: Only allow triggers when volatility is at/above a set percentile.
HTF trend gate: Only allow longs when the HTF slope is up (and shorts when it’s down), above a minimum slope.
Visuals & UX
Only show “important” SFPs: Filters pivot SFPs by Volume Z and |Impulse stretch|.
Trigger badges/history and Max badge count: Control label clutter.
Compact labels: Toggle SFP‑P/L vs full names.
Dashboard mode and position; Dark theme.
Reading PR (the built‑in “oscillator”)
PR ~ 0–10: Potential bullish extreme (long side can arm).
PR ~ 90–100: Potential bearish extreme (short side can arm).
Important: “Armed” ≠ “Enter.” A trigger still needs a micro BOS on a closed bar and spacing/cooldown to pass.
Repainting, confirmations, and HTF notes
By default, prints wait for the bar to close; this reduces repaint‑like effects.
Pivot SFPs only appear after the pivot confirms (after the chosen “right” bars).
PD/W levels come from the prior completed candles and do not change intraday.
If you enable confirmed HTF values, the HTF slope will not change until its higher‑timeframe bar completes (safer but slightly delayed).
Performance tips
If labels/zones clutter or the chart lags:
Turn ON Performance mode.
Hide FVG or the Trigger Zone.
Reduce badge history or turn badge history off.
If price scaling looks compressed:
Keep optional “score”/“PR” plots OFF (they overlay price and can affect scaling).
Alerts (neutral)
Structural Liquidity: LONG TRIGGER
Structural Liquidity: SHORT TRIGGER
These fire when a trigger condition is met on a confirmed bar (with defaults).
Limitations and risk
Not every sweep/extreme reverses; false triggers occur, especially on thin markets and low timeframes.
This indicator does not provide entries, exits, or position sizing—use your own plan and risk control.
Educational/informational only; no financial advice.
License and credits
© BullByte - MPL 2.0. Open‑source for learning and research.
Built from repeated observations of how liquidity runs, imbalance (FVG), and distance from “fair” (AVWAPs) combine, and how a small BOS often marks the moment structure actually shifts.
Trend-Strong Candle - Pro Multi Assetighlights:
Major Assets Mode (optional): EURUSD, GBPUSD, USDJPY, AUDUSD, USDCAD, NZDUSD, EURGBP, EURJPY
One‑per‑bar alerts, 24/7 toggle, no session limits
Default EMAs 20/40/60, improved stability and EMA-close filters
Lightweight performance, warning-free calculations, and clearer arrows/plots
Bullish Surge Signal-V2This indicator is best used with KST "Know Sure Thing" and "ADX and DI". Golden bar is positive volume, Red dots means sell volume pressure. When you see buy signals on a one hour chart, you know volume, bullish burst is coming soon.
Sentinel Nexus Dashboard [AGP] Ver.1.5Sentinel Nexus Dashboard is a versatile Pine Script designed as a comprehensive technical analysis tool. It condenses a variety of key indicators and metrics into a single, intuitive visual dashboard, providing an integrated view of market trends, momentum, volatility, and liquidity, all neatly organized on your TradingView chart.
Key Features and Benefits
All-in-One Dashboard: This script centralizes relevant information, offering a clean, efficient control panel that helps you make quick decisions without cluttering your chart with multiple overlays.
Trend Analysis with ADX: It incorporates the Average Directional Index (ADX) to measure trend strength. The dashboard displays ADX, DI+, and DI- values with dynamic color-coding to highlight trend intensity (e.g., blue for a very strong trend).
Momentum Analysis with MACD: The dashboard shows MACD line and signal line values in a table. The background color of the MACD values reflects the histogram's direction, allowing you to quickly identify crosses and shifts in market momentum.
Multi-Timeframe RSI Analysis: The RSI (Relative Strength Index) dashboard displays values across multiple timeframes (from 1 minute to 1 month). Overbought (77) and oversold (23) levels are color-coded for immediate identification of market conditions, making it an ideal tool for multi-timeframe analysis.
Smart and Dynamic Volume: The script uses a bar coloring algorithm based on average volume. Chart bars change color according to volume magnitude (extreme, high, average, or low) relative to the average, distinguishing between bullish and bearish bars. This helps you identify significant, liquidity-driven price movements.
Fair Value Analysis: The script calculates an asset's "fair value" using a noise filter (similar to a Kalman filter) on recent highs and lows to determine a midpoint. The price dashboard's background color changes to indicate if the current price is above or below this fair value.
Fibonacci EMA Analysis: A table displays several Exponential Moving Averages (EMAs) based on the Fibonacci sequence. The values are color-coded to show whether the current price is above (white) or below (orange) each EMA, helping you quickly identify dynamic support and resistance levels.
CME Futures Data Integration: For Bitcoin, the script can show a chart label with the Bitcoin futures price (CME:BTC1!), allowing you to compare the spot price with the CME futures market.
Potential Uses and Applications
The Sentinel Nexus Dashboard is an excellent support tool for trading. It is not a signal system but rather a suite of confirmation tools that can be used to:
Confirm Trend Strength: Before entering a trade, use the ADX data to ensure the trend has enough strength for your expected move.
Detect Reversal Points: Multi-timeframe RSI data can alert you to potential overbought or oversold conditions, indicating possible exhaustion of a price move.
Validate Price Movements: Bar coloring based on volume helps you determine if a price move is genuine and supported by strong market participation. High volume can confirm a breakout or reversal.
Identify Support and Resistance: The Fibonacci EMAs allow you to quickly visualize key levels where price might find support or resistance, aiding in planning entries and exits.
In short, this script is perfect for traders who want a comprehensive market overview without chart clutter. It efficiently integrates trend, momentum, and volume analysis in one place.
Legal Disclaimer
RISK WARNING:
This Pine Script is a technical analysis tool and should not be considered financial advice. Past performance of any indicator is no guarantee of future results. Trading in financial markets involves a high risk of loss and is not suitable for all investors. By using this indicator, you accept full responsibility for your trading decisions and acknowledge that any financial loss is your sole responsibility.
IMPORTANT:
Some script functions, such as the CME price label, may not work correctly if your TradingView subscription plan is not a paid one. Please check your plan's limitations to ensure the indicator's optimal functionality.
AWSA "Level Indicator with ATR" isn't a single, defined indicator but typically refers to a trading strategy or indicator that uses the Average True Range (ATR) to create dynamic levels on a price chart, such as support, resistance, or stop-loss levels. The ATR is a volatility indicator that measures market volatility; when high, it suggests the market has large price swings, and when low, small price swings. By using the ATR value with a multiplier, traders can set price levels that adapt to changing market volatility, providing more objective and dynamic trading signals than fixed-price levels.
Implied Volatility RangeThe Implied Volatility Range is a forward-looking tool that transforms option market data into probability ranges for future prices. Based on the lognormal distribution of asset prices assumed in modern option pricing models, it converts the implied volatility curve into a volatility cone with dynamic labels that show the market’s expectations for the price distribution at a specific point in time. At the selected future date, it displays projected price levels and their percentage change from today’s close across 1, 2, and 3 standard deviation (σ) ranges:
1σ range = ~68.2% probability the price will remain within this range.
2σ range = ~95.4% probability the price will remain within this range.
3σ range = ~99.7% probability the price will remain within this range.
What makes this indicator especially useful is its ability to incorporate implied volatility skew. When only ATM IV (%) is entered, the indicator displays the standard Black–Scholes lognormal distribution. By adding High IV (%) and Low IV (%) values tied to strikes above and below the current price, the indicator interpolates between these inputs to approximate the implied volatility skew. This adjustment produces a market-implied probability distribution that indicates whether the option market is leaning bullish or bearish, based on the data entered in the menu:
ATM IV (%) = Implied volatility at the current spot price (at-the-money).
High IV (%) = Implied volatility at a strike above the current spot price.
High Strike = Strike price corresponding to the High IV input (OTM call).
Low IV (%) = Implied volatility at a strike below the current spot price.
Low Strike = Strike price corresponding to the Low IV input (OTM put).
Expiration (Day, Month, Year) = Option expiration date for the projection.
Once these inputs are entered, the indicator calculates implied probability ranges and, if both High IV and Low IV values are provided, adjusts for skew to approximate the option market’s distribution. If no implied volatility data is supplied, the indicator defaults to a lognormal distribution based on historical volatility, using past realized volatility over the same forward horizon. This keeps the tool functional even without implied volatility inputs, though in that case the output represents only an approximation of ATM IV, not the actual market view.
In summary, the Implied Volatility Range is a powerful tool that translates implied volatility inputs into a clear and practical estimate of the market’s expectations for future prices. It allows traders to visualize the probability of price ranges while also highlighting directional bias, a dimension often difficult to interpret from traditional implied volatility charts. It should be emphasized, however, that this tool reflects only the market’s expectations at a specific point in time, which may change as new information and trading activity reshape implied volatility.
IV Rank (tasty-style) — VIXFix / HV ProxyIV Rank (tasty-style) — VIXFix / HV Proxy
Overview
This indicator replicates tastytrade’s IV Rank calculation—but built entirely inside TradingView.
Because TradingView does not expose live option-chain implied volatility, the script lets you choose between two widely used price-based IV proxies:
VIXFix (Williams VIX Fix): a fast-reacting volatility estimate derived from price extremes.
HV(30): 30-day annualized historical volatility of daily log returns.
The goal is to approximate the “rich vs. cheap” option volatility environment that traders use to decide whether to sell or buy premium.
Formula
IV Rank answers the question: Where is current implied volatility relative to its own 1-year range?
𝐼
𝑉
𝑅
=
𝐼
𝑉
𝑐
𝑢
𝑟
𝑟
𝑒
𝑛
𝑡
−
𝐼
𝑉
1
𝑦
𝐿
𝑜
𝑤
𝐼
𝑉
1
𝑦
𝐻
𝑖
𝑔
ℎ
−
𝐼
𝑉
1
𝑦
𝐿
𝑜
𝑤
×
100
IVR=
IV
1yHigh
−IV
1yLow
IV
current
−IV
1yLow
×100
IVcurrent: Current value of the chosen IV proxy.
IV1yHigh/Low: Highest and lowest proxy values over the user-defined lookback (default 252 trading days ≈ 1 year).
IVR = 0 → Current IV equals its 1-year low
IVR = 100 → Current IV equals its 1-year high
IVR ≈ 50 → Current IV sits mid-range
How to Use
High IV Rank (≥50–60%)
Options are relatively expensive → short-premium strategies (credit spreads, iron condors, straddles) may be more attractive.
Low IV Rank (≤20%)
Options are relatively cheap → long-premium strategies (debit spreads, calendars, diagonals) may offer better risk/reward.
Combine with your own analysis, liquidity checks, and risk management.
Inputs & Customization
IV Source: Choose “VIXFix” or “HV(30)” as the volatility proxy.
IVR Lookback: Rolling window for 1-year high/low (default 252 trading days).
VIXFix Parameters: Length and stdev multiplier to fine-tune sensitivity.
Info Label: Optional on-chart label displays current IV proxy, 1-year high/low, and IV Rank.
Alerts: Optional alerts when IVR crosses 50, falls below 20, or rises above 80.
Notes & Limitations
This indicator does not pull real option-chain IV.
It provides a close structural analogue to tastytrade’s IV Rank using price-derived proxies for markets where options data is not directly available.
For live option IV, use broker platforms or third-party data feeds alongside this script.
Tags: IV Rank, Implied Volatility, Tastytrade, VIXFix, Historical Volatility, Options, Premium Selling, Debit Spreads, Market Volatility
Double Median SD Bands | MisinkoMasterThe Double Median SD Bands is a new trend following tool designed to capture trends in a smooth, yet responsive way:
> Think of it like a house:
It will keep you warm & safe, but it will also let you admire the nature through windows, so on this scale our indicator would be a house, without being a jail (too restrictive) or no-house (too unsafe)
How does it work, what is the methodology and more?
The script work in the following way:
1. Calculate the standard deviation of the source
2. Calculate the upper and lower bands:
Band Upper = src + sd*multiplier
Lower Band = src - sd*multiplier
3. Apply the median over half the length used for the SD to the bands
The point of this is to smooth the indicator, but not to make it too lagging, that would just hurt performance, this provides you with decent smoothing
4. Because the indicator is still noisy, we add a median, over the square root of the length used for the SD
This maximizes accuracy, while the speed lost is minimal.
This is due to the cutting of the length and the median itself.
The cutting of the length makes the indicator very responsive, while the median makes it too lagging. The combination of these 2 factors creates a dynamic that works really well for the cryptocurrencies like INDEX:BTCUSD , but might work for others too.
After doing all this you are left with crystal clear, top tier sniper level accurate and "Usain Bolt" fast signals, giving users an edge in the market.
EMA+HHV-ATR Trail By SrinuGreen “BUY: ” below bars.
Red “SELL: ” above bars.
Alerts also include the triggered close price.
Volume Profile Auto POC📌 Overview
Volume Profile Auto POC is a trend-following strategy that uses the automatically calculated Point of Control (POC) from the volume profile, combined with ATR zones, to capture reversals and breakouts.
By basing decisions on volume concentration, it dynamically visualizes the price levels most watched by market participants.
⚠️ This strategy is provided for educational and research purposes only.
Past performance does not guarantee future results.
🎯 Strategy Objectives
Automatically detect the volume concentration area (POC) to improve entry accuracy
Optimize risk management through ATR-based volatility adjustment
Provide early and consistent signals when trends emerge
✨ Key Features
Automatic POC Detection : Updates the volume profile over a defined lookback window in real time
ATR Zone Integration : Defines a POC ± 0.5 ATR zone to clarify potential reversals/breakouts
Visual Support : Plots the POC line and zones on the chart for intuitive decision-making
📊 Trading Rules
Long Entry:
Price breaks above the POC + 0.5 ATR zone
Volume is above average to support the breakout
Short Entry:
Price breaks below the POC - 0.5 ATR zone
Volume is above average to support the downside move
Exit (or Reverse Position):
Price returns to the POC area
Or touches the ATR band
⚙️ Trading Parameters & Considerations
Indicator Name: Volume Profile Auto POC
Parameters:
Lookback Bars: 50
Bins for Volume Profile: 24
ATR Length: 14
ATR Multiplier: 2.0
🖼 Visual Support
POC line plotted in red
POC ± 0.5 ATR zone displayed as a semi-transparent box
ATR bands plotted in blue for confirmation
🔧 Strategy Improvements & Uniqueness
This strategy is inspired by traditional Volume Profile + ATR analysis,
while adding the improvement of a sliding-window mechanism for automatic POC updates.
Compared with conventional trend-following approaches,
its strength lies in combining both price and volume perspectives for decision-making.
✅ Summary
Volume Profile Auto POC automatically extracts key market levels (POC) and combines them with ATR-based zones,
providing a responsive trend-following method.
It balances clarity with practicality, aiming for both usability and reproducibility.
⚠️ This strategy is based on historical data and does not guarantee future profits.
Always use proper risk management when applying it.
Daily standard deviation (Volatility measurer)Volatility measurer based on daily standard deviation. The user is free to select the number of iterations (days).
USD vs USDT Perp PremiumPerp Premiu. An indicator that analyzes the differences betweenvarious crypto price oracles
Stop Loss Advisor📊 Stop Loss Advisor - Advanced Risk Management Tool
A sophisticated Pine Script v5 indicator designed to suggest optimal stop loss distances based on market volatility, combining ATR and Standard Deviation analysis for precise risk management.
🎯 What Makes This Different from Bollinger Bands?
While Bollinger Bands focus on mean reversion and overbought/oversold conditions using a moving average center line, this indicator is specifically designed for risk management . It creates dynamic bands around the current price to suggest where NOT to place your stop loss, preventing you from being stopped out by normal market noise.
⚡ Key Features
Dynamic ATR Calculation - Fully customizable ATR periods with adaptive volatility filtering
Standard Deviation Integration - Optional StdDev component for enhanced statistical accuracy
Multiple Combination Modes - Average, Maximum, ATR Weighted, or StdDev Weighted
Flexible Price Sources - Choose from Close, HL2, HLC3, or OHLC4
Automatic Pip Calculation - Works across all instruments with automatic pip value detection
Smart Alerts System - Get notified when suggested stop loss exceeds your base risk tolerance
Real-time Information Table - Displays current values and risk status
Visual Labels - Shows exact pip distances directly on chart
Band Smoothing - Prevents erratic movements with customizable averaging
📈 How It Works
ATR Analysis : Calculates Average True Range to measure current market volatility
Statistical Enhancement : Optionally combines with Standard Deviation for more robust calculations
Dynamic Bands : Creates upper and lower bands that expand/contract with volatility
Pip Conversion : Automatically converts distances to pips for easy interpretation
Risk Assessment : Compares suggested distances with your base stop loss tolerance
🔧 Customization Options
ATR Settings:
Customizable ATR period (default: 14)
Adjustable multiplier with 0.1 step precision
Optional volatility filtering for enhanced sensitivity
Standard Deviation (Optional):
Independent period and multiplier settings
Multiple price source options
Four combination modes with ATR
Visual Customization:
Fully customizable colors for all elements
Multiple line styles (solid, dashed, dotted)
Optional band filling with transparency control
Show/hide ATR line overlay
Configurable band smoothing
💡 Perfect For
Forex Traders - Especially effective on major pairs and XAUUSD
Risk Managers - Calculate optimal stop distances before entering trades
Scalpers - Avoid being stopped out by normal market fluctuations
Swing Traders - Adapt stop losses to current volatility conditions
📊 Indicator Values
The information table displays:
Current ATR Value (in pips)
Suggested Long Stop Loss (distance in pips)
Suggested Short Stop Loss (distance in pips)
Risk Status - "SAFE" or "HIGH RISK" based on your base tolerance
Standard Deviation Value (when enabled)
Combination Method (when using both ATR and StdDev)
⚠️ Important Notes
This indicator suggests minimum stop loss distances, not entry/exit signals
Always combine with your trading strategy and risk management rules
Do not use as a standalone trading system
Backtesting recommended before live implementation
Default settings work well for most scenarios, but optimization is encouraged
🎨 Default Configuration
ATR Period: 14
ATR Multiplier: 2.0
Price Source: Close
Base Stop Loss: 20 pips
Band Smoothing: 3 periods
Standard Deviation: Optional (20 period, 2.0 multiplier)
🚀 Getting Started
Add the indicator to your chart
Set your base stop loss tolerance in the settings
Choose your preferred price source and ATR parameters
Enable Standard Deviation for enhanced accuracy (optional)
Monitor the information table for real-time risk assessment
Use the suggested distances as minimum stop loss levels
Pro Tip: In low volatility markets, the bands will contract suggesting tighter stops. In high volatility periods, they expand warning you to use wider stops to avoid being stopped out by normal price action.
📝 Version History & Updates
This indicator is actively maintained and updated based on user feedback. Future enhancements may include multi-timeframe analysis, trend-based asymmetric bands, and additional statistical measures.
Transform your risk management approach with data-driven stop loss suggestions that adapt to real market conditions!
Apertura USA - Estrategia Compra8:30 a.m. opening is a very successful strategy in gold with Heikin Ashi candles, 3 minutes, over 80% effectiveness.
Options Straddle Strategy Backtester 140% APR for 2025This script provides the most convenient manual tool for backtesting a straddle stagy in options.
The straddle is when you buy a call and a put option at the same price and the expiration date. You profit when the price movement at expiry (8 am UTC) in either directions surpass the price of the premium paid. The price of opening this straddle on ETH is always 1.6% of the current ETH price including fees.
In my example I use ETH options, I am buying a straddle at 8:30 UTC every day with the next day expiration date. In the script it looks like I am opening a long position on ETH at 8:30 and then close it the next days. We need to use 1 minute chart, chart time set to UTC for exact results and deep back testing function to go back in time.
Once the system generates a trade report - we need to download it and go to the list of trades sections, there we do the following:
1) remove all long entry lines leaving only long exit lines that have all the information we need.
2) We add one column that calculates the cost of premium for every trade: Position size*1.6%=cost of premium with fees.
3)We add a second column copying all Net PNL in USDT changing negative amounts to positive - since it doesn't matter for us which direction the move was towards.
The results are quite impressive: If you were buying straddles during 2025 that is not ended yet you will get 69% return on investment (11K paid in premiums, 19K return, 8K net profit). 2024 and 2025 combined: 53% (29 K, 45 K, and 15 profits).
Moreover, since you have the date of the trade in the table you can filter the results further to figure out if trading on some days is less profitable. Interestingly trades from Sun to Mon given are not profitable at -15% and most profitable days are Mon to Tue - 103%, Friday to Sat - 102 %. So if we remove Sun to Monday trades we will be at 89% for the first 221 days of the year or 140% APR.
Zero Lag + ML SuperTrend Strategy (Multi-Symbol) himanshuThis is a multi-symbol trading strategy that combines two indicators:
Zero Lag EMA with volatility filter
ML SuperTrend
Both must agree (bullish or bearish) before entering a trade.
📊 Entry Rules
Long Entry (Buy):
When price is above ZeroLag line (with volatility filter) and above SuperTrend line.
Short Entry (Sell):
When price is below ZeroLag line (with volatility filter) and below SuperTrend line.
📉 Exit Rules
Take Profit (TP): Fixed at +1% from entry price.
Stop Loss (SL): Fixed at -0.5% from entry price.
Trade closes automatically at TP or SL.
⚡ Features
Multi-symbol ready: Works on any chart you apply it to (DOGE, BTC, ETH, Nifty, etc.).
Alerts included: Sends webhook alerts for long entry, short entry, TP hit, and SL hit.
Plots: Displays ZeroLag line and SuperTrend line on the chart.
👉 In short: The system waits until both indicators confirm the same direction, enters a trade, and then exits automatically at a 1% target or 0.5% stop.
MTF Levels [OmegaTools]📖 Introduction
The Ω Levels Indicator is a complete market structure and level-mapping framework designed to help traders identify key zones where price is likely to react.
It blends classic technical anchors (VWAP, pivots, means, standard deviations) with modern statistical pattern recognition to dynamically project areas of manipulation, extension, and equilibrium.
At its core, Ω Levels creates an evolving map of market balance vs. imbalance, showing traders where liquidity is most likely to build and where price could pivot or accelerate.
But what makes it truly unique is the Pivot Forecaster — an embedded predictive engine that applies machine-learning inspired logic to recognize conditions that historically precede market turning points.
🔎 Key Features
Customizable Levels Framework
Define up to three levels (manipulation, extensions, VWAP, pivots, stdev bands, or prior extremes).
Choose mean references such as Open, VWAP, Pivot Mean, or Previous Session Mean.
Style controls (solid, dotted, dashed) and fill modes (internal, external, ranges) allow you to adapt the chart to your visual workflow.
Dynamic Zone Highlighting
Automatic fills between internal/external levels, or between specific level pairs (1–2, 1–3, 2–3).
Makes it easy to visualize value areas, expansions, and compression zones at a glance.
Multi-Timeframe Anchoring
Works on any timeframe, but calculations can be anchored to a higher timeframe (e.g., show daily VWAP & pivots on a 15m chart).
This allows traders to align intraday execution with higher timeframe context.
Pivot Forecaster (Machine Learning / Pattern Recognition)
This is the advanced predictive component.
The algorithm collects historical conditions observed around pivot highs and lows (volume state, ATR state, % candle expansion, oscillator conditions).
It then builds statistical “profiles” of typical pivot behavior and compares them in real-time against current market conditions.
When conditions match the “signature” of a pivot, the indicator highlights a Forecast Pivot High or Forecast Pivot Low (displayed as small diamond markers).
This functions as a pattern-recognition system, effectively learning from past pivots to anticipate where the next turning point is more likely to occur.
⚡ How Traders Can Use It
Intraday Execution: Use VWAP, manipulation, and extension levels to frame trades around liquidity zones.
Swing Context: Overlay higher timeframe pivots and means to guide medium-term positioning.
Fade Setups: Forecasted pivots often coincide with exhaustion zones where fading momentum carries edge.
Breakout Validation: When price breaks a structural level but the forecaster does not confirm a pivot, continuation probability is higher.
Risk Management: Levels provide natural stop/target placements, while pivot forecasts serve as warning signals for potential reversals.
⚙️ Settings Overview
Timeframe: Choose the anchor timeframe for calculations (default: Daily).
Means: Two selectable mean references (Open, VWAP, Pivot Point, Previous Mean).
Levels: Three levels can be customized (Manipulation, Extension, 1–2 StDev, Pivot Point, VWAP, Previous Extremes).
Fill Modes: Highlight zones between internal/external levels or custom ranges.
Visual Customization: Colors, line styles, fill opacity, and toggle for old levels.
Pivot Forecaster: Fully automated — no settings required, it adapts to instrument and timeframe.
🧭 Best Practices
Align Levels With Market Profile: Treat the levels as dynamic S/R zones and watch how price interacts with them.
Use Forecaster as Confirmation: The diamonds are not standalone signals; they are context filters that help you decide whether a move has higher reversal odds.
Higher Timeframe Anchoring: On intraday charts, set the timeframe to Daily or Weekly to trade with institutional levels.
Combine With ATR: Pair with the Ω ATR Indicator to size positions according to volatility while Ω Levels provides the structural roadmap.
📌 Summary
The Ω Levels Indicator is more than a level plotter — it’s a market map + predictive engine.
By combining traditional levels with an intelligent pivot forecaster, it gives traders both the static structure of where price should react, and the dynamic signal of where it is likely to react next.
This dual-layer approach — structural + predictive — makes it an invaluable tool for discretionary intraday traders, swing traders, and anyone who wants to anticipate price behavior instead of just reacting to it.
Compression Zones by @crypto.erkeCompression Zones - a handy tool I whipped up to spot those quiet moments in the market where volatility drops low. These compression zones often hint at big breakouts or trend shifts.
Key Features:
Volatility Check: I built it with Standard Deviation or ATR, using a 14-period lookback and 50-period SMA to track those calm patches.
Compression Alert: You’ll see a "+" pop up just above the candle when a zone kicks in, with an alert hitting you at candle close—simple and to the point.
Last 20 Zones: Keeps the last 20 zones on your chart so you can glance back at the action.
Tweak It: Defaults are set, but hidden inputs let you play around if you’re feeling adventurous.
How to Use:
Drop it on your chart.
Set an alert for "Compression found" to catch those sweet spots.
Keep an eye on the "+" - great for planning your next move in or out.
Notes:
Works like a charm on crypto, but it’s versatile for any asset.
Hidden settings are there if you want to dig deeper.
The "+" stays put pretty well, even when you zoom—thanks to some label magic I figured out!
Omega ATR Indicator📖 Introduction
The Ω ATR Indicator was created to provide a more complete and professional framework for volatility analysis than the classic Average True Range (ATR).
While the traditional ATR is a useful tool, it has limitations: it delivers a simple rolling average of volatility, but it does not adapt to market regimes, it does not highlight extreme events, and it often leaves the trader with incomplete information about risk.
The Ω ATR takes the same foundation and elevates it into a multi-dimensional volatility dashboard, adding statistical layers, adaptive calculations, and clear visual references that allow traders to interpret volatility in a way that is immediately actionable.
🔎 What makes it different from a standard ATR?
This indicator introduces several features beyond the classic formula:
True Range Core – plots the raw True Range (TR) for each bar, providing a direct, bar-by-bar view of volatility impulses.
Standard & Adjusted ATR – includes both the conventional ATR (smoothed average) and an Adjusted ATR that automatically corrects for extreme conditions by incorporating percentile rescaling.
Percentile Volatility Levels – dynamically calculated extreme thresholds (99.8%, 75%, 50%, 25%), plotted as dotted levels across the chart. These act as reference lines for “normal” vs. “abnormal” volatility, useful for spotting unusual price expansions or contractions.
Linear Regression Volatility Trend – overlays a regression line of volatility, showing whether the market is moving toward expansion (rising vol), contraction (falling vol), or stability.
Monetary Value Translation – the indicator converts volatility into points, ticks, and dollar values (based on the instrument’s point value). This allows futures traders and high-value instruments users to immediately see how much volatility is “worth” in cash terms.
Interactive Table Display – a real-time statistics table is displayed directly on the chart, showing:
SMA of ATR in $ and points
Percentile-based volatility range (VAR) in $ and points
Tick equivalences, for quick position sizing
⚡ How traders can use it
The Ω ATR Indicator is designed to be versatile, fitting both discretionary traders and systematic strategy developers.
Risk Management: ATR-based stop losses and position sizing are significantly improved by using the adjusted ATR and percentile thresholds. Traders can size their positions according to volatility regimes, not just raw averages.
Breakout & Exhaustion Detection: When TR or ATR values spike above the 99.8% or 95% percentile levels, this often corresponds to breakout conditions or volatility exhaustion — useful for breakout strategies, mean-reversion setups, and volatility fades.
Market Regime Identification: The regression line helps distinguish if volatility is rising (trending environment, larger swings expected) or compressing (range-bound environment, lower risk opportunities).
Multi-Asset Flexibility: Works equally well on equities, futures, crypto, and FX. Its point/tick/dollar conversion makes it especially powerful for futures traders who need to quantify risk precisely.
Scalping to Swing Trading: On lower timeframes, it acts as a micro-volatility detector; on higher timeframes, it functions as a strategic risk gauge for position management.
⚙️ Settings and Customization
Length: The ATR lookback period (default = 34).
Shorter lengths (14–21) for intraday traders who want fast response.
Longer lengths (34–55) for swing/position traders who want smoother readings.
AVG / ADJ AVG: Toggle to display the standard ATR or the adjusted ATR.
Volatility Levels: Enable/disable up to 4 percentile-based levels (1st = 25%, 2nd = 50%, 3rd = 75%, 4th = 99.8%). Recommended: keep 3 levels active for clarity.
Color Controls: All plots and levels are fully customizable to match your chart style.
Table Display: Positioned on the chart (default: middle-right) with key values updated in real time.
🧭 Best Practices for Use
Combine with Trend Tools: Volatility readings are most powerful when combined with trend filters or volume analysis. For example, a breakout with both high volatility and trend confirmation is stronger than either alone.
ATR Stops: Use the Adjusted ATR rather than the standard one when trailing stops in highly volatile instruments like crypto or Nasdaq futures, as it adapts to outlier spikes.
Dollar Risk Translation: Use the dollar-value outputs to predefine maximum acceptable risk per trade (e.g., “I only risk $250 per position”). This bridges volatility to portfolio risk management.
Event Monitoring: Around economic events or earnings, expect volatility spikes above higher percentile levels. The indicator makes these moves instantly visible.
📌 Summary
The Ω ATR Indicator is not just “another ATR.” It is a comprehensive volatility framework that transforms volatility from a simple statistic into an actionable trading signal.
By combining:
the classic ATR,
an adjusted ATR,
percentile extremes,
regression-based volatility trends,
and real-time dollar conversions,
…this tool allows traders to precisely understand, visualize, and act on volatility in ways that a standard ATR simply cannot provide.
Whether you are scalping intraday moves, swing trading equities, or managing futures positions, the Ω ATR equips you with a professional-grade volatility dashboard that clarifies risk, highlights opportunity, and adapts across all markets and timeframes.
👉 Designed and developed by OmegaTools for traders who demand precision, clarity, and adaptability in their volatility analysis.
Heavy Buy/Sell + Traps + FVG (Options) – Cleanthis script under testing stage so it is not accurate so please make buy & sell decision wisely
Outside the Bollinger Bands Alerting Indicator Overview
The Outside the Bollinger Bands Alerting Indicator is a comprehensive technical analysis tool that combines multiple proven
indicators into a single, powerful system designed to identify high-probability reversal patterns at Bollinger Band extremes. This
indicator goes beyond simple band touches to detect sophisticated pattern formations that often signal strong directional moves.
Key Features & Capabilities
🎯 Advanced Pattern Recognition
Bollinger Band Breakout Patterns
- Detects "pierce-and-reject" formations where price breaks through a Bollinger Band but immediately reverses back inside
- Identifies failed breakouts that often lead to strong moves in the opposite direction
- Combines multiple confirmation signals: engulfing candle patterns, MACD momentum, and ATR volatility filters
- Visual alerts with symbols positioned below (bullish) or above (bearish) candles
Tweezer Top & Bottom Patterns
- Identifies consecutive candles with nearly identical highs (tweezer tops) or lows (tweezer bottoms)
- Requires at least one candle to breach the respective Bollinger Band
- Confirms reversal with directional close requirements
- Customizable tolerance settings for pattern sensitivity
- Visual alerts with ❙❙ symbols for easy identification
📊 Multi-Indicator Integration
Bollinger Bands Indicator
- Dual-band configuration with outer (2.0 std dev) and inner (1.5 std dev) bands that can be adjusted to suit your own parameters
- Configurable MA types: SMA, EMA, SMMA (RMA), WMA, VWMA
- Customizable length, source, and offset parameters
- Color-coded band fills for visual clarity
Moving Average Suite
- EMA 9, 21, 50, and 200 (individually toggleable)
- Special "SMA 3 High" for help visualizing and detecting Bollinger Band break-outs
- Dynamic color coding based on price relationship
Optional Ichimoku Cloud overlay
- Complete Ichimoku implementation with customizable periods
- Dynamic cloud coloring based on trend direction
- Toggleable overlay that doesn't interfere with other indicators
🚨 Comprehensive Alert System
Real-Time JSON Alerts
- Sends structured data on every confirmed bar close
- Includes all indicator values: BB levels, EMAs, MACD, RSI
- Contains signal states and crossover conditions
- Perfect for automated trading systems and webhooks
{"timestamp":1753118700000,"symbol":"ETHUSD","timeframe":"5","price":3773.3,"bollinger_bands":{"upper":3826.95,"basis":3788.32,"lower":3749.68},"emas":{"ema_9":3780.45,"ema_21":3788.92,"ema_50":3800.79,"ema_200":3787.74,"sma_3_high":3789.45},"macd":{"macd":-10.1932,"signal":-11.3266,"histogram":1.1334},"rsi":{"rsi":40.5,"rsi_ma":39.32,"level":"neutral"}}
Specific Alert Conditions
- MACD histogram state changes (rising to falling, falling to rising)
- RSI overbought/oversold crossovers
- All pattern detections (BB Bounce, Tweezer patterns)
- Bollinger Band breakout alerts
🎨 Visual Elements
Pattern Identification
- ♻ symbols for Bollinger Band breakout patterns (green for bullish, red for bearish)
- ❙❙ symbols for tweezer patterns (green below for bottoms, red above for tops)
- Color-coded band fills for trend visualization
Chart Overlay Options
- All moving averages with distinct colors
- Bollinger Bands with inner and outer boundaries
- Optional Ichimoku cloud with trend-based coloring
Trading Applications
Reversal Trading
- Identify high-probability reversal points at extreme price levels
- Use failed breakout patterns for entry signals
- Combine multiple timeframes for enhanced accuracy
Trend Analysis
- Monitor moving average relationships for trend direction
- Use Ichimoku cloud for trend strength assessment
- Track momentum with MACD and RSI integration
Risk Management
- ATR-based volatility filtering reduces false signals
- Multiple confirmation requirements improve signal quality
- Real-time alerts enable prompt decision making
Suggested Use
- Use on multiple timeframes for confluence
- Combine with support/resistance levels for enhanced accuracy
- Set up alerts for hands-free monitoring
- Customize settings based on market volatility and trading style
- Consider volume confirmation for stronger signals
Mony Strategy with TP1/TP2/SL V2//@version=5
strategy("Mony Strategy with TP1/TP2/SL", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=2, initial_capital=10000)
// ===== TAKE PROFIT & STOP LOSS SETTINGS =====
tp_sl_group = "Take Profit & Stop Loss"
enable_tp_sl = input.bool(true, "Enable TP/SL", group=tp_sl_group)
tp1_multiplier = input.float(1.0, "TP1 Multiplier (x ATR)", minval=0.1, maxval=10.0, step=0.1, group=tp_sl_group)
tp2_multiplier = input.float(2.0, "TP2 Multiplier (x ATR)", minval=0.1, maxval=20.0, step=0.1, group=tp_sl_group)
sl_multiplier = input.float(1.5, "Stop Loss Multiplier (x ATR)", minval=0.1, maxval=10.0, step=0.1, group=tp_sl_group)
show_tp_sl_lines = input.bool(true, "Show TP/SL Lines", group=tp_sl_group)
show_rr_ratio = input.bool(true, "Show Risk:Reward Ratio", group=tp_sl_group)
// portion allocation to TP1 and TP2 (must sum to 100)
tp1_pct = input.int(50, "TP1 % of position", minval=1, maxval=100, group=tp_sl_group)
tp2_pct = input.int(50, "TP2 % of position", minval=1, maxval=100, group=tp_sl_group)
// normalize if sum != 100
_tp_sum = tp1_pct + tp2_pct
if _tp_sum != 100
tp1_pct := math.round(tp1_pct * 100.0 / _tp_sum)
tp2_pct := 100 - tp1_pct
// TP/SL Colors
tp_color = input.color(color.new(color.green, 20), "Take Profit Color", group=tp_sl_group)
sl_color = input.color(color.new(color.red, 20), "Stop Loss Color", group=tp_sl_group)
// ===== ORIGINAL NIFTY MAGNET SETTINGS (kept mostly intact) =====
const bool DEBUG = false
const float epsilon = 0.02 / 100.0
const int showLastXPivots = 50
// Auto Trendline
var int TYPE_UP = 1
var int TYPE_DOWN = -1
var string LINE_WIDTH1_STR = "Width 1"
var string LINE_WIDTH2_STR = "Width 2"
_get_width(string str_input) =>
switch str_input
LINE_WIDTH1_STR => 1
LINE_WIDTH2_STR => 2
var string GROUP_FRACT = "Fractals"
var color col_hl = input.color(color.blue, title="Plot:", inline="plot_low", group=GROUP_FRACT)
var bool show_hl = input.bool(true, title="HL", inline="plot_low", group=GROUP_FRACT)
var color col_ll = input.color(color.gray, title=", Plot:", inline="plot_low", group=GROUP_FRACT)
var bool show_ll = input.bool(false, title="LL", inline="plot_low", group=GROUP_FRACT)
var color col_lh = input.color(color.red, title="Plot:", inline="plot_high", group=GROUP_FRACT)
var bool show_lh = input.bool(false, title="LH", inline="plot_high", group=GROUP_FRACT)
var color col_hh = input.color(color.gray, title=", Plot:", inline="plot_high", group=GROUP_FRACT)
var bool show_hh = input.bool(false, title="HH", inline="plot_high", group=GROUP_FRACT)
var string GROUP_ATL = "Auto trendlines"
var string subgroup1 = "recent line"
var color ln_col_recent = input.color(color.new(color.purple, 0), title="Latest Trendline", group=GROUP_ATL, inline=subgroup1)
var int lnwidth_recent = _get_width(input.string(LINE_WIDTH1_STR, options= , title="", inline=subgroup1, group=GROUP_ATL))
var string subgroup2 = "historical line"
var color ln_col_prev = input.color(color.new(color.gray, 50), title="Historical Trendline", group=GROUP_ATL, inline=subgroup2)
var int lnwidth_prev = _get_width(input.string(LINE_WIDTH1_STR, options= , title="", inline=subgroup2, group=GROUP_ATL))
var bool show_historical = input.bool(false, title="Show Historical Lines", group=GROUP_ATL)
var int max_tl = input.int(1, title="Max pair of lines", maxval=250, minval=1, group=GROUP_ATL)*2
var string _str_extend = input.string("Right", options= , title="Which way to extend lines", group=GROUP_ATL)
var string str_extend = _str_extend == "Both ways" ? extend.both : extend.right
var bool show_crosses = input.bool(false, title="Show crosses", tooltip="Instances when closing price of a bar has crossed lower/upper trendlines", group=GROUP_ATL)
// ===== TP/SL VARIABLES =====
var float call_entry = na
var float put_entry = na
// ===== FRACTAL TYPE DEFINITION =====
type fractal
int up_or_down = na
int xloc = na
float yloc = na
int xloc_parent = na
float yloc_parent = na
var fractal arr_fract = array.new()
var line arr_ln_up = array.new_line()
var line arr_ln_dn = array.new_line()
// ===== FRACTAL FUNCTIONS =====
init_fractal(int fract_type, int xloc, float yloc, int xparent, float yparent)=>
f = fractal.new()
f.up_or_down := fract_type
f.xloc := xloc
f.yloc := yloc
f.xloc_parent := xparent
f.yloc_parent := yparent
ln = line.new(xloc, yloc, xparent, yparent, xloc.bar_index, str_extend, color=ln_col_recent, style=line.style_dashed, width=lnwidth_recent)
if f.up_or_down == TYPE_UP
array.unshift(arr_ln_up, ln)
else if f.up_or_down == TYPE_DOWN
array.unshift(arr_ln_dn, ln)
array.unshift(arr_fract, f)
f
drop_and_roll(fractal f) =>
arr_ln = f.up_or_down == TYPE_UP ? arr_ln_up : f.up_or_down == TYPE_DOWN ? arr_ln_dn : na
if array.size(arr_ln) > 1
if show_historical
line.set_color(array.get(arr_ln, 1), ln_col_prev)
line.set_width(array.get(arr_ln, 1), lnwidth_prev)
else
line.delete(array.get(arr_ln, 1))
while array.size(arr_ln) > math.floor(max_tl/2)
line.delete(array.pop(arr_ln))
draw_trendline(fract_type, x2, y2, x1, y1) =>
f = init_fractal(fract_type, x2, y2, x1, y1)
drop_and_roll(f)
// ===== PIVOT CALCULATIONS =====
float ph = ta.pivothigh(10, 10)
bool upfract = not na(ph)
float pl = ta.pivotlow(10, 10)
bool downfract = not na(pl)
// ===== VOLATILITY FILTER =====
data_source = close
filter_length = 20
range_factor = 3.5
vol_range(input_data, multiplier, period) =>
window_size = period * 2 - 1
vol_avg = ta.ema(math.abs(input_data - input_data ), period)
adjusted_vol = ta.ema(vol_avg, window_size) * multiplier
adjusted_vol
vol_filter(input_data, range_val, period) =>
v_range = range_val
var v_filtered = array.new_float(2, input_data)
array.set(v_filtered, 1, array.get(v_filtered, 0))
if input_data - v_range > array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data - v_range)
if input_data + v_range < array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data + v_range)
filtered_val = array.get(v_filtered, 0)
upper_band = filtered_val + v_range
lower_band = filtered_val - v_range
// Calculate current ATR for TP/SL
current_atr = ta.atr(14)
// Volatility Filter Values
= vol_filter(data_source, vol_range(data_source, range_factor, filter_length), filter_length)
// Direction Conditions
var float trend_dir = 0.0
trend_dir := filtered_data > filtered_data ? 1 : filtered_data < filtered_data ? -1 : trend_dir
bull_trend = trend_dir == 1 ? 1 : 0
bear_trend = trend_dir == -1 ? 1 : 0
// Trading Conditions
buy_condition = (data_source > filtered_data and data_source > data_source and bull_trend > 0) or (data_source > filtered_data and data_source < data_source and bull_trend > 0)
sell_condition = (data_source < filtered_data and data_source < data_source and bear_trend > 0) or (data_source < filtered_data and data_source > data_source and bear_trend > 0)
var int state_trend = 0
state_trend := buy_condition ? 1 : sell_condition ? -1 : nz(state_trend , 0)
entry_buy = buy_condition and nz(state_trend , 0) == -1
entry_sell = sell_condition and nz(state_trend , 0) == 1
// ===== STRATEGY ENTRY + TP/SL LOGIC =====
// We'll use strategy.entry for entries and strategy.exit for TP1 and TP2 (each with qty_percent).
// Calculate TP/SL prices based on the price at signal (we use close at the signal bar).
var float last_long_entry_price = na
var float last_short_entry_price = na
if entry_buy
// place a long entry (full size)
strategy.entry("Long", strategy.long)
if enable_tp_sl
last_long_entry_price := close
if entry_sell
strategy.entry("Short", strategy.short)
if enable_tp_sl
last_short_entry_price := close
// When we have an entry price, create two exits: TP1 (partial) and TP2 (remaining).
// Both exits include the same stop (SL) so the remaining is protected if SL hit.
if enable_tp_sl
// LONG exits
if not na(last_long_entry_price)
long_tp1 = last_long_entry_price + tp1_multiplier * current_atr
long_tp2 = last_long_entry_price + tp2_multiplier * current_atr
long_sl = last_long_entry_price - sl_multiplier * current_atr
// create (or update) exits for long
// TP1: partial take-profit
strategy.exit(id="Long TP1", from_entry="Long", limit=long_tp1, stop=long_sl, qty_percent=tp1_pct)
// TP2: remainder take-profit
strategy.exit(id="Long TP2", from_entry="Long", limit=long_tp2, stop=long_sl, qty_percent=tp2_pct)
// Plot lines/labels for clarity (only visible while active)
if show_tp_sl_lines and strategy.position_size > 0
line.new(bar_index , long_tp1, bar_index, long_tp1, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_dotted, width=1)
line.new(bar_index , long_tp2, bar_index, long_tp2, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_solid, width=1)
line.new(bar_index , long_sl, bar_index, long_sl, xloc=xloc.bar_index, extend=extend.right, color=sl_color, style=line.style_dashed, width=1)
// show label of R:R
if show_rr_ratio
rr1 = (long_tp1 - last_long_entry_price) / (last_long_entry_price - long_sl)
rr2 = (long_tp2 - last_long_entry_price) / (last_long_entry_price - long_sl)
label.new(bar_index, long_tp2, text="RR1: " + str.tostring(rr1, format.percent) + " RR2: " + str.tostring(rr2, format.percent), style=label.style_label_left, color=color.new(color.black, 80), textcolor=color.white, size=size.tiny)
// SHORT exits
if not na(last_short_entry_price)
short_tp1 = last_short_entry_price - tp1_multiplier * current_atr
short_tp2 = last_short_entry_price - tp2_multiplier * current_atr
short_sl = last_short_entry_price + sl_multiplier * current_atr
strategy.exit(id="Short TP1", from_entry="Short", limit=short_tp1, stop=short_sl, qty_percent=tp1_pct)
strategy.exit(id="Short TP2", from_entry="Short", limit=short_tp2, stop=short_sl, qty_percent=tp2_pct)
if show_tp_sl_lines and strategy.position_size < 0
line.new(bar_index , short_tp1, bar_index, short_tp1, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_dotted, width=1)
line.new(bar_index , short_tp2, bar_index, short_tp2, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_solid, width=1)
line.new(bar_index , short_sl, bar_index, short_sl, xloc=xloc.bar_index, extend=extend.right, color=sl_color, style=line.style_dashed, width=1)
if show_rr_ratio
srr1 = (last_short_entry_price - short_tp1) / (short_sl - last_short_entry_price)
srr2 = (last_short_entry_price - short_tp2) / (short_sl - last_short_entry_price)
label.new(bar_index, short_tp2, text="RR1: " + str.tostring(srr1, format.percent) + " RR2: " + str.tostring(srr2, format.percent), style=label.style_label_left, color=color.new(color.black, 80), textcolor=color.white, size=size.tiny)
// Reset recorded entry prices when no position
if strategy.position_size == 0
last_long_entry_price := na
last_short_entry_price := na
// ===== TP/SL HIT VISUAL NOTIFICATIONS (labels on the bar where fills happen) =====
// Detect if exits happened this bar by inspecting strategy.closedtrades or position change
// Simple approach: check last bar's position change vs current to label TP/SL hits is not bulletproof but useful.
long_closed = strategy.closedtrades > 0 and strategy.position_size > 0 and strategy.position_size == 0
short_closed = strategy.closedtrades > 0 and strategy.position_size < 0 and strategy.position_size == 0
// Use builtin trade info to label: iterate last closed trade not directly available per-bar in strategy — keep this simple and place a generic label when a position is closed
if long_closed
label.new(bar_index, high, "Closed Long", style=label.style_label_down, color=color.new(color.blue, 0), textcolor=color.white)
if short_closed
label.new(bar_index, low, "Closed Short", style=label.style_label_up, color=color.new(color.orange, 0), textcolor=color.white)
// ===== FRACTAL TRACKING (trendline drawing preserved) =====
var float recent_dn1 = na
var int i_recent_dn1 = na
var float recent_up1 = na
var int i_recent_up1 = na
var float recent_dn2 = na
var int i_recent_dn2 = na
var float recent_up2 = na
var int i_recent_up2 = na
if downfract
recent_dn2 := recent_dn1
i_recent_dn2 := i_recent_dn1
recent_dn1 := low
i_recent_dn1 := bar_index-11
draw_trendline(TYPE_DOWN, i_recent_dn2, recent_dn2, i_recent_dn1, recent_dn1)
if upfract
recent_up2 := recent_up1
i_recent_up2 := i_recent_up1
recent_up1 := high
i_recent_up1 := bar_index-11
draw_trendline(TYPE_UP, i_recent_up2, recent_up2, i_recent_up1, recent_up1)
// ===== COLORS AND FILTER PLOT =====
filter_color = bull_trend ? #05ff9b : bear_trend ? #ff0583 : #cccccc
// Filter Plot
plot(filtered_data, color=filter_color, linewidth=3, title='Volatility Filter')
// ===== BUY/SELL SIGNALS (visual only) =====
plotshape(entry_buy, title='Call Signal', text='BUY', textcolor=color.rgb(9, 233, 110),
style=shape.labelup, size=size.normal, location=location.belowbar, color=color.new(color.green, 0))
plotshape(entry_sell, title='Put Signal', text='SELL', textcolor=color.rgb(228, 10, 21),
style=shape.labeldown, size=size.normal, location=location.abovebar, color=color.new(color.red, 0))
// ===== ALERTS (kept) =====