Script Title: FX Exchange Simulator: Two Investors (Gain vs. LosDescriptionOverviewThis educational tool is designed to help traders and beginners understand the mechanics of currency exchange rates in the EUR/USD pair. It simulates two distinct investor scenarios based on the highest and lowest prices over a user-defined period (default: 100 bars).The Two ScenariosThe script compares how the direction of exchange and the timing of the trade impact final purchasing power:Investor 1 (Starting with USD - The Strategic Entry):At the Low: Converts $1,000 USD into EUR by dividing the amount by the exchange rate.At the High: Converts those EUR back into USD by multiplying.Result: Demonstrates how buying a currency when it is "cheap" (at the low) increases your total capital in dollars.Investor 2 (Starting with EUR - The Timing Error):At the Low: Panics and converts 1,000€ into USD by multiplying.At the High: Tries to recover the 1,000€ by dividing the USD back at a higher rate.Result: Demonstrates how selling a currency when it is "cheap" and buying it back when it is "expensive" leads to a significant loss of purchasing power.FeaturesDynamic Historical Analysis: Automatically finds the highest and lowest points within the selected lookback period.Step-by-Step Calculation Table: A clean, top-centered table showing the initial amount, the exchange process, the final total, and the ROI (Return on Investment) percentage.Visual Annotations: Labels on the chart pinpoint exactly where the "Minimum" and "Maximum" occurred to provide visual context for the trade simulation.Fully Customizable: Users can adjust the initial capital amount and the lookback period via the settings menu.Mathematics Behind the ScriptThe script uses the following formulas for the calculations:Profit Scenario (USD to EUR):$$\text{Total USD} = \left( \frac{\text{Initial USD}}{\text{Price}_{min}} \right) \times \text{Price}_{max}$$Loss Scenario (EUR to USD):$$\text{Total EUR} = \left( \text{Initial EUR} \times \text{Price}_{min} \right) / \text{Price}_{max}$$InstructionsAdd the script to your chart (best used on EUR/USD).Look at the labels to see where the period extremes are.Check the table at the top to see the financial outcome of both investors.Use the "Settings" to change the initial amount or the bar period to test different market cycles.DisclaimerThis script is for educational purposes only. It is intended to illustrate currency exchange mechanics and does not constitute financial advice.
インジケーターとストラテジー
HAP Trend CageHAP Trend Cage – Visual Band & Stochastic Entry System
HAP Trend Cage is a pure visual overlay indicator designed to show when price is trapped inside dynamic bands — and when momentum timing aligns for a potential entry.
This is not Bollinger Bands.
These bands are built to contain price behavior, not volatility expansion.
🔹 What it shows:
Dynamic price bands plotted directly on the chart
Clear visual zones where price is compressed or held
Stochastic (14, 3, 3) used purely for entry timing
Exact candle awareness — you see where and when the signal happens
🔹 How to use:
Follow the bands visually — price inside the cage = structure intact
Wait for Stochastic alignment inside or near band boundaries
Designed for confirmation, not prediction
No clutter, no repainting, no over-signaling
🔹 Why it’s different:
Focuses on market structure first
Momentum is used only as a timing tool
Built for traders who trust price behavior over indicators
This indicator does not tell you to buy or sell.
It shows you where the market is constrained — and lets you decide when to act
Broadening Formation Reclaim Stats v1.0Description: Broadening Formation Reclaim Stats v1.0
Overview
The Broadening Formation Reclaim Stats is a technical analysis tool designed to track and quantify "reclaim" price action within expanding market structures (Broadening Formations). It focuses on scenarios in which price breaches a prior Swing High or Swing Low and subsequently rotates back into the range, often signaling a potential reversal toward the opposite side of the formation.
This indicator is built for traders who study price action rotations, "The Strat" (Rev 2-2 / Failed 2-Down/Up), and liquidity sweeps.
How It Works
The script utilizes a state-machine logic to track price movements relative to high and low pivots:
1. Structure Identification: It identifies recent Pivot Highs and Lows (Auto-Swing mode) or allows users to input specific price levels (Manual mode).
2. The Breach: It identifies when price breaks above the established high or below the established low, "locking" the structure for a potential reclaim.
3. The Reclaim: A signal is generated when price moves back inside the range using specific price action triggers:
Rev 2-2: A reversal pattern where price reverses the direction of the previous candle.
Failed 2-Down/Up: Price makes a new wick extreme but closes back within the previous candle's range and below its opening price.
4. Targets: The script considers a reclaim "Successful" if price reaches the opposite side of the broadening formation (the opposing pivot).
Key Features
Backtesting Dashboard: A real-time table displaying the total number of reclaims, global success rates, and a breakdown of Bullish vs. Bearish performance.
Flexible Lookbacks: Statistics can be calculated based on the entire chart history, "Today Only" (for day traders), or a specific number of bars.
Dual Mode Detection: Choose between **Auto Swing** detection (based on a user-defined pivot length) or **Manual** mode for specific levels.
Optimized Visuals: Uses the Pine Script Plot Engine for core levels to ensure price-scale stability and "Box Objects" for clear pivot visualization.
Settings
Swing Length: Adjust the sensitivity of the pivot detection.
BF Mode: Toggle between automatic pivot tracking or manual price entry.
Statistics Start Mode: Filter the data displayed in the table to focus on recent price action or historical performance.
UI Customization: Fully adjustable table position, size, and transparency.
Disclaimer
This indicator is for educational and research purposes only. It tracks historical price action patterns and does not constitute financial advice. Past performance (success rates) as displayed in the dashboard is not an indicator of future results.
NVentures Liquidity Radar ProInstitutional Liquidity Radar Pro
OVERVIEW
This indicator combines three institutional trading concepts into a unified confluence scoring system: Liquidity Zones (swing-based), Order Blocks, and Fair Value Gaps. The unique value lies not in these individual concepts, but in HOW they interact through the confluence scoring algorithm to filter high-probability zones.
HOW THE CONFLUENCE SCORING WORKS
The core innovation is the calcConfluence() function that assigns a numerical score to each detected level:
1. Base Score: Every swing pivot starts with score = 1
2. Zone Overlap Detection: The algorithm iterates through all active zones within confDist * ATR proximity. Each overlapping zone adds +1 to the score
3. Order Block Proximity: If an Order Block's midpoint (top + bottom) / 2 falls within the confluence distance, +1 is added
4. HTF Validation: Using request.security(), the indicator fetches higher timeframe swing pivots. If the current zone aligns with an HTF swing within 2 * confDist * ATR_htf, a +2 bonus is awarded
Zones scoring 4+ are highlighted as high confluence - these represent areas where multiple institutional concepts converge.
HOW LIQUIDITY ZONES ARE CALCULATED
Detection: ta.pivothigh() and ta.pivotlow() with configurable lookback (default: 5 bars left/right)
Zone Width - Three modes available:
- ATR Dynamic: ATR(14) * multiplier (default 0.25)
- Fixed %: close * (percentage / 100)
- Wick Based: max(upperWick, lowerWick) * 1.5
Proximity Filter: isTooClose() prevents clustering by enforcing minimum ATR * minATRdist between zones
HOW ORDER BLOCKS ARE DETECTED
The detectBullishOB() / detectBearishOB() functions identify the last opposing candle before an impulse move:
1. Check if candle is opposing direction (bearish before bullish impulse, vice versa)
2. Validate consecutive candles in impulse direction (configurable, default: 3)
3. Volume confirmation: volume >= volMA * volMult (using 50-period SMA)
4. Minimum move validation: abs(close - close ) > ATR
This filters out weak OBs and focuses on those with institutional volume footprints.
HOW FAIR VALUE GAPS ARE DETECTED
FVGs represent price imbalances:
- Bullish FVG: low - high > ATR * fvgMinSize
- Bearish FVG: low - high > ATR * fvgMinSize
The ATR-relative sizing ensures gaps are significant relative to current volatility.
HOW SWEEP DETECTION WORKS
The checkSweep() function identifies false breakouts through wick analysis:
1. Calculate wick percentage: upperWick / totalRange or lowerWick / totalRange
2. Sweep conditions for resistance: high > zone.upper AND close < zone.price AND wickPct >= threshold
3. Sweep conditions for support: low < zone.lower AND close > zone.price AND wickPct >= threshold
A sweep indicates liquidity was grabbed without genuine continuation - often preceding reversals.
HOW FRESHNESS DECAY WORKS
The calcFreshness() function implements linear decay:
freshness = 1.0 - (age / decayBars)
freshness = max(freshness, minFresh)
This ensures old, tested zones fade visually while fresh zones remain prominent.
WHY THESE COMPONENTS WORK TOGETHER
The synergy is based on the principle that institutional activity leaves multiple footprints:
- Swing Pivots = where retail stops cluster
- Order Blocks = where institutions entered
- FVGs = where aggressive institutional orders created imbalances
- HTF Alignment = where higher timeframe participants are active
When these footprints converge at the same price level (high confluence score), the probability of significant price reaction increases.
CONFIGURATION
- Swing Detection Length: 5-8 for intraday, 8-15 for swing trading
- HTF Timeframe: One level above trading TF (e.g., D for H4)
- Min Confluence to Display: 2 for comprehensive view, 3-4 for high-probability only
- FVGs: Disabled by default for cleaner charts
STATISTICS PANEL
Displays: Active resistance/support zones, high confluence count, swept zones, active OBs, active FVGs, current ATR, selected HTF.
ALERTS
- Price approaching high confluence zone
- Liquidity sweep detected
- Bullish/Bearish Order Block formed
- Bullish/Bearish FVG detected
TECHNICAL NOTES
- Uses User-Defined Types (UDTs) for clean data structure management
- Respects Pine Script drawing limits (500 boxes/labels/lines)
- All calculations are ATR-normalized for cross-market compatibility
Auto Chart Patterns- Market AdaptedAuto Chart Patterns - Code Description
This Pine Script v5 indicator is a sophisticated automated chart pattern detection system that identifies geometric price patterns using zigzag analysis. Here's a comprehensive breakdown:
🎯 Purpose
Automatically detects and visualizes classic chart patterns (channels, wedges, triangles) on any timeframe by analyzing price pivot points.
📦 Dependencies (Imports)
text
- HeWhoMustNotBeNamed/utils/1 → Utility functions (theme colors)
- Trendoscope/ohlc/1 → OHLC data handling
- Trendoscope/LineWrapper/1 → Line drawing utilities
- Trendoscope/ZigzagLite/2 → Zigzag pivot detection
- Trendoscope/abstractchartpatterns/5 → Pattern definitions
- Trendoscope/basechartpatterns/6 → Pattern recognition logic
⚙️ Input Parameters
1. Source Settings
Custom OHLC sources (default: standard OHLC)
2. Zigzag Settings (4 Independent Zigzags)
Zigzag Enabled Length Depth Purpose
ZZ1 ✅ 8 55 Primary - catches larger swings
ZZ2 ✅ 13 34 Secondary - medium swings
ZZ3 ❌ 21 21 Tertiary - balanced
ZZ4 ❌ 34 13 Quaternary - smaller swings
3. Scanning Parameters
Parameter Default Description
numberOfPivots 5 Points needed for pattern (5 or 6)
errorThreshold 30% Tolerance for trendline validation
flatThreshold 20% Slope ratio for "flat" determination
lastPivotDirection both Filter by final pivot direction
checkBarRatio false Validate time proportionality
avoidOverlap true Prevent overlapping patterns
repaint true Use real-time or confirmed bars
4. Pattern Groups
Geometric Shapes:
✅ Channels
✅ Wedges
✅ Triangles
Direction:
✅ Rising
✅ Falling
✅ Flat/Bi-Directional
Formation Dynamics:
✅ Expanding
✅ Contracting
✅ Parallel
📊 Detected Pattern Types (14 Total)
text
INDEX | PATTERN TYPE | CATEGORY
------|--------------------------------|------------------
1 | Ascending Channel | Parallel/Rising
2 | Descending Channel | Parallel/Falling
3 | Ranging Channel | Parallel/Flat
4 | Rising Expanding Wedge | Expanding/Rising
5 | Falling Expanding Wedge | Expanding/Falling
6 | Diverging Triangle | Expanding/Flat
7 | Ascending Expanding Triangle | Expanding/Rising
8 | Descending Expanding Triangle | Expanding/Falling
9 | Rising Contracting Wedge | Contracting/Rising
10 | Falling Contracting Wedge | Contracting/Falling
11 | Converging Triangle | Contracting/Flat
12 | Descending Contracting Triangle| Contracting/Falling
13 | Ascending Contracting Triangle | Contracting/Rising
🏗️ Core Architecture
Scanner Type (Custom Object)
JavaScript
type Scanner
bool enabled
string ticker
string timeframe
ScanProperties sProperties // Scanning configuration
DrawingProperties dProperties // Visual settings
array patterns // Detected patterns storage
array zigzags // Zigzag pivots storage
Key Methods
getZigzagAndPattern()
Calculates zigzag pivots from price data
When new pivot detected → scans for patterns
Requires minimum 6 pivots in buffer
Uses multi-level zigzag analysis
Validates patterns against allowed configurations
scan()
Creates OHLC array from sources
Iterates through enabled zigzags (1-4)
Calls pattern detection for each zigzag configuration
🔄 Execution Flow
text
1. Initialize Scanner with all properties
2. On each bar (confirmed or real-time based on 'repaint'):
│
├─→ Build OHLC array
│
├─→ For each enabled Zigzag:
│ ├─→ Calculate pivots
│ ├─→ If new pivot detected:
│ │ ├─→ Scan for valid patterns
│ │ ├─→ Draw pattern if found
│ │ ├─→ Store in patterns array
│ │ ├─→ Trim old patterns (if > maxPatterns)
│ │ └─→ Trigger alert
│ └─→ Move to next zigzag level
│
└─→ Repeat on next bar
🎨 Display Features
Theme: Light/Dark mode
Pattern lines: Customizable width
Labels: Pattern name + pivot labels (with size options)
Zigzag: Optional display with custom color
Pattern limit: Auto-deletes oldest when exceeding max (default: 20)
⚡ Alerts
Triggers 'New Pattern Alert' when any valid pattern is detected.
💡 "Market Adapted" Features
Dual zigzag enabled by default (ZZ1 + ZZ2) for multi-timeframe sensitivity
Higher error threshold (30%) for volatile markets
Flexible pivot direction filtering per pattern type
Overlap avoidance to reduce noise
RSI Divergence Indicator (Multi-Time Frame Confirmation)This custom-built RSI indicator blends traditional divergence detection with multi-timeframe trend confirmation, offering traders a smarter way to spot meaningful momentum shifts.
Clean SMC: Filtered OB + FVGHow does this indicator work?
Fair Value Gaps (FVG): It identifies price imbalances (gaps between the wick of candle 1 and candle 3). They appear as small, light-colored rectangles.
Order Blocks (OB): It marks "Smart Money" candles that precede a strong impulse. These areas are extended to the right because they often act as future support or resistance.
Signals (BUY/SELL): The indicator displays a signal when it detects a confluence (for example, a bullish OB appearing right after an FVG).
Some friendly trading tips:
Timeframe: This indicator works best on higher timeframes (15m, 1h, 4h) to avoid market "noise."
Confirmation: Don't take a "BUY" signal on its own. Check if the overall trend (on a higher timeframe) is also bullish.
Risk management: Always place your Stop Loss just below the identified Order Block.
RSI Chebyshev Pro with Goldilocks Fractals - NR [NPR21]RSI Chebyshev Pro with Goldilocks Fractals - Non-Repaint
----------------------------------------------------------------------------------------------------------------------
CHART INFORMATION
Instrument: /MNQ (Micro E-mini Nasdaq-100 Futures)
Timeframe: 2-minute
Indicator: RSI Chebyshev Pro with Goldilocks Fractals - NR
----------------------------------------------------------------------------------------------------------------------
THE PROBLEM
Standard RSI is too choppy and noisy – it whipsaws all over the place in volatile markets like futures, giving false oversold/overbought signals that burn you on entries. I was sick of missing real reversals or getting stopped out on fakeouts. I wanted something smoother that still catches the big momentum shifts without lagging too much, plus actual market structure to make it more reliable for quick trades.
WHAT MAKES THIS UNIQUE
Unlike basic RSI indicators that use simple moving average smoothing, this combines several advanced techniques that aren't commonly found together:
1. Chebyshev Type I Filtering - Signal processing mathematics (not basic EMAs) that kills noise while keeping real swings sharp. Most RSI smoothing just blurs everything - this keeps responsiveness without the chop.
2. MAMA Adaptive Period - The moving average adapts to actual market cycles using the MESA algorithm, not fixed periods that lag in changing conditions.
3. RSI Pivot Fractals - These aren't price fractals slapped onto RSI. The fractals detect pivots directly on RSI values at extreme levels, with signals appearing back at the exact pivot bar (not current bar), showing you where the actual reversal happened.
4. True Non-Repainting Implementation - Signals appear delayed BUT locked at the historical pivot location forever. What you see in backtests is exactly what appeared live - no vanishing signals, no shifting.
5. All-in-One Integration - Instead of running 3-4 separate indicators (RSI + fractals + patterns + smoothing), everything works together in a single, optimized calculation with confluence built in.
This isn't just RSI with some Williams Fractals thrown on top - it's a complete rethink of how to identify high-probability RSI reversals using signal processing and adaptive algorithms.
ORIGIN & ENHANCEMENTS
Original Source: ChartPrime RSI Chebyshev indicator
Converted & Enhanced by: NPR21
What I Added:
✅ Converted to Pine Script v6 - Made this available to TradingView traders
✅ Goldilocks Fractals - RSI alone doesn't tell you about price structure. These fractals nail those "just right" pivot points where highs/lows confirm. I kept seeing RSI extremes that reversed hard when they lined up with fractals - this was the missing piece for confluence.
✅ 100% Non-Repainting - I've been burned by repainters. You'd backtest something, looks amazing, then live it vanishes or shifts. Lost real money on that. This is rock-solid: signals show delayed but once they're there, they're locked forever. Makes backtesting trustworthy.
✅ Candlestick Patterns - Engulfing, Morning Star, Evening Star detection for confluence
✅ Customizable Visuals - BUY/SELL labels, multiple display styles, full color/size control
✅ Complete Alert System - Get notified on all signal types
HOW IT WORKS
Chebyshev Filtering:
Like putting noise-canceling on your RSI – smooths out jittery ups and downs from random price spikes without flattening into useless lag. It's signal processing math that keeps important swings sharp while killing BS noise. Way better than simple EMA smoothing that blurs everything.
The Components:
Ultra-Smooth RSI - Chebyshev Type I filtering + adaptive MAMA algorithm
Goldilocks Fractals - Pivot detection confirmed after N bars (default 5)
Pattern Recognition - Detects Engulfing, Morning/Evening Star patterns
Visual Styles - Candle Trend (hollow green/solid red) or traditional candles
SIGNAL DELAY vs REPAINTING
✅ THIS HAS SIGNAL DELAY (GOOD) - NOT REPAINTING (BAD)
Signal Delay:
Signals appear after N bars (default 5 bar delay)
Once visible, NEVER disappears or moves
Perfect for backtesting - 100% reliable
What you see in history is what you'd see live
Why the Delay:
To confirm a pivot, we need to see price didn't go lower/higher in the next N bars. This confirmation makes signals reliable. The delay is the price for trustworthy signals.
Want faster? Drop Fractal Periods to 2-3 (more signals, less confirmation).
HOW I TRADE IT
My /MNQ Scalping (1-3 min charts):
LONG: BUY label appears (down fractal + maybe morning star/engulfing) → Check RSI crossing up from oversold (<30) → Confirm with volume → Long with stop below fractal low → Target 1-2R
SHORT: SELL label (up fractal + maybe evening star) → RSI from overbought → Short with stop above
Filter: Only longs in uptrends (watch the MA). Exit partials if momentum fades.
Best Timeframes: 1-5 min for futures scalping. Works on 15 min for swings but for pure scalping, stay under 5 min in high-vol sessions.
SETTINGS I USE
Standard Setup:
Length: 24, Smoothing: 3
Auto MA: ON, Multiplier: 1-2
Fractal Periods: 5 (good confirmation)
Choppy Days:
Smoothing to 5
Aggressive:
Fractal Periods to 3
Pro Tip: Pair with volume or price EMA. Love when fractal BUY + engulfing bull align. Use Candle Trend style. Test on demo first.
KEY SETTINGS
RSI: Length (24), Smoothing (3), Auto MA, Style (Candle/Candle Trend)
Fractals: Periods (5 = more reliable, 3 = faster/riskier), Label colors/sizes, Offsets
Alerts: All signals fire only on confirmed, non-repainting events
DISCLAIMERS
⚠️ Tool, not a complete system - use proper risk management
⚠️ Signals have delay for reliability - not for instant entries
⚠️ Best with price action, volume, other analysis
⚠️ Test on demo before live trading
Questions? Comment below!
NPR21
Absorption Pro V4This indicator detects absorption-style reversal setups and scores them with a multi-factor model.
It builds key levels from ZigZag/Fibonacci and round numbers across multiple timeframes, then flags potential absorption candles using volume and a delta-proxy filter plus strict candle-structure rules. Signals are validated with trend context (MA/SMMA/EMA/ATR), VWAP positioning, and optional momentum/volatility filters (RSI, Stoch, CCI, MACD, ADX, Volume Profile). Only score-threshold crosses can trigger long/short markers and alerts (defaults tuned for NQ).
ezzy Golden Cross mit Target und StopA simple crossover system based on SMA 50 and SMA 200 including percentage target and stop loss.
High Volume Footprint BreakoutThe High Volume Footprint Breakout indicator brings institutional-grade Order Flow analysis to your standard TradingView charts. By looking inside the candles using intrabar data, this tool identifies specific price levels where massive, aggressive buying or selling volume has occurred.
Unlike standard Volume Profiles which show volume over a long period, this indicator isolates specific moments of high-intensity participation. It draws extended support and resistance lines from these "High Volume Nodes," helping you identify where institutions have stepped in and where trapped traders might exist.
Why Use This Indicator?
Standard candlestick charts show you where price went, but they hide how it got there. A candle might look normal, but inside that candle, there could be a massive battle between buyers and sellers at a specific price level.
Reveal Hidden Liquidity : Find the exact price levels that defended a move.
Filter the Noise : Instead of showing every volume node, this script only highlights Breakout Levels —areas where the single-price volume exceeded a historical maximum (e.g., the highest volume node in the last 20 bars).
No External Tools Needed : Replicates the logic of professional Footprint/Order Flow software using native TradingView data.
How It Works (The Logic)
This script uses a strict algorithm to reconstruct a virtual "Footprint" of the market:
Intrabar Analysis : It accesses lower timeframe data (e.g., 1-minute data inside a Daily bar) to analyze price action at a granular level.
Volume Categorization : It separates volume into Buy Volume (Aggressive Buyers) and Sell Volume (Aggressive Sellers) based on price movement logic.
Volume Distribution : To ensure accuracy, it distributes the volume of intrabar candles across their High-Low range, preventing artificial volume spikes on single ticks.
Breakout Detection : It compares the highest volume node of the current bar against the highest nodes of the previous X bars. If the current volume is a new local record, a line is drawn.
How to Trade This Indicator
1. The Standard Rejection (Trend Continuation)
Green Lines (Aggressive Buyers) : These levels represent areas where buyers stepped in with massive force. In an uptrend, expect price to bounce off these lines. Treat them as Support.
Red Lines (Aggressive Sellers) : These levels represent areas where sellers unloaded heavy positions. In a downtrend, expect price to reject these lines. Treat them as Resistance.
2. The "Flip" Setup (Trapped Traders)
This is an advanced Order Flow concept. When the market disrespects a high-volume level, it creates "Trapped Traders."
Red Line Acting as Support : If price breaks above a Red (Sell) line and holds, the aggressive sellers at that level are now trapped underwater. When price returns to this line, these sellers often buy to close their positions at breakeven, fueling a bounce.
Green Line Acting as Resistance : If price breaks below a Green (Buy) line, the aggressive buyers are trapped. When price rallies back to this line, they often sell to exit, creating resistance.
Settings & Configuration
Auto-Select Intrabar Timeframe :
Enabled (Recommended) : Automatically selects the best resolution (1-min for Intraday/Daily, 60-min for Weekly/Monthly) to match the "Volume Data Source" standards.
Disabled : Allows you to manually force a specific intrabar resolution.
Breakout Lookback Period : Determines how significant a volume spike must be to trigger a line. (Default: 20). Higher values = fewer, stronger lines.
Max Visible Lines : Limits the number of lines on the chart to keep your workspace clean.
Label Offset : Adjusts how far to the right the text labels appear, allowing you to position them perfectly for your screen setup.
Who Should Use This?
Order Flow Traders : Who want footprint-style logic without complex grid charts.
Price Action Traders : Who want objective, data-driven Support & Resistance levels rather than subjective drawings.
Scalpers & Day Traders : Who need to see where the "heavy hands" are transacting in real-time.
Disclaimer & Limitations
Intrabar vs. Tick Data : This script uses TradingView's intrabar data to approximate the footprint. While highly accurate, it may differ slightly from tick-perfect software.
Volume Data Required : This indicator requires the asset to provide real volume data. It works best on Futures, Crypto, and Stocks. It may not work on FOREX pairs that do not provide tick volume.
Does it Repaint?
Short Answer:
No , it does not repaint on closed bars. Once a candle closes and a line is drawn, that line is permanent and will not move or disappear.
Long Answer (The Nuances):
There are two specific scenarios you need to be aware of regarding how TradingView handles data:
1. The "Forming Bar" (Wait for Close)
Behavior : While the current candle is still moving (open), the indicator is calculating the volume in real-time. If a massive volume spike happens right now, a line might appear. If the volume of previous bars suddenly looks smaller by comparison, the condition might change.
Solution : Like almost all indicators, you must wait for the bar to close to confirm the signal. Once the bar closes, the calculation is locked and the line is fixed forever.
2. Historical Data Limits (The "Disappearing History" Issue)
Behavior : This script relies on request.security_lower_tf (e.g., fetching 1-minute data inside a Daily bar). TradingView does not store infinite 1-minute data for every asset. They usually store a few thousand bars of lower timeframe history (more if you have a Premium account).
The Issue : If you scroll back 5 years on a Daily chart, the script will try to fetch the 1-minute data for a day in 2019. If TradingView has deleted that old 1-minute data to save space, the script will receive "empty" data.
Result : You might see lines on the recent chart (last few months/year), but if you scroll back too far, the lines will stop appearing because the underlying data doesn't exist anymore.
Is this Repainting? Technically, no. It's a Data Availability limitation. But it means that what you see on a chart from 5 years ago might look different than what you saw when you were trading it live 5 years ago.
Disclaimer
For Educational and Informational Purposes Only
This indicator is provided for educational and informational purposes only and DOES NOT constitute financial, investment, or trading advice. The "High Volume Footprint Breakout" tool is based on historical data analysis and algorithmic interpretation of market volume; it does not predict future market movements with certainty.
Risk Warning
Trading in financial markets (Stocks, Crypto, Futures, Forex, etc.) involves a high degree of risk and may not be suitable for all investors. You could lose some or all of your initial investment. Past performance of any trading system or methodology is not necessarily indicative of future results.
No Liability
The author of this script assumes no responsibility or liability for any errors or omissions in the content of this indicator, or for any trading losses or damages incurred as a result of using this tool. Users are solely responsible for their own trading decisions and should always use proper risk management. By using this script, you acknowledge and agree to these terms.
Gtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingview
Forecast OscillatorGeneral Overview
The Forecast Oscillator Plus (FOSC+) is not just another oscillator. It is an advanced quantitative analysis tool developed to bridge the gap left by traditional momentum indicators (like RSI or Stochastic) which often suffer from "lag" or remain pinned in extreme zones during strong trends.
This "Plus" version has been specifically engineered and optimized for high-velocity scalping and day-trading on assets like NAS100 (Nasdaq) and XAUUSD (Gold) using ultra-short timeframes (1-min, 5-min).
🛡️ Why is FOSC+ Different?
1. Linear Regression Intelligence
At the heart of this script is a powerful Linear Regression (LinReg) engine. Instead of comparing price to a simple average, FOSC+ calculates the percentage deviation between the current price and its predicted theoretical trajectory. This allows the indicator to identify not just if the price is "high" or "low," but if it is abnormally distanced from its current trend, signaling an imminent Mean Reversion.
2. Adaptive Dynamic Bands (Volatility-Adjusted)
A major weakness of classic oscillators is the use of fixed levels (e.g., 80/20). FOSC+ utilizes Standard Deviation to generate overbought and oversold zones that "breathe" with the market.
During high volatility, the bands expand to filter out noise and premature entries.
During low volatility, they tighten to capture precise turning points.
3. Institutional Volume Filter (Anti-Fakeout)
To succeed in the Nasdaq market, you must follow the "Smart Money." This script integrates a Volume Spike Filter. A signal (Buy/Sell) is only triggered if the current candle's volume is significantly higher than its moving average (adjustable multiplier). This ensures you only enter trades backed by real institutional strength.
4. Algo-Ready for PineConnector
The code has been structured for seamless automation. With built-in EMA smoothing to reduce 1-minute "market chatter," the signals are clean and sharp, minimizing execution errors when sending orders to MetaTrader 5 via PineConnector.
📈 Technical Trading Guide
Buy Signals (Green Triangle): Occur when the oscillator crosses above the dynamic oversold band OR crosses back above the zero line, provided that volume confirms the impulse.
Sell Signals (Red Triangle): Occur when the oscillator crosses below the dynamic overbought band OR breaks below the zero line from above, with volume confirmation.
Momentum Histogram: The colored columns indicate acceleration strength. Excellent for Trailing Stops: as long as the histogram is growing, the momentum is in your favor!.
⚙️ Recommended Parameters
Length (14): The "Sweet Spot" for balancing reactivity and reliability.
Smooth Len (4): Essential for 1-min charts to eliminate micro-fluctuations without adding lag.
Volume Mult (1.15): Filters out the bottom 15% of volume to keep only significant candles.
⚠️ Stress-Tested for Real Conditions
This script has been rigorously backtested with Slippage settings ranging from 10 to 25 points. Even under difficult market conditions with high spreads, the indicator maintains a positive expectancy, making it a premier tool for traders using Standard or Raw accounts.
BNF (Kotegawa) Strategy [CB Algos]STRATEGY: BNF (Kotegawa) Mean Reversion Strategy
DEVELOPED BY: CB Algos
DESCRIPTION:
This indicator replicates the trading style of Takashi Kotegawa (BNF).
It calculates the percentage deviation of the price from the 25-period SMA.
HOW TO USE:
1. Look for 'Lime' bars (Extreme Buy) or 'Teal' bars (Moderate Buy). These indicate the price has dropped significantly below the average.
2. Look for 'Red' bars (Extreme Sell) as profit-taking zones.
3. Use the Info Panel to see the exact current deviation %.
Clean Support & Resistance ZonesThis indicator automatically maps out key Support and Resistance zones on any chart and displays them as clean, easy-to-read filled boxes.
Instead of flooding the chart with dozens of levels, it ranks zones by strength (how often price has pivoted from that area), then shows only the most relevant zones near current price. It also includes a no-overlap filter, so zones don’t stack on top of each other — making it much easier to see exactly where you might want to buy from support or sell from resistance.
Key Features
Automatic Support & Resistance zones using pivot structure
Strength-based filtering (keeps the most respected zones)
Distance filter (only shows zones within a user-defined ATR range of price)
No overlapping zones + optional minimum spacing for clarity
Custom colours for support/resistance fill and borders
Works on all markets and all timeframes
Boxes can optionally extend to the right for forward planning
Inputs You Can Adjust
Pivot sensitivity (Pivot Left/Right)
Zone thickness (ATR multiplier or fixed tolerance)
How many zones to display per side
How close zones must be to current price (ATR distance)
Minimum separation between zones (ATR spacing)
Full colour controls for fills + borders
AI Reversal Probability Zones (Dual Mode)This custom-built indicator is designed to detect potential bullish and bearish reversals by aggregating multiple high-probability signals into a unified score. It blends momentum, volatility, trend deviation, and candle structure into a single visual line, enhanced by dynamic color zones that represent the probability and strength of a market reversal.
Nova Capital MACDNova Capital MACD is a momentum oscillator based on the classic MACD calculation, enhanced with a clean 4-state histogram and optional signal labels.
Core calculation:
MACD Line = Fast MA − Slow MA
Signal Line = MA(MACD Line, Signal Length)
Histogram = MACD Line − Signal Line
Features in this version:
4-state histogram coloring (positive/negative + rising/falling) to visualize momentum changes more clearly.
Optional confirmed-bar behavior (signals trigger only on closed bars).
Optional zero-line directional filter:
Long labels only when MACD is below 0.
Short labels only when MACD is above 0.
Built-in alert conditions for Long/Short events.
How to use:
Watch histogram state changes for momentum transitions.
A Long label appears on MACD crossing above the Signal line (optionally below 0).
A Short label appears on MACD crossing below the Signal line (optionally above 0).
Note: This indicator is not a complete trading system. Use risk management and confirm signals with market context.
Gann Octogram - Sacred Geometry Confluence Ver 1.0📐 Gann Octogram - Sacred Geometry Confluence Ver 1.0
Overview
Advanced Gann analysis tool combining W.D. Gann's Square of Nine principles with sacred geometry and multi-factor confluence signals. This indicator automatically detects swing highs/lows and projects octogram grids forward in time and price, identifying high-probability trading opportunities where multiple factors align.
Understanding Gann Octograms
W.D. Gann believed markets move in geometric patterns through time and price. The octogram (8-sided figure) represents the square of nine principle where:
Price divisions (1/8ths) create natural support/resistance
Time cycles mark potential reversal points
Diagonal angles show dynamic price-time relationships
Confluence zones where geometry aligns offer highest probability trades
This indicator makes these complex calculations automatic and visual.
Key Features
🎯 Intelligent Auto-Detection
Auto Gann Number Selection: Automatically chooses optimal Gann period (11, 22, 44, 88, 176) based on timeframe and data availability
Adaptive Half-Period Mode: Uses Gann/2 for faster swing detection while validating with full period
Smart Grid Projection: Projects octagrams near current price action for relevance
📊 Sacred Geometry Visualization
Octogram Grids: Complete octagonal geometry with inner square, angled square, and connecting lines
Gann Angles: 1×1 and 2×1 diagonal support/resistance angles
Time Cycles: Quarter, half, and three-quarter cycle markers
Price Levels: Automatic 1/8th division levels (0%, 12.5%, 25%, 37.5%, 50%, 62.5%, 75%, 87.5%, 100%)
⚡ Advanced Confluence System
Adjustable 4-Factor Confluence (Levels 0-4):
Price Level Touch: Precise detection of key support/resistance levels
Time Cycle Alignment: Major (25%, 50%, 75%) and minor (1/8th divisions) cycles
Octogram Geometry: Proximity to vertices and diagonal angles
Price Action: Bullish/bearish candle confirmation
Confluence Levels:
Level 0: Signals on price touch only (most signals)
Level 1: Minimum 1 factor required
Level 2: Minimum 2 factors (⭐ recommended - balanced)
Level 3: Minimum 3 factors (strict quality)
Level 4: All 4 factors required (highest quality, fewer signals)
🛡️ Signal Quality Controls
Max Signals Per Cell: Limit signals to 1-10 per grid cell
Cooldown Period: Minimum bars between consecutive signals
Cell Signal Tracking: Automatic reset when entering new time cells
Adjustable Tolerances: Fine-tune price and geometry sensitivity
How It Works
Swing Detection: Identifies significant market swings using pivot highs/lows
Grid Construction: Builds octogram grid from swing high to swing low
Multi-Grid Projection: Projects multiple cells forward (time) and vertically (price)
Confluence Analysis: Monitors all 4 factors continuously
Signal Generation: Fires BUY/SELL when confluence threshold is met
BUY Signals trigger when:
Price touches LOW zones (0%-50%)
At key time cycle points
Near octogram geometry
Bullish candle forms
SELL Signals trigger when:
Price touches HIGH zones (50%-100%)
At key time cycle points
Near octogram geometry
Bearish candle forms
Settings Guide
Structure Settings
Auto Gann Number: Enable for automatic period selection (recommended)
Manual Gann Number: 11, 22, 44, 88, or 176 bars
Use Half Period: Faster detection using Gann/2 lookback
Grid Stability: Adaptive (1/8th) / Strict (1/4th) / Relaxed (1/16th)
Signal Settings ⚙️
Confluence Level: 0-4 (start with 2)
Price Tolerance: 1-8% (default 3%)
Geometry Tolerance: 0.5-5% (default 2.5%)
Min Bars Between Signals: 1-20 (default 3)
Max Signals Per Cell: 1-10 (default 4-6)
Display Options
Toggle grid squares, octagrams, triangles, Gann angles
Customizable colors for all elements
Time cycle visualization
Swing high/low markers
Info panel with swing statistics
Best Practices
For Day Trading (5min-15min charts):
Confluence Level: 2
Auto Gann: ON
Grid Stability: Adaptive
Max Signals Per Cell: 4-6
For Swing Trading (1H-4H charts):
Confluence Level: 3
Auto Gann: ON
Grid Stability: Strict
Max Signals Per Cell: 2-4
For Position Trading (Daily charts):
Confluence Level: 3-4
Manual Gann: 88 or 176
Grid Stability: Strict
Max Signals Per Cell: 2-3
Alert Setup
Built-in alert conditions:
Gann Octogram Buy - Fires on BUY signal
Gann Octogram Sell - Fires on SELL signal
Configure alerts using TradingView's alert system to get notified when confluence zones trigger.
Backtesting Tips
Start with Confluence Level 2 (balanced approach)
Increase level to 3-4 if too many signals
Decrease to 1 if missing opportunities
Adjust tolerances based on asset volatility
Test different Gann numbers for your specific market
Credits & Theory
Based on W.D. Gann's principles:
Square of Nine
Time-Price Geometry
Sacred Geometry (Octograms)
Natural Market Cycles
Developed with modern Pine Script for reliability, efficiency, and user control.
Version History
Ver 1.0 - Initial Release
4-factor confluence system
Auto Gann number selection
Adjustable confluence levels (0-4)
Sacred geometry visualization
Signal quality controls
Support
For questions, suggestions, or issues:
Comment on this indicator
Check the code (open source)
Experiment with settings for your trading style
Happy Trading! 📈
Disclaimer
This indicator is for educational and informational purposes only. Past performance does not guarantee future results. Always practice proper risk management and never risk more than you can afford to lose. Backtest thoroughly before live trading.
Neeson bitcoin Dynamic ATR Trailing SystemNeeson bitcoin Dynamic ATR Trailing System: A Comprehensive Guide to Volatility-Adaptive Trend Following
Introduction
The Dynamic ATR Trailing System (DATR-TS) represents a sophisticated approach to trend following that transcends conventional moving average or breakout-based methodologies. Unlike standard trend-following systems that rely on price pattern recognition or fixed parameter oscillators, this system operates on the principle of volatility-adjusted position management—a nuanced approach that dynamically adapts to changing market conditions rather than imposing rigid rules on market behavior.
Originality and Innovation
Distinct Methodological Approach
What sets DATR-TS apart from hundreds of existing trend-following systems is its dual-layered conditional execution framework. While most trend-following systems fall into one of three broad categories—moving average crossovers, channel breakouts, or momentum oscillators—this system belongs to the more specialized category of volatility-normalized trailing stop systems.
Key Original Contributions:
Volatility-Threshold Signal Filtering: Most trend systems generate signals continuously, leading to overtrading during low-volatility periods. DATR-TS implements a proprietary volatility filter that requires minimum market movement before generating signals, effectively separating high-probatility trend opportunities from market noise.
Self-Contained Position State Management: Unlike traditional systems that require external position tracking, DATR-TS maintains an internal position state that prevents contradictory signals and creates a closed-loop decision framework.
Dynamic Risk Parameter Adjustment: The system doesn't use fixed percentage stops or rigid ATR multiples. Instead, it implements a responsive adjustment mechanism that widens stops during high volatility and tightens them during low volatility, creating an optimal balance between risk protection and opportunity capture.
Trader-Centric Visualization Philosophy: Beyond mere signal generation, the system provides a comprehensive visual feedback system designed to align with human cognitive patterns, reducing emotional decision-making through consistent color coding and information hierarchy.
Technical Implementation and Functionality
Core Operational Mechanism
DATR-TS implements a volatility-adjusted trend persistence model that operates on the principle that trending markets exhibit characteristic volatility signatures. The system specifically targets medium-term directional movements (typically lasting 5-20 days) rather than short-term scalping opportunities or long-term position trades.
The Four-Pillar Architecture:
Volatility Measurement and Normalization
Calculates Average True Range (ATR) over a user-defined period
Converts absolute volatility to percentage terms relative to price
Compares current volatility against user-defined thresholds to filter suboptimal conditions
Dynamic Trailing Stop Algorithm
Establishes an initial stop distance based on current volatility
Implements a four-state adjustment mechanism that responds to price action
Maintains stop position during trend continuation while allowing for trend reversal detection
Conditional Signal Generation
Generates entry signals only when price action meets both directional and volatility criteria
Produces exit signals based on trailing stop penetration
Incorporates position state awareness to prevent conflicting signals
Comprehensive Feedback System
Provides multi-layer visual information including dynamic stop lines, signal labels, and color-coded price action
Displays real-time metrics through an integrated dashboard
Offers configurable visualization options for different trading styles
Specific Trend-Following Methodology
DATR-TS employs a volatility-normalized trailing stop breakout approach, which differs significantly from common trend identification methods:
Not a moving average crossover system (like MACD or traditional MA crosses)
Not a channel breakout system (like Bollinger Band or Donchian Channel breaks)
Not a momentum oscillator system (like RSI or Stochastic trend following)
Not a price pattern recognition system (like head-and-shoulders or triangle breaks)
Instead, it belongs to the more specialized category of volatility-adjusted stop-and-reverse systems that:
Wait for market volatility to reach actionable levels
Establish positions when price confirms directional bias through stop penetration
Manage risk dynamically based on evolving market conditions
Exit positions when the trend exhausts itself through stop violation
Practical Application and Usage
Market Environment Optimization
Ideal Conditions:
Trending markets with sustained directional movement
Medium volatility environments (neither excessively calm nor chaotic)
Timeframes: 4-hour to daily charts for optimal signal quality
Instruments: Forex majors, commodity futures, equity indices
Suboptimal Conditions:
Ranging or consolidating markets
Extreme volatility events or news-driven spikes
Very short timeframes (below 1-hour)
Illiquid or highly manipulated instruments
Parameter Configuration Strategy
Core Parameter Philosophy:
ATR Length (Default: 21 periods)
Controls the system's memory of volatility
Shorter lengths increase sensitivity but may cause overtrading
Longer lengths provide smoother signals but may lag during volatility shifts
ATR Multiplier (Default: 6.3x)
Determines the initial risk buffer
Lower values (4-5x) create tighter stops for conservative trading
Higher values (6-8x) allow for larger trends but increase drawdown risk
Volatility Threshold (Default: 1.5%)
Filters out low-quality trading environments
Adjust based on market characteristics (higher for volatile markets)
Acts as a quality control mechanism for signals
Trading Workflow and Execution
Signal Interpretation and Action:
Entry Protocol:
Wait for BLUE "BUY" signal label appearance
Confirm volatility conditions meet threshold requirements
Enter long position at market or next reasonable opportunity
Set initial stop at displayed dynamic stop level
Position Management:
Monitor dynamic stop line for position adjustment
Allow profits to run while stop protects capital
No manual adjustment required—system manages stop automatically
Exit Protocol:
Exit on ORANGE "SELL" signal label appearance
Alternative exit if price hits dynamic stop level
System will generate new entry signal if conditions warrant re-entry
Risk Management Integration:
Position sizing based on distance to dynamic stop
Volatility filter prevents trades during unfavorable conditions
Clear visual feedback on current risk exposure
Built-in protection against overtrading
Philosophical Foundation and Market Theory
Core Trading Principles
DATR-TS embodies several foundational market principles:
Volatility Defines Opportunity
Markets don't trend continuously—they alternate between trending and ranging phases
Volatility provides the energy for trends to develop and sustain
By measuring and filtering volatility, we can focus on high-probability trend phases
Risk Should Be Proportional
Fixed percentage stops ignore market context
Dynamic stops that adjust with volatility provide more appropriate risk management
Position sizing should reflect current market conditions, not arbitrary rules
Simplicity Through Sophistication
Complex systems often fail in real-world conditions
A simple core algorithm with intelligent filtering outperforms complex multi-indicator approaches
Clear visual feedback reduces cognitive load and emotional interference
Trends Persist Until Proven Otherwise
Markets exhibit momentum characteristics
Once a trend establishes itself, it tends to continue
The trailing stop methodology captures this persistence while providing exit mechanisms
Mathematical and Statistical Foundation
The system operates on several statistical market observations:
Volatility Clustering Phenomenon
High volatility periods tend to follow high volatility periods
Low volatility periods tend to follow low volatility periods
By filtering for adequate volatility, we increase the probability of capturing meaningful trends
Trend Magnitude Distribution
Most trends are small to medium in magnitude
Very large trends are rare but account for disproportionate returns
The dynamic stop methodology allows capture of varying trend magnitudes
Autocorrelation in Price Movements
Price movements exhibit short-term positive autocorrelation during trends
This persistence allows trailing stops to capture continued movement
The system leverages this characteristic without requiring explicit autocorrelation calculation
Performance Characteristics and Expectations
Typical System Behavior
Signal Frequency:
Low to moderate signal generation (prevents overtrading)
Signals concentrated during trending market phases
Extended periods without signals during ranging conditions
Risk-Reward Profile:
Win rate typically 40-60% in trending conditions
Average win larger than average loss
Risk-reward ratios of 1:2 to 1:3 achievable
Drawdown Patterns:
Controlled through volatility adjustment
Larger drawdowns during extended ranging periods
Recovery typically follows when trending conditions resume
Comparison with Alternative Approaches
Versus Moving Average Systems:
Less prone to whipsaws during ranging markets
Better adaptation to changing volatility conditions
Clearer exit signals through stop levels
Versus Channel Breakout Systems:
More responsive to emerging trends
Lower false breakout probability
Dynamic risk adjustment rather than fixed parameters
Versus Momentum Oscillator Systems:
Better trend persistence capture
Less susceptible to overbought/oversold false signals
Clearer position management rules
Educational Value and Skill Development
Learning Opportunities
DATR-TS serves as more than just a trading tool—it provides educational value through:
Market Condition Awareness
Teaches traders to distinguish between trending and ranging markets
Develops understanding of volatility's role in trading opportunities
Encourages patience and selectivity in trade execution
Risk Management Discipline
Demonstrates dynamic position sizing principles
Illustrates the importance of adaptive stops
Reinforces the concept of risk-adjusted returns
Psychological Skill Development
Reduces emotional trading through clear rules
Builds patience through conditional execution
Develops discipline through systematic approach
Customization and Evolution
The system provides a foundation for further development:
Beginner Level:
Use default parameters for initial learning
Focus on signal recognition and execution discipline
Develop understanding of system behavior across market conditions
Intermediate Level:
Adjust parameters based on specific market characteristics
Combine with complementary analysis techniques
Develop personal variations based on trading style
Advanced Level:
Integrate with portfolio management systems
Develop automated execution frameworks
Create derivative systems for specialized applications
Conclusion: The Modern Trend-Following Paradigm
The Dynamic ATR Trailing System represents a significant evolution in trend-following methodology. By moving beyond simple price pattern recognition or fixed parameter oscillators, it embraces the complex reality of financial markets where volatility, trend persistence, and risk management interact dynamically.
This system doesn't claim to predict market direction or identify tops and bottoms. Instead, it provides a systematic framework for participating in trends when they emerge, managing risk appropriately as conditions change, and preserving capital during unfavorable environments.
For traders seeking a methodology that combines mathematical rigor with practical execution, adapts to changing market conditions rather than fighting against them, and provides clear, actionable information without cognitive overload, DATR-TS offers a sophisticated yet accessible approach to modern trend following.
The true value lies not in any single signal or parameter setting, but in the comprehensive philosophy of volatility-aware, risk-adjusted, conditionally-executed trend participation that the system embodies—a philosophy that aligns with how markets actually behave rather than how we might wish them to behave.
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.
H//@version=5
indicator("H", overlay=true)
// 設定計算的周期
length = input(30, title="Length")
// 計算最近的高點和低點
highestHigh = ta.highest(high, length)
lowestLow = ta.lowest(low, length)
// 畫出支撐和壓力線
line.new(x1=bar_index , y1=highestHigh, x2=bar_index, y2=highestHigh, color=color.red, width=2, extend=extend.right)
line.new(x1=bar_index , y1=lowestLow, x2=bar_index, y2=lowestLow, color=color.blue, width=2, extend=extend.right)
// --- SAR 計算與背景顏色 ---
sar = ta.sar(0.3, 0.3, 0.11)
bgcolor(close > sar ? color.new(color.red, 80) : color.new(color.green, 80))
// Hide the SAR plot by setting color with full transparency using `color.new`
plot(sar, style=plot.style_cross, color=color.new(color.blue, 100), linewidth=2)
// --- 定義時間範圍 ---
var int startHour = 8
var int startMinute = 45
var int endHour = 13
var int endMinute = 45
// 取得當前時間
currentTime = timestamp("GMT+8", year, month, dayofmonth, hour, minute)
startTime = timestamp("GMT+8", year, month, dayofmonth, startHour, startMinute)
endTime = timestamp("GMT+8", year, month, dayofmonth, endHour, endMinute)
// 價差計算
ix0001_price = request.security("IX0001", "1", close)
txf1_price = request.security("TXF1!", "1", close)
price_diff = (ix0001_price - txf1_price) / txf1_price
// 判斷條件:價差達到正或負0.004%且在指定時間範圍內
positive_condition = (price_diff >= 0.004) and (currentTime >= startTime) and (currentTime <= endTime)
negative_condition = (price_diff <= -0.004) and (currentTime >= startTime) and (currentTime <= endTime)
// 根據條件變更背景顏色
bgcolor(positive_condition ? color.new(color.red, 40) : na)
bgcolor(negative_condition ? color.new(color.green, 40) : na)
// --- KD Divergence Marker for 9,3 ---
k_9 = ta.sma(ta.stoch(close, high, low, 9), 3)
d_9 = ta.sma(k_9, 3)
var float lastHighPrice_9 = na
var float lastLowPrice_9 = na
var float lastHighKD_9 = na
var float lastLowKD_9 = na
isTopDivergence_9 = (k_9 > 93 and close < lastHighPrice_9 and k_9 < lastHighKD_9)
isBottomDivergence_9 = (k_9 < 15 and close > lastLowPrice_9 and k_9 > lastLowKD_9)
if ta.crossover(k_9, 97)
lastHighPrice_9 := high
lastHighKD_9 := k_9
if ta.crossunder(k_9, 15)
lastLowPrice_9 := close
lastLowKD_9 := k_9
plotshape(series=isTopDivergence_9, location=location.abovebar, color=color.orange, style=shape.labeldown, text="頂部轉折")
plotshape(series=isBottomDivergence_9, location=location.belowbar, color=color.green, style=shape.labelup, text="底部轉折")
// --- KD Divergence Marker for 14,3 ---
k_14 = ta.sma(ta.stoch(close, high, low, 14), 3)
d_14 = ta.sma(k_14, 3)
var float lastHighPrice_14 = na
var float lastLowPrice_14 = na
var float lastHighKD_14 = na
var float lastLowKD_14 = na
isTopDivergence_14 = (k_14 > 93 and close < lastHighPrice_14 and k_14 < lastHighKD_14)
isBottomDivergence_14 = (k_14 < 15 and close > lastLowPrice_14 and k_14 > lastLowKD_14)
if ta.crossover(k_14, 97)
lastHighPrice_14 := high
lastHighKD_14 := k_14
if ta.crossunder(k_14, 15)
lastLowPrice_14 := close
lastLowKD_14 := k_14
plotshape(series=isTopDivergence_14, location=location.abovebar, color=color.orange, style=shape.labeldown, text="頂部轉折")
plotshape(series=isBottomDivergence_14, location=location.belowbar, color=color.green, style=shape.labelup, text="底部轉折")
// --- Range Breakout ---
// Define the range
range_length = 23
highest_high = ta.highest(high, range_length)
lowest_low = ta.lowest(low, range_length)
// Determine if price is within the range
isInRange = (close >= lowest_low and close <= highest_high)
// Track when price re-enters the range after leaving it
var bool leftRange = false
if close < lowest_low or close > highest_high
leftRange := true
if leftRange and close >= lowest_low and close <= highest_high
leftRange := false
// Plot range only when price is within range
plot(isInRange and not leftRange ? highest_high : na, title="最高盤整區間", color=color.red, linewidth=1, style=plot.style_stepline)
plot(isInRange and not leftRange ? lowest_low : na, title="最低盤整區間", color=color.green, linewidth=1, style=plot.style_stepline)
// --- Volume Crossover Indicator ---
short_ma_length = 5
long_ma_length = 10
volume_multiplier = 3.5
short_ma_volume = ta.sma(volume, short_ma_length)
long_ma_volume = ta.sma(volume, long_ma_length)
current_volume_ratio = volume / short_ma_volume
crossover_condition = ta.crossover(short_ma_volume, long_ma_volume)
volume_condition = current_volume_ratio > volume_multiplier
plotshape(series=crossover_condition and volume_condition and isInRange, location=location.abovebar, color=color.red, style=shape.labelup, text="變盤")






















