Trendlines with Breaks Oscillator [LuxAlgo]The Trendlines with Breaks Oscillator is an oscillator based on the Trendlines with Breaks indicator, and tracks the maximum distance on price from bullish and bearish trendline breakouts.
The oscillator features divergences and trendline breakout detection.
🔶 USAGE
This tool is based on our Trendlines with Breaks indicator, which detects bullish and bearish trendlines and highlights the breaks on the chart. Now, we bring you this tool as an oscillator.
The oscillator calculates the maximum distance between the price and the break of each trendline, for both bullish and bearish cases, then calculates the delta between both.
When the oscillator is above 0, the market is in an uptrend; when it is below 0, it is in a downtrend. An ascending slope indicates positive momentum, and a descending slope indicates negative momentum.
Trendline breaks are displayed as green and red dots on the oscillator. A green dot corresponds to a bullish break of a descending trendline, and a red dot corresponds to a bearish break of an ascending trendline.
The oscillator calculation depends on two parameters from the settings panel: short and long alpha length. These parameters are used to calculate a synthetic EMA with a variable alpha for both bullish and bearish breaks. The final result is the difference between the two averages.
As shown in the image, using the same trend detection parameters but different alphas can produce very different results. The larger the alphas, the smoother the oscillator becomes, detecting bigger trends but making it less reactive.
This tool features the same trendline detection system as the Trendlines with Breaks indicator, which is based on three main parameters: swing length, slope, and calculation method.
As we can see in the image above, the data collected for the oscillator calculation will be different when using different parameters. A larger length detects larger trends. A larger slope or a different calculation method also impacts the final result.
🔹 Signal Line
The signal line is a smoothed version of the oscillator; traders can choose the smoothing method and length used from the settings panel.
In the image, the signal line crossings are displayed as vertical lines. As we can see, the market usually corrects downward after a bearish crossing and corrects upward after a bullish crossing.
Traders can choose among 10 different smoothing methods for the signal line. In the image, we can see how different methods and lengths give different outputs.
🔹 Divergences
The tool features a divergence detector that helps traders understand the strength behind price movements. Traders can adjust the detection length from the settings panel.
As shown in the image, a bearish divergence occurs when the price prints higher highs, but the momentum on the histogram prints lower highs. A bullish divergence occurs when the price prints lower lows, but the histogram prints higher lows.
By adjusting the length of the divergence detector, traders can filter out smaller divergences, allowing the tool to only detect more significant ones.
The image above depicts divergences detected with different lengths; the larger the length, the bigger the divergences are detected.
🔶 SETTINGS
🔹 Trendlines
Swing Detection Lookback: The size of the market structure used for trendline detection.
Slope: Slope steepness, a value of 0 gives horizontal levels, values larger than 1 give a steeper slope
Slope Calculation Method: Choose how the slope is calculated
🔹 Oscillator
Short Alpha Length: Synthetic EMA short period
Long Alpha Length: Synthetic EMA long period
Smoothing Signal: Choose the smoothing method and period
Divergences: Enable or disable divergences and select the detection length.
🔹 Style
Bullish: Select bullish color.
Bearish: Select bearish color.
指标和策略
SK-Trading ABC - Stefan Style The SK System Indicator combines trend, volume, and momentum analysis to generate precise buy and sell signals. Perfect for scalping and swing trading — highlights clear entry/exit zones, trend direction, and potential reversal points in real time.
TraderDemircan Fibonacci + XABCD Formation v1.0This indicator automatically identifies the most recent significant swing low (Point X) and the subsequent swing high (Point A) to plot a comprehensive set of Fibonacci extension levels.
Beyond a standard Fibonacci tool, this script also projects a potential harmonic XABCD pattern. It identifies a retracement level (Point B) and projects a "C" target based on the XA=BC price projection. This provides traders with a complete visual framework of key support/resistance levels and potential price targets based on the last significant impulse move.
How It Works
Swing Detection (X & A Points): The script scans the previous Lookback Bars (user-defined) to find the lowest low, which it labels as Point X. It then finds the highest high that occurred after Point X, labeling it as Point A.
Fibonacci Levels: The price range between X and A (the "XA leg") is used as the basis (0.0 to 1.0) to draw 18 different Fibonacci levels, including key extensions (1.272, 1.618, 2.618, etc.) and retracements.
XABCD Projection (B & C Points):
Point B: The script dynamically identifies Point B at either the 0.382 or 0.5 retracement level of the XA leg, depending on the current price action. This shows the level that is currently acting as support.
Point C (Target): A target (Point C) is projected by adding the price range of the XA leg to the B point. This creates a classic XA=BC (or AB=CD, where the first leg is XA) price projection, offering a potential target for the next upward move.
Key Features
Automatic Swing Detection: Automatically finds and plots the X and A points, adapting to the latest price action.
Comprehensive Fibonacci Suite: Includes 18 toggleable Fibonacci levels (from 0.0 to 4.618) to cover all common retracement and extension targets.
XABCD Pattern & Target: Visually plots the X-A, A-B, and the projected B-C legs, clearly highlighting the C target.
Dynamic "B" Point: The B point label (0.382 or 0.5) updates to reflect which retracement level is currently in play.
On-Screen Info Table: A clean table in the top-right corner displays the exact price values for X, A, B, and the C Target for quick reference.
Full Customization: Users can control the visibility, color, width, and style of every Fibonacci level and pattern line.
Label Options: Toggle price labels (on the right) and percentage/level labels (on the left) for a clean or detailed chart.
Akkam Confirmation (Extended)Disclaimer:
This indicator is not the original GKD-C Trend Akkam script.
It was independently rebuilt from publicly available descriptions, screenshots, and discussions about the indicator’s logic. No proprietary or invite-only source code was used.
The purpose of this publication is educational — to explore how a volatility-adaptive “confirmation” line can be modeled using open methods.
About this version:
Implements an ATR- or Delta-based trailing confirmation line centered on the bar’s open.
Supports optional moving average smoothing of the offset.
Visual flip signals (▲ / ▼) show when direction changes.
Inputs:
• ATR Range — ATR lookback length
• MA Range — optional smoothing of offset
• ATR Factor — multiplier for ATR in ATR mode
• Mode — “ATR” or “Delta Price” offset computation
• Delta Price Dips — lookback length for delta mode
• MA Type — SMA or EMA
Credits & context:
The concept and naming reference GKD-C Trend Akkam (TradingView invite-only).
This script is an open educational approximation, not endorsed by or affiliated with Loxx or the original GKD system.
Use it for learning, experimentation, or as a building block for your own strategies.
Author:
PejoTech (www.tradingview.com
High Volume Zones with Signals – HVZ█ OVERVIEW
"High Volume Zones with Signals – HVZ" is a technical analysis indicator that identifies High Volume Zones (HVZ) on the chart and draws them as fully customizable boxes. Perfect for traders using price action, ICT, and Smart Money Concepts. The indicator highlights key volume-based support/resistance levels, detects potential consolidation zones (very large candles), and generates precise breakout and exit signals. Flexible volume filters, ATR filter, and visual styling options ensure a clean and highly effective chart.
█ CONCEPTS
The indicator detects candles with volume significantly above the average (default ≥ 2× SMA of volume over 20 periods). Such candles often signal institutional activity and create strong supply/demand zones.
The ATR filter additionally identifies very large candles – frequently a sign of market capitulation (panic buying/selling). Within the range of such a candle, prolonged consolidation often occurs, especially on higher timeframes (e.g., 4H and above).
Why are HVZ important? High-volume zones are areas where the market has left a large number of orders – institutions return there to “refresh” liquidity before the next move. A breakout against the zone’s character triggers a Break signal:
- Bullish HVZ broken downward (close below the lower boundary) → Break Down (sell),
- Bearish HVZ broken upward (close above the upper boundary) → Break Up (buy).
Note: The indicator requires real exchange volume – it will not work correctly on instruments without reported volume (e.g., certain CFDs or forex).
█ FEATURES
- HVZ Detection: Automatic identification of high-volume zones with Volume SMA Length and Volume Multiplier filters; historical initialization up to 500 candles back.
- ATR Filter: Optional detection of very large candles (potential consolidation/capitulation) using - ATR Length and ATR Multiplier; three action modes:
Skip Zone – large candle creates no zone,
Separate Color – zone is drawn in a distinct style (gray by default),
Normal Zone – treated like a regular HVZ.
- Gray zones (large candles, Separate Color): generate exactly the same Break signals as regular zones – based solely on the original candle direction (bullish → Break Down on lower break, bearish → Break Up on upper break). Gray color is only a visual marker for potential consolidation/capitulation zones.
- Customizable Boxes: Separate styles for bullish and bearish zones (border color, background gradient, line thickness and style); adjustable background and 50 % midline transparency.
- Break & Exit Signals:
Break Up/Down – green/red triangle after a candle closes outside the zone (zone disappears, triangle remains as a trace).
Exit Up/Down – green/red circle when price leaves the zone without a full breakout.
Signal Type option: Break, Exit, or Both.
- Midline: Automatic dashed line at the 50 % zone level with independent transparency control.
- Chart Cleanup: Automatic removal of inactive zones older than 500 candles (max_boxes_count=500).
- Alerts: Built-in alerts for Break Up and Break Down with clear messages.
█ HOW TO USE
Add to Chart: Paste the script in Pine Editor or find it in TradingView’s indicator library.
Configure Settings:
- Volume Filter: Volume SMA Length (default 20) and Volume Multiplier (default 2.0) – higher multiplier = fewer but stronger zones.
- ATR Filter: Enable/disable, set ATR Length (14) and ATR Multiplier (3.5); choose action for very large candles (Skip Zone / Separate Color / Normal Zone).
- Box Style: Background transparency (90) and midline transparency (70).
- Bull/Bear Box Style: Border and gradient colors, line thickness (1-5).
- ATR Style: Separate colors for large-candle zones (gray by default).
- Signal Settings: Choose Signal Type (Break/Exit/Both) and signal colors.
Signal Interpretation:
- Break Up (green triangle below bar): Bearish HVZ broken upward → buy signal, continuation of uptrend.
- Break Down (red triangle above bar): Bullish HVZ broken downward → sell signal, continuation of downtrend.
- Exit Up/Down (circles): Price leaves zone without breakout – may signal end of correction or reversal setup.
- HVZ Zones: Price often returns to high-volume zones to clear orders. An unfilled zone remains a price magnet.
- 50 % Level (midline): Ideal target for partial take-profit or reaction point inside the zone.
Combine signals with other tools (e.g., RSI, MACD, higher timeframes) for higher confidence.
█ APPLICATIONS
- Price Action & ICT: HVZ act as dynamic S/R; in an uptrend look for buys after breaking a bearish HVZ, in a downtrend look for sells after breaking a bullish HVZ. If you trade retests instead of breakouts, increase Volume Multiplier to 2.5-3.0 – fewer zones but much stronger. Note that after breaking a very strong zone, price often pulls back deeply before continuing.
- Breakout Strategies: For maximum Break signals, lower Volume Multiplier to 1.5-1.8 – gives many high-quality entries in trending markets. Always trade in the direction of the prevailing trend (e.g., only longs in uptrends). Enter after a Break signal with confirmation from volume or momentum (MACD above zero, RSI >50 for longs, <50 for shorts).
█ NOTES
- The indicator requires real exchange volume – it will not function properly on instruments without reported volume (e.g., certain CFDs, forex).
- Always confirm signals with additional context (market structure, higher timeframe).
Smart Price Projection - Crypto Scalping V3Core Functionality
Trend Detection System:
Identifies swing highs/lows to detect breakouts
Requires 3 confirmations: swing break + volume spike + momentum
Uses ADX for trend strength validation
Tracks price structure (higher highs, lower lows)
Statistical Projection Engine:
Stores historical trend data (duration & movement per bar)
Filters by volatility regime (HIGH/MED/LOW)
Uses exponentially weighted averages to favor recent patterns
Projects 3 targets: Conservative (60%), Expected (100%), Aggressive (140%)
Applies momentum decay over projection period
Key Features:
Adaptive: Adjusts projections based on current volatility regime
Quality-aware: Compares current momentum to historical average
Visual: Shows trend phase (EARLY/MID/LATE), momentum strength, ADX, volume
Defensive: Won't project until sufficient sample size builds up
Strengths
✅ Multiple confirmation layers reduce false signals
✅ Volatility-adjusted projections
✅ Momentum decay prevents unrealistic targets
✅ Clean visual feedback with emojis and color coding
Tactical Holding [SwissAlgo]Tactical Holding
A visual framework for managing long-term positions across market cycles
--------------------------------------------------------------
Purpose
Instead of holding a fixed position through all market conditions , you can use this framework to adjust your exposure tactically . By reducing positions during distribution phases and accumulating during favorable accumulation zones, you may end up holding more units of the asset over complete market cycles - even if you temporarily exit or reduce exposure during unfavorable periods. This approach aims to help you compound your holdings by taking advantage of market volatility rather than simply enduring it.
--------------------------------------------------------------
Recommended Settings
Timeframe : Weekly (1W) chart
Chart Type : Standard candlesticks (select 'Bar' type Candles)
This indicator is designed for higher timeframe analysis. While it can be applied to other timeframes, the logic and signal generation are optimized for weekly charts to filter out short-term noise and focus on major market cycles.
--------------------------------------------------------------
Key Features
♦ Market State Classification
The indicator aims to categorize potential market conditions into five color-coded states based on technical confluences:
* Bull (bright green): Multiple bullish indicators align
* Bull Retrace (teal): Bullish structure with temporary weakness
* Bull ⇆ Bear Reversal (yellow): Transitional phase between trends
* Bear (bright red): Multiple bearish indicators align
* Bear Retrace (Pale Red/Maroon): Bearish structure with temporary strength
♦ Visual Elements
* Candles change color based on the current market state
* A 50-period EMA tracks with the same color coding, providing visual trend context
* Small arrow markers appear when specific pattern conditions are met (zones for potential distribution or accumulation)
* A legend table (toggle on/off) explains the color system
* A label shows the current state name on the chart
♦ Pattern Recognition
The system monitors for two types of potential entry/exit zones:
1. State transition patterns after periods of market regime consistency
2. RSI divergence patterns (when price and momentum move in opposite directions)
♦ Customization
* Toggle the legend table visibility through settings
* All calculations are transparent and use standard technical analysis methods
--------------------------------------------------------------
How It Works
Think of this indicator as a traffic light system for your portfolio:
♦ Green zones suggest the asset might be in an environment where long-term holders historically have remained invested
Bright green (Bull) : Multiple technical indicators align in a potentially strong bullish phase
Pale green (Bull Retrace) : Bullish structure remains intact, but momentum shows temporary weakness - often a pullback within an uptrend
♦ Red zones suggest conditions where long-term holders might consider reducing exposure or waiting for better entry points
Dark red (Bear) : Multiple technical indicators align in a potentially strong bearish phase
Pale red (Bear Retrace) : Bearish structure remains intact but shows temporary strength - often a bounce within a downtrend
♦ Yellow zones indicate the market is in transition between bull and bear regimes - a time for increased attention as the trend direction becomes uncertain
The system doesn't predict future prices. Instead, it helps you understand the current technical environment by doing the heavy lifting of analyzing multiple indicators at once and presenting them in a simple visual format.
Example: During the 2022 crypto bear market, the indicator would have displayed extended red periods, signaling defensive conditions for holders. When accumulation arrows appeared in late 2022-early 2023, it highlighted potential re-entry zones as the technical regime transitioned back toward green, before the 2024 recovery.
--------------------------------------------------------------
Who This Is For
♦ Long-term investors who want to hold assets through cycles but prefer a systematic approach to position sizing and timing rather than buying and never selling .
♦ Portfolio managers looking for a visual tool to help determine when to increase or decrease exposure to specific assets based on technical regime changes.
♦ Swing traders on higher timeframes who want to align their positions with the broader market structure rather than fighting the trend.
This is not designed for:
* Day traders or scalpers
* Those seeking exact entry/exit prices
* Automated trading systems (this is a visual decision-support tool)
--------------------------------------------------------------
Understanding the Visuals
When you apply Tactical Holding to a chart, you'll see:
1. Colored candles - Instantly see what market regime the asset is in
2. Colored EMA line (thick line) - Provides a dynamic support/resistance reference that changes color with market conditions
3. Small arrows (↑ ↓) - Mark bars where specific technical patterns complete
4. State label - Shows current market classification
5. Legend table (top right) - Quick reference guide for the color system
6. Warning banner (top center) - Reminds you to use weekly charts
The visual design prioritizes clarity over complexity. You should be able to glance at a chart and immediately understand the current technical environment.
--------------------------------------------------------------
Important Limitations
This indicator cannot:
* Predict future price movements
* Guarantee profitable trades
* Work equally well on all assets or timeframes
* Replace your own research and risk management
Technical considerations:
* Divergence detection has a 3-bar confirmation lag (by design, to avoid false signals)
* State transitions require multiple technical confirmations, which may cause delayed reactions to rapid market changes
* The system is reactive, not predictive - it responds to price action after it occurs
* Performance varies significantly between trending assets (like Solana) and stable assets (like Apple)
--------------------------------------------------------------
Practical Application
Consider using this indicator as one component of a broader investment framework:
♦ Understanding Position Context:
The color-coded states can help frame your thinking about current holdings:
Bull: Technical conditions that have historically been associated with sustained uptrends
Bull Retrace: Pullbacks within an overall bullish structure- these periods may offer opportunities to evaluate entry points or reassess existing positions
Reversal (Yellow): Transitional phases where the trend direction is unclear - periods that may warrant closer monitoring
Bear Retrace: Temporary strength within an overall bearish structure - rallies that historically have often faded
Bear: Technical conditions that have historically been associated with sustained downtrends
♦ Interpreting Signal Arrows:
Arrow markers indicate when specific technical pattern conditions have been met. These are observation points, not instructions:
A signal appearing doesn't mean immediate action is required
Treat arrows as prompts for further analysis rather than automatic triggers
Consider the broader context: fundamentals, your investment timeline, risk tolerance, and overall market conditions
Signals show when historical technical patterns have formed - not whether those patterns will lead to the same outcomes as in the past
The framework is designed to organize information visually, not to tell you what to do. Your investment decisions should incorporate this technical perspective alongside other factors relevant to your situation.
--------------------------------------------------------------
Technical Methodology
For transparency, the indicator uses:
* RSI (14) with a 14-period SMA to assess momentum direction
* MACD (12,26,9) to confirm trend strength and histogram momentum
* Stochastic RSI with K and D line crossovers for additional confirmation
* 50-period EMA as the primary trend filter
* Linear regression-based slope analysis to detect flat/transitional periods
* Pivot-based divergence detection following standard technical analysis principles
All calculations use publicly available technical analysis formulas. Nothing is hidden or proprietary beyond the specific combination and weighting of these standard tools.
--------------------------------------------------------------
Disclaimer
This indicator is an educational and analytical tool only. It is not financial advice.
* Trading and investing involve substantial risk of loss
* Past performance of any technical system does not indicate future results
* No indicator can predict market movements with certainty
* Always conduct your own research and consult with qualified financial professionals
* Never invest more than you can afford to lose
* The creators of this indicator are not responsible for any trading losses
* This tool is not affiliated with, endorsed by, or connected to TradingView, 3Commas, or any other trading platform
* Use of this indicator is at your own risk
Risk Management: Regardless of what any indicator shows, always use proper position sizing, stop losses, and risk management appropriate to your personal financial situation.
This indicator provides a framework for analysis. Your decisions, research, and risk management determine your results.
Swing High/Low Support ResistanceThis indicator detects recent swing highs and swing lows using Pine Script pivots and marks them with visible chart labels. These points highlight potential turning areas in price action and can help identify short-term support or resistance for intraday or swing trading.
How to Apply
Locate the indicator in TradingView’s “Indicators” library; search by its name or author.
Click the star icon to mark it as a favourite for quick future access.
Apply directly to your chosen chart and timeframe with a single click—no need to enter or paste code.
Adjust the input parameters from the settings panel if desired to personalize swing sensitivity.
Choose Your Timeframe:
Apply to any intraday or swing timeframe; shorter lengths show more frequent pivots.
Set Sensitivity:
Use the “Swing Detection Length” input to adjust how many bars define a pivot, making swings more or less sensitive to price action.
How to Analyze
Swing High Labels: Mark recent local peaks, suggesting resistance zones or possible reversal points.
Swing Low Labels: Highlight recent bottoms, indicating support or bounce areas.
Monitor labels for clustering or repeated appearance at similar levels, which may strengthen their importance as price reacts near those points.
Track how price behaves after forming new pivots—multiple tests can affirm the relevance of a level.
What Traders Should Watch
Price reaction at labeled areas: frequent tests may anticipate reversals or breakouts.
Transition between higher highs/higher lows (uptrend) vs. lower highs/lower lows (downtrend).
Combine the swing levels with other analysis methods, such as volume, RSI, or EMA, for better signal quality.
Features Included
Dynamic swing high and low detection via confirmed pivots.
Direct labeling on the chart for market structure clarity.
No repainting—labels show only after complete formation.
Fully automatic updates as price action unfolds.
No promotional, external, or non-compliant elements; open source and safe for public or private use.
Compliance Notes
No signals, buy/sell calls, financial advice, or performance claims.
No hidden code, advertising, or off-platform contacts.
Pure educational and analytical utility; adheres to all TradingView house rules and script publishing policies.
Disclaimer
This indicator is for informational purposes only and does not constitute advice. Always do your own research and use proper risk management.
Market Breadth - [JTCAPITAL]Market Breadth - is a comprehensive crypto market strength and sentiment indicator designed to visualize the overall bullish or bearish alignment across 40 major cryptocurrencies. By combining multi-asset Exponential Moving Average (EMA) comparisons and smoothing techniques, it offers a clean, aggregated view of the broader market trend—helping traders quickly assess whether the market is dominated by bullish momentum or bearish pressure.
The indicator works by calculating in the following steps:
Symbol Selection and Data Retrieval
The script monitors 40 leading cryptocurrencies based on Market Cap. Each asset’s daily close price is requested using a 1D timeframe. This ensures that every data point reflects the same temporal resolution, allowing the indicator to evaluate global crypto strength rather than individual token volatility.
EMA Comparison per Asset
For each asset, two Exponential Moving Averages (EMAs) are calculated:
A short-term EMA with period emalength (default 10).
A long-term EMA with period emalength2 (default 20).
Each coin receives a score of +1 when the short-term EMA is greater than the long-term EMA (indicating bullish structure), or -1 when it is below (indicating bearish structure). This binary scoring system effectively converts individual price action into a directional sentiment measure.
Market Breadth Aggregation
All 40 individual scores are summed into a single composite value called scores .
If many assets have bullish EMA alignment, the total score becomes strongly positive.
If the majority show bearish alignment, the total score turns negative.
This step transforms scattered price data into one unified market breadth metric—quantifying how many assets participate in the same directional trend.
Smoothing the Breadth Line
To reduce short-term noise and isolate trend direction, the aggregated score is smoothed using an EMA of length = smoothlen (default 15). The resulting smoothed line helps identify sustained shifts in collective sentiment rather than temporary fluctuations.
Visualization and Color Coding
When scores > 0 , the market breadth is bullish and the histogram is colored blue.
When scores < 0 , the breadth turns bearish and the histogram is purple.
The same logic applies to the smoothed line and background color, offering an instant visual cue of market mood transitions.
Buy and Sell Conditions:
The indicator itself does not trigger direct buy/sell signals but rather acts as a market regime filter . Traders can use it as follows:
Buy Filter: When the smoothed value is above zero and rising, the majority of assets confirm an uptrend — this favors long setups or trend continuation entries.
Sell Filter: When the smoothed value is below zero and falling, bearish alignment dominates — ideal for short setups or defensive risk management.
Optional filters could include combining this with RSI or volume-weighted momentum indicators to confirm breadth-based reversals.
Features and Parameters:
emalength – Defines the short-term EMA length used for individual asset trend detection (default 10).
emalength2 – Defines the long-term EMA length (default 20).
smoothlen – Defines the smoothing EMA length for the total market breadth line (default 15).
40 asset inputs – User-editable symbols allow full customization of which cryptos are tracked.
Dynamic color backgrounds – Visual distinction between bullish and bearish phases.
Specifications:
Exponential Moving Average (EMA)
EMA is a type of moving average that places more weight on recent price data, responding faster to market changes compared to SMA. By comparing a short-term and long-term EMA, the indicator captures momentum shifts across each asset individually. The crossover logic (EMA10 > EMA20) signals bullish conditions, while the opposite indicates bearish momentum.
Market Breadth
Market Breadth quantifies how many assets are participating in a directional move. Instead of tracking a single coin’s trend, breadth analysis measures collective sentiment. When most coins’ short-term EMAs are above long-term EMAs, the market shows healthy bullish breadth. Conversely, when most are below, weakness dominates.
Smoothing (EMA on Scores)
After summing the breadth score, the result is smoothed with an additional EMA to mitigate the inherent volatility caused by individual coin reversals. This second-level smoothing transforms raw fluctuations into a readable, trend-consistent curve.
Color Visualization
Visual cues are integral for intuitive interpretation.
Blue Shades: Indicate bullish alignment and collective upward momentum.
Purple Shades: Indicate bearish conditions and potential risk-off phases.
The background tint reinforces visual clarity even when the indicator is overlaid on price charts.
Background Logic
By applying the same color logic to the chart’s background, users can instantly recognize the prevailing market phase.
Use Cases
As a trend confirmation filter for other indicators (e.g., trade only in the direction of positive breadth).
As a divergence tool : when price rises but breadth weakens, it may signal a topping market.
As a macro sentiment monitor : perfect for assessing when the crypto market as a whole transitions from bearish to bullish structure.
Summary
“ Market Breadth - ” transforms the chaotic price movements of 40 cryptocurrencies into a single, powerful visual representation of overall market health. By merging EMA cross analysis with market-wide aggregation and smoothing , it provides traders with a deep understanding of when bullish or bearish forces dominate the ecosystem.
It’s a clean, data-driven approach to identifying shifts in crypto market sentiment — a perfect companion for trend-following, macro analysis, and timing portfolio exposure.
Enjoy!
Mickey's Breaker Engine⚡ Breaker Engine | Auto Retest + Smart R:R Targets
A precision-grade breaker-block detection system built for traders who live and breathe clean structure.
This indicator automatically detects Breaker Candles, confirms them, marks their zones, and executes intelligent retest-based entry logic — complete with Stop-Loss and Risk-to-Reward (R:R) tracking up to 3R (or any custom ratio).
🧠 Core Concept
A Breaker Block is a structural shift where price violates liquidity from a failed order block and flips the zone’s polarity — turning a former supply into demand (or vice-versa).
This script identifies those setups automatically, confirms them only after a valid structure break, and waits for a clean retest to trigger a trade signal.
🚀 Key Features
⚙️ Smart Zone Detection
Detects both Bullish Breakers and Bearish Breakers.
Zones are drawn precisely using the breaker’s middle candle body (or full wick range if enabled).
Fully configurable transparency, width, and extension for better visual context.
🎯 Auto Retest Entry Logic
Entry triggers only on a clean retest, not on immediate breakout.
Includes logical filters to ensure retests are structurally valid and not overlapping candles.
Works in any timeframe or market — crypto, forex, indices, or commodities.
💡 Dynamic Risk–Reward Tracking
Automatically plots 1R, 2R, 3R, ...R targets based on your defined stop range.
Risk is calculated from entry to zone boundary or ATR offset.
Each target label appears precisely when hit.
Targets automatically stop updating once Stop-Loss is triggered.
🧱 Visual Clarity
BUY 🟢 / SELL 🔴 bubbles at entries.
SL ❌ marker when stop is hit.
🎯 1R / 2R / 3R labels dynamically plotted when each reward level is reached.
Non-overlapping placement using ATR-based spacing.
⚡ Real-Time Alerts - Instant alerts for:
✅ “Breaker BUY” – Clean retest confirmed (Long setup)
✅ “Breaker SELL” – Clean retest confirmed (Short setup)
❌ “Breaker BUY SL” – Stop hit for Long
❌ “Breaker SELL SL” – Stop hit for Short
🧩 Customization Panel
| Setting | Description |
| :-------------------------- | :------------------------------------------------------------------------------ |
| **ATR Length** | Controls volatility-based offset sizing. |
| **Entry / SL Offset × ATR** | Adjusts label spacing and dynamic positioning. |
| **Risk-Reward Ratio** | Define default R:R (e.g. 1:3). |
| **Multiple Retests** | Enable if you want the same breaker zone to allow multiple retests/entries. |
| **Banner Design** | Control opacity, extension, and wick usage for the breaker block visualization. |
| **Color Controls** | Choose your BUY/SELL/SL bubble colors to match your chart theme. |
⚙️ Underlying Logic (At a Glance)
Pattern Detection:
Identifies a 5-bar sequence that forms a valid Breaker Candle (the middle bar flips structure).
Confirmation:
Requires a follow-through candle to validate a real liquidity break.
Zone Registration:
Stores the breaker zone’s body range in arrays for tracking.
Clean Retest Entry:
Waits for price to retest the zone from the opposite side and close cleanly inside.
Stop Loss / Target Projection:
Defines stop loss just beyond the zone and plots up to 3 × reward targets dynamically.
Monitoring & Alerts:
Tracks each setup independently until either an R-target or SL is reached.
💬 Recommended Usage
Works best with market-structure traders, smart-money concepts, or liquidity-based systems.
Combine it with an external displacement confirmation or BOS/CHOCH tool for best precision.
Ideal for backtesting breaker-based R:R consistency or forward-testing retest entries.
Compatible with any asset / timeframe.
🧭 Disclaimer
This script is for educational and analytical purposes only.
It is not financial advice and should not be used to make trading decisions without independent confirmation or risk management.
Always test on demo data before deploying live.
Avg % Move Dashboard — Body and WicksTitle
Avg % Move Dashboard — Body and Wicks (w/ True Range)
Summary
Compact right-side dashboard showing the average percent move of recent candles:
Body size (absolute % from Open to Close)
Body bias (signed %, with up/down arrow and color)
Full range (High–Low %)
True range (ATR-style % relative to previous close)
Perfect for quickly gauging current market velocity and directional skew on any symbol or timeframe.
How It Works
Body % (per bar): (Close − Open) / Open × 100
Full range % (per bar): (High − Low) / Open × 100
True range % (per bar): max(High−Low, |High−PrevClose|, |Low−PrevClose|) / PrevClose × 100
Averages: Simple moving averages over the last N candles
Rounding: Values rounded to your chosen decimals
Bias row: shows signed average body percent with an ↑/↓ arrow and green/red color; near-zero values can display a neutral ⟷ based on a threshold
Settings
Candles to average (default 20): Window length for SMA calculations.
Decimals: Rounding precision for display.
Dashboard position: Top/Middle/Bottom Right.
Dashboard size: Tiny, Small, Normal, Large, Huge.
Background Color: Panel background.
Text Color (size rows): For non-bias rows.
Near-zero threshold (%): If the average body bias absolute value is below this, show neutral (⟷) instead of bullish/bearish.
What to show (toggles):
Show Body (Open→Close)
Show Full Range (High→Low)
Show True Range (ATR-style)
What You’ll See
Body size: average absolute body percent (magnitude only).
Body bias: average signed body percent with:
↑ and green if bullish
↓ and red if bearish
⟷ and gray if within the near-zero threshold
Full Range: average percent from High to Low.
True Range: average percent true range relative to previous close.
Footer: n = number of candles used.
How to Use
Add to any chart and timeframe; it overlays a table on the right-side.
Use “Body size” to assess typical candle strength.
Use “Body bias” to see directional skew:
Strong positive = persistent buying pressure.
Strong negative = persistent selling pressure.
Near-zero = balanced/sideways conditions.
Compare “Full range” vs “Body size”:
Large range but small body may indicate indecision or wicky conditions.
“True range” offers a classic ATR-style read (relative to prior close), useful for volatility-aware sizing.
Adjust “Candles to average” to your timeframe:
Short-term (scalps): 20–50
Intraday: 50–100
Swing: 100–200+
Best Practices
Pair with structure (S/R, sessions) to avoid false impressions in thin markets.
Increase length on noisy pairs/timeframes to smooth out noise.
Use the near-zero threshold to suppress micro-bias and focus on meaningful shifts.
Alerts
This dashboard is informational and doesn’t define alertconditions in the code. If you’d like, I can add optional alerts (e.g., bias flips from bearish to bullish beyond threshold, or volatility spikes on TR) — just say the word.
Limitations
This panel summarizes recent averages; it’s not a signal generator.
Values can differ across assets/timeframes; tune “Candles to average.”
True Range uses prev close normalization; that’s by design for ATR-style context.
Changelog
v1.0: Initial release — Body size, Body bias (with arrows/colors/neutral), Full Range, True Range, configurable UI.
Session Breakout, Retest, Reversal + Large Move Alert## **Session Breakout, Retest, Reversal + Large Move Alert**
### Overview
A powerful multi-functional indicator designed for day traders and futures traders to identify session-based breakout opportunities, retest confirmations, and significant price movements across all futures contracts (Gold, E-mini S&P 500, Nasdaq, Crude Oil, and more).
### Key Features
**📊 Pre-Market Session Tracking**
- Automatically calculates pre-market/overnight session highs and lows
- Displays session ranges with customizable colors and styling
- Extends lines through the entire trading session for easy reference
- Supports overnight sessions (e.g., 4 PM – 7:30 AM for Gold futures)
**🚀 Breakout Detection**
- Identifies breakouts above/below pre-market highs and lows
- Uses close-price confirmation to filter false signals from wicks
- Displays "BO ↑" and "BO ↓" labels at breakout points
- Generates instant alerts when breakouts occur
**♻️ Retest Failed Tracking**
- Monitors price retests after breakouts
- Detects when retests fail to reach previous support/resistance
- Labels "RF" (Retest Failed) for high-probability trade setups
- Helps identify reversal opportunities
**📈 First 5-Minute Analysis**
- Captures first 5 minutes of market open (customizable timeframe)
- Tracks first 5-minute highs and lows separately
- Essential for mean-reversion and breakout confirmation strategies
- Blue lines extend through the trading session for easy tracking
**⚡ Large Move Alerts**
- Detects significant price movements based on point thresholds
- Individual thresholds for 5+ different symbols:
- GC (Gold): 15 points
- ES (E-mini S&P 500): 15 points
- NQ (E-mini Nasdaq): 50 points
- CL (Crude Oil): 1.5 points
- Custom: Fully adjustable
- Auto-detects symbol from chart ticker
- Labels show exact point movement and candle direction
### Customization Options
**Symbol Configuration**
- **Auto-Mode**: Automatically detects trading symbol from chart ticker
- **Manual-Mode**: Select specific symbol (GC, ES, NQ, CL, or Custom)
**Session Settings**
- Fully customizable pre-market session time (24-hour format)
- Adjustable market open time for first 5-minute window
- Market close hour and minute configuration
- Support for any timezone
**Point Move Thresholds by Symbol**
- Set independent thresholds for each of your trading symbols
- Quickly adjust settings when switching between different futures
- Includes helpful tooltips for recommended values
**Display & Styling**
- Toggle all visual elements on/off individually
- Customizable colors for all lines and labels:
- Pre-market high/low colors
- Breakout labels (up/down)
- Retest failed labels
- First 5-minute session lines
- Large move indicators
- Text size options: tiny, small, normal, large, huge
### How It Works
1. **Session Tracking**: The indicator identifies your pre-market session and marks the high and low with labeled lines (PH/PL)
2. **Breakout Signal**: Once the market opens, it monitors for close prices above/below the pre-market levels and alerts you with "BO ↑" or "BO ↓"
3. **Retest Confirmation**: After a breakout, it tracks retests and labels "RF" when the retest fails to reach the opposite extreme, confirming trade direction
4. **Large Move Detection**: Simultaneously monitors for significant point moves that exceed your symbol-specific thresholds
5. **Alert Triggers**: Get real-time alerts for:
- Breakout Up/Down
- Any Breakout
- Large Move events
### Alert Conditions
The indicator includes four alert conditions:
- **Breakout Up Alert**: Price closes above pre-market high
- **Breakout Down Alert**: Price closes below pre-market low
- **Any Breakout Alert**: Either breakout condition triggers
- **Large Move Alert**: Point movement exceeds threshold for current symbol
### Ideal For
- ✅ Day traders (breakout/retest strategies)
- ✅ Futures traders (Gold, Oil, Stock Index Contracts)
- ✅ Intraday scalpers (first 5-minute analysis)
- ✅ Swing traders (session-based levels)
- ✅ Multi-symbol traders (independent thresholds per symbol)
### Disclaimer
This indicator is designed for educational and informational purposes. Past performance does not guarantee future results. Always use proper risk management and position sizing. Test thoroughly on historical data before trading live.
FC Session & Levels: Killzone, FVG, BB, OB, MAs, VWAP, Zizag FibFC Session & Levels – Ultimate Multi-Tool Trading Indicator
All-in-one professional-grade indicator combining session analysis, key levels, institutional concepts, and trend tools for futures, forex, crypto, and stocks.
Core Features
Real-time Session High/Low tracking for Asia, London, NY AM/PM, MOC
Dynamic Daily Pivot Points with R1–R3 / S1–S3 levels
Configurable Opening Range Breakout (ORB) 15-min high/low from NY open
Smart VWAP, EMA/SMA crosses, Trend Cloud (EMA38/62)
CHoCH (Change of Character) detection with dotted breakout lines
Fair Value Gaps (FVG) with volume & ATR filtering
Advanced ZigZag + Fibonacci Retracement/Extension levels
Institutional Order Blocks & Breaker Blocks with mitigation tracking
How to Use – Step-by-Step Instructions
1. Add to Chart
Open TradingView → Indicators → Search " FC Session & Levels "
Add to any chart (works on all timeframes, best on 1m–1H)
2. Configure Time Zone
Set Time Zone to UTC-5 (Standard Time) or UTC-4 (Daylight Saving)
NYT sessions auto-adjust
3. Enable Sessions
Toggle: Asia, London, NY AM, NY PM, MOC
Each draws high/low lines + optional labels
Colors fully customizable
4. Pivot & Pre-Market Levels
Daily Pivot (PP) + R1–R3 / S1–S3 auto-calculated
Pre-Day High/Low (purple) & Pre-Week High/Low (blue)
Daily Open line (cyan)
Extend future lines with Extend Future
5. Opening Range Breakout (ORB)
Enable ORB 15min High/Low
Set start: 9:30 AM , end: 9:45 AM (NYT)
Lines extend ± N bars (default 5)
Great for breakout entries
6. VWAP & Moving Averages
Toggle VWAP , MA9/20 cross , MA50/100/200
Trend Cloud : EMA38 (fast) vs EMA62 (slow) → bullish/bearish fill
7. CHoCH – Change of Character
Detects swing breaks with 20-bar lookback
Draws dotted line from swing point to breakout
Labels: "CHoCH" in green (bull) or red (bear)
8. Fair Value Gaps (FVG)
Detects gaps > 0.5× ATR with volume > 1.2× avg
Draws semi-transparent boxes + midline
Max 10 FVGs , auto-expire after 50 bars
9. ZigZag + Fibonacci
ZigZag period: 15 (adjustable)
Auto-draws 0.236, 0.382, 0.5, 0.618, 0.786 levels
Labels show ratio + price
Extends to right on last leg
10. Order Blocks & Breaker Blocks
Detects institutional zones using swing + volume
Filters by size (0–30%) and volume multiplier
Shows last 5 Bull / 5 Bear OBs
Breaker Blocks : when OB is broken → becomes supply/demand
Mitigation tracking : 50%, Close, or Wick
Strength score (0–100) → stronger = bolder color
11. Statistics Dashboard
Toggle Show Statistics Table
Displays: Total OBs, Breakers, Bull/Bear counts
Position: Top/Bottom, Left/Right
12. Alerts
Bullish OB Formation
Bearish OB Formation
Breaker Block Formation
Polarity Change (▲/▼)
Best Practices & Tips
Use on 1m, 3m, 5m, 15m for intraday
Combine ORB + CHoCH for high-probability breakouts
Wait for FVG retest in direction of trend
Strong OBs (>70 strength) = high confluence zones
Use Pre-Week H/L for weekly bias
MOC session (15:50–16:00) = final 10min imbalance
Customization Options
Colors : All lines, boxes, labels
Opacity : Pivot (0–100%), FVG, OB
Line Width : OB/Breaker lines
Display Mode : Boxes, Lines, or Both
Labels : Session, FVG, CHoCH, Polarity
Author : futurescall @ fcalgobot.com . discord.gg
Credit: @LuxAlgo for BB, OB . Zigzag base on @LonesomeTheBlue
The Ultimate Price Action & SMC Toolkit: Delta Zones, MTF IndicaThis is an All-in-One Pine Script indicator that seamlessly combines three advanced trading concepts:
Delta Zones (Wick Pressure): Uses Standard Deviation to identify extreme buying/selling pressure within the candlestick wicks, signaling potential stop hunts or liquidity absorption. These are plotted as critical Buy/Sell Boxes.
Multi-Timeframe (MTF) Indicators: Confirms signals using popular indicators (RSI, CCI, Stochastic) calculated from a separate, user-selected Timeframe or the current chart timeframe. This adds a crucial layer of context and momentum confirmation.
Smart Money Concepts (SMC): Automatically detects and plots Orderblocks (OBs) and Breaker Blocks based on confirmed Market Structure Breaks (MSB). This helps locate high-probability Supply and Demand zones.
Key Features:
Integrated plotting for combined indicator signals.
Flexible MTF selection for all standard oscillators.
Automatic Swing High/Low detection for SMC analysis.
Comprehensive Alert system for Delta Pressure, Orderblocks, and Breaker Zones.
Option 2: Focusing on SMC and Flow (Concise)
Title: "SMC Delta Flow: Advanced Orderblock, Breaker, and Wick Reversal Zones with MTF Filter."
Description:
An essential tool for sophisticated SMC traders. This indicator provides high-precision zones:
Smart Money Blocks: Plots Orderblocks and Breaker Blocks following Market Structure Shifts (MSS). Includes a "Chop Control" feature to invalidate re-used or weak Breakers.
Delta Reversal Zones: Pinpoints candles showing extreme high-deviation wick pressure. Use these zones to confirm reversals and identify precise entry points where liquidity was captured.
MTF Confirmation: Incorporates configurable Multi-Timeframe (MTF) RSI, CCI, and Stochastic indicators to act as a momentum filter or confirmation tool.
Add this indicator to unify your analysis of Liquidity, Market Structure, and Momentum on a single chart!
SMC, SmartMoneyConcepts, Orderblock, BreakerBlock, MTF, MultiTimeframe, Delta, Wick, Liquidity, PriceAction, RSI, Stochastic, CCI
Volume Climax Reversal (VCR) — Catch Exhaustion Tops & Bottoms New! VCR spots exhaustion spikes at highs/lows using volume extremes + price action + VWAP context.
If you trade parabolic runners, indices, or mean-reversion edges, VCR helps you time the backside (shorts) and fade capitulation (longs) with clean, rule-based signals.
What it does
Detects volume climax: current volume > SMA(len) × multiplier and a new volume high in the lookback.
Confirms price context: makes a higher high (for tops) or lower low (for bottoms).
Filters with VWAP (optional): bearish signals only below VWAP, bullish signals only above VWAP.
Optional wick filter: requires an exhaustion wick > body to reduce chop.
Why traders like it
Clear entries: “VCR↓” (bearish) at exhaustion tops, “VCR↑” (bullish) at washout lows.
Fewer false signals: VWAP gating + wick filter focus on true climaxes.
Built-in alerts: set once, get notified on your phone/desktop when a setup appears.
How I trade it (simple playbook)
Bearish reversal (short / puts)
Wait for VCR↓ (exhaustion at/near HH).
Look for a lower high that fails to reclaim the signal candle high.
Enter on the break of that lower-high candle low.
Stop above the signal wick high.
Covers/targets: VWAP first; then 20–30% fade from the local top / prior demand.
Bullish reversal (long / calls)
Wait for VCR↑ (capitulation at/near LL).
Look for a higher low that holds above the signal candle low.
Enter on the break of the HL candle high.
Stop below the signal wick low.
Targets: VWAP first; then prior supply/MA bands.
Tip for small-cap/“Dux” style: VCR pairs perfectly with a gap + high USD-rotation scan. Let them blow off, then use VCR for the timing.
Inputs (tune to your market)
Volume SMA Length (default 20)
Volume Spike Multiplier (default 2.0)
Lookback High / Low (default 10 / 10)
Require VWAP confirmation? (on)
Use wick filter? (on)
Works on stocks, indices, futures, crypto.
Timeframes: 1–15m for day trading; 1h–4h–D for swing.
Alerts
Set one (or both) alerts and forget it:
Bearish Volume Climax — VCR↓
Bullish Volume Climax — VCR↑
You’ll get instant notifications when a qualified top/bottom prints.
Best practices
Don’t countertrend the first front-side ramp—wait for the VCR and a lower-high/higher-low.
Respect VWAP: it’s your first profit-taking and a bias filter.
Size small into volatility; widen stops in fast markets.
Combine with your watchlist filters (gap %, float/O/S, USD rotation, session timing).
What’s included
Clean visual signals (triangles + subtle background shading)
Session-anchored VWAP
Alert conditions that appear in TradingView’s alert menu
Sensible defaults + clear docs (this post)
FAQ
Q: Does it repaint?
No. VCR uses completed-bar data; signals print end-of-bar.
Q: Which markets?
Anything with volume: US equities, futures, crypto, indices.
Q: Can I use it for scalps?
Yes—1–5m with wick filter on and VWAP required works well.
Get more / upgrades
I’m iterating fast (MTF filter, heatmap panel, combined “one-alert” mode).
Want the pro template with dashboard & combined alerts? Message me on TV or DM / email you@domain.com
.
Risk Notice
This is educational research, not financial advice. Markets carry risk—always manage position size and use stops.
If this helped you, smash the 👍 and ⭐ — it really helps!
#volume #vwap #reversal #exhaustion #trendreversal #smallcaps #scalping #daytrading #swingtrading #stocks #futures #crypto #indicator
Algorithm Predator - ML-liteAlgorithm Predator - ML-lite
This indicator combines four specialized trading agents with an adaptive multi-armed bandit selection system to identify high-probability trade setups. It is designed for swing and intraday traders who want systematic signal generation based on institutional order flow patterns , momentum exhaustion , liquidity dynamics , and statistical mean reversion .
Core Architecture
Why These Components Are Combined:
The script addresses a fundamental challenge in algorithmic trading: no single detection method works consistently across all market conditions. By deploying four independent agents and using reinforcement learning algorithms to select or blend their outputs, the system adapts to changing market regimes without manual intervention.
The Four Trading Agents
1. Spoofing Detector Agent 🎭
Detects iceberg orders through persistent volume at similar price levels over 5 bars
Identifies spoofing patterns via asymmetric wick analysis (wicks exceeding 60% of bar range with volume >1.8× average)
Monitors order clustering using simplified Hawkes process intensity tracking (exponential decay model)
Signal Logic: Contrarian—fades false breakouts caused by institutional manipulation
Best Markets: Consolidations, institutional trading windows, low-liquidity hours
2. Exhaustion Detector Agent ⚡
Calculates RSI divergence between price movement and momentum indicator over 5-bar window
Detects VWAP exhaustion (price at 2σ bands with declining volume)
Uses VPIN reversals (volume-based toxic flow dissipation) to identify momentum failure
Signal Logic: Counter-trend—enters when momentum extreme shows weakness
Best Markets: Trending markets reaching climax points, over-extended moves
3. Liquidity Void Detector Agent 💧
Measures Bollinger Band squeeze (width <60% of 50-period average)
Identifies stop hunts via 20-bar high/low penetration with immediate reversal and volume spike
Detects hidden liquidity absorption (volume >2× average with range <0.3× ATR)
Signal Logic: Breakout anticipation—enters after liquidity grab but before main move
Best Markets: Range-bound pre-breakout, volatility compression zones
4. Mean Reversion Agent 📊
Calculates price z-scores relative to 50-period SMA and standard deviation (triggers at ±2σ)
Implements Ornstein-Uhlenbeck process scoring (mean-reverting stochastic model)
Uses entropy analysis to detect algorithmic trading patterns (low entropy <0.25 = high predictability)
Signal Logic: Statistical reversion—enters when price deviates significantly from statistical equilibrium
Best Markets: Range-bound, low-volatility, algorithmically-dominated instruments
Adaptive Selection: Multi-Armed Bandit System
The script implements four reinforcement learning algorithms to dynamically select or blend agents based on performance:
Thompson Sampling (Default - Recommended):
Uses Bayesian inference with beta distributions (tracks alpha/beta parameters per agent)
Balances exploration (trying underused agents) vs. exploitation (using proven winners)
Each agent's win/loss history informs its selection probability
Lite Approximation: Uses pseudo-random sampling from price/volume noise instead of true random number generation
UCB1 (Upper Confidence Bound):
Calculates confidence intervals using: average_reward + sqrt(2 × ln(total_pulls) / agent_pulls)
Deterministic algorithm favoring agents with high uncertainty (potential upside)
More conservative than Thompson Sampling
Epsilon-Greedy:
Exploits best-performing agent (1-ε)% of the time
Explores randomly ε% of the time (default 10%, configurable 1-50%)
Simple, transparent, easily tuned via epsilon parameter
Gradient Bandit:
Uses softmax probability distribution over agent preference weights
Updates weights via gradient ascent based on rewards
Best for Blend mode where all agents contribute
Selection Modes:
Switch Mode: Uses only the selected agent's signal (clean, decisive)
Blend Mode: Combines all agents using exponentially weighted confidence scores controlled by temperature parameter (smooth, diversified)
Lock Agent Feature:
Optional manual override to force one specific agent
Useful after identifying which agent dominates your specific instrument
Only applies in Switch mode
Four choices: Spoofing Detector, Exhaustion Detector, Liquidity Void, Mean Reversion
Memory System
Dual-Layer Architecture:
Short-Term Memory: Stores last 20 trade outcomes per agent (configurable 10-50)
Long-Term Memory: Stores episode averages when short-term reaches transfer threshold (configurable 5-20 bars)
Memory Boost Mechanism: Recent performance modulates agent scores by up to ±20%
Episode Transfer: When an agent accumulates sufficient results, averages are condensed into long-term storage
Persistence: Manual restoration of learned parameters via input fields (alpha, beta, weights, microstructure thresholds)
How Memory Works:
Agent generates signal → outcome tracked after 8 bars (performance horizon)
Result stored in short-term memory (win = 1.0, loss = 0.0)
Short-term average influences agent's future scores (positive feedback loop)
After threshold met (default 10 results), episode averaged into long-term storage
Long-term patterns (weighted 30%) + short-term patterns (weighted 70%) = total memory boost
Market Microstructure Analysis
These advanced metrics quantify institutional order flow dynamics:
Order Flow Toxicity (Simplified VPIN):
Measures buy/sell volume imbalance over 20 bars: |buy_vol - sell_vol| / (buy_vol + sell_vol)
Detects informed trading activity (institutional players with non-public information)
Values >0.4 indicate "toxic flow" (informed traders active)
Lite Approximation: Uses simple open/close heuristic instead of tick-by-tick trade classification
Price Impact Analysis (Simplified Kyle's Lambda):
Measures market impact efficiency: |price_change_10| / sqrt(volume_sum_10)
Low values = large orders with minimal price impact ( stealth accumulation )
High values = retail-dominated moves with high slippage
Lite Approximation: Uses simplified denominator instead of regression-based signed order flow
Market Randomness (Entropy Analysis):
Counts unique price changes over 20 bars / 20
Measures market predictability
High entropy (>0.6) = human-driven, chaotic price action
Low entropy (<0.25) = algorithmic trading dominance (predictable patterns)
Lite Approximation: Simple ratio instead of true Shannon entropy H(X) = -Σ p(x)·log₂(p(x))
Order Clustering (Simplified Hawkes Process):
Tracks self-exciting event intensity (coordinated order activity)
Decays at 0.9× per bar, spikes +1.0 when volume >1.5× average
High intensity (>0.7) indicates clustering (potential spoofing/accumulation)
Lite Approximation: Simple exponential decay instead of full λ(t) = μ + Σ α·exp(-β(t-tᵢ)) with MLE
Signal Generation Process
Multi-Stage Validation:
Stage 1: Agent Scoring
Each agent calculates internal score based on its detection criteria
Scores must exceed agent-specific threshold (adjusted by sensitivity multiplier)
Agent outputs: Signal direction (+1/-1/0) and Confidence level (0.0-1.0)
Stage 2: Memory Boost
Agent scores multiplied by memory boost factor (0.8-1.2 based on recent performance)
Successful agents get amplified, failing agents get dampened
Stage 3: Bandit Selection/Blending
If Adaptive Mode ON:
Switch: Bandit selects single best agent, uses only its signal
Blend: All agents combined using softmax-weighted confidence scores
If Adaptive Mode OFF:
Traditional consensus voting with confidence-squared weighting
Signal fires when consensus exceeds threshold (default 70%)
Stage 4: Confirmation Filter
Raw signal must repeat for consecutive bars (default 3, configurable 2-4)
Minimum confidence threshold: 0.25 (25%) enforced regardless of mode
Trend alignment check: Long signals require trend_score ≥ -2, Short signals require trend_score ≤ 2
Stage 5: Cooldown Enforcement
Minimum bars between signals (default 10, configurable 5-15)
Prevents over-trading during choppy conditions
Stage 6: Performance Tracking
After 8 bars (performance horizon), signal outcome evaluated
Win = price moved in signal direction, Loss = price moved against
Results fed back into memory and bandit statistics
Trading Modes (Presets)
Pre-configured parameter sets:
Conservative: 85% consensus, 4 confirmations, 15-bar cooldown
Expected: 60-70% win rate, 3-8 signals/week
Best for: Swing trading, capital preservation, beginners
Balanced: 70% consensus, 3 confirmations, 10-bar cooldown
Expected: 55-65% win rate, 8-15 signals/week
Best for: Day trading, most traders, general use
Aggressive: 60% consensus, 2 confirmations, 5-bar cooldown
Expected: 50-58% win rate, 15-30 signals/week
Best for: Scalping, high-frequency trading, active management
Elite: 75% consensus, 3 confirmations, 12-bar cooldown
Expected: 58-68% win rate, 5-12 signals/week
Best for: Selective trading, high-conviction setups
Adaptive: 65% consensus, 2 confirmations, 8-bar cooldown
Expected: Varies based on learning
Best for: Experienced users leveraging bandit system
How to Use
1. Initial Setup (5 Minutes):
Select Trading Mode matching your style (start with Balanced)
Enable Adaptive Learning (recommended for automatic agent selection)
Choose Thompson Sampling algorithm (best all-around performance)
Keep Microstructure Metrics enabled for liquid instruments (>100k daily volume)
2. Agent Tuning (Optional):
Adjust Agent Sensitivity multipliers (0.5-2.0):
<0.8 = Highly selective (fewer signals, higher quality)
0.9-1.2 = Balanced (recommended starting point)
1.3 = Aggressive (more signals, lower individual quality)
Monitor dashboard for 20-30 signals to identify dominant agent
If one agent consistently outperforms, consider using Lock Agent feature
3. Bandit Configuration (Advanced):
Blend Temperature (0.1-2.0):
0.3 = Sharp decisions (best agent dominates)
0.5 = Balanced (default)
1.0+ = Smooth (equal weighting, democratic)
Memory Decay (0.8-0.99):
0.90 = Fast adaptation (volatile markets)
0.95 = Balanced (most instruments)
0.97+ = Long memory (stable trends)
4. Signal Interpretation:
Green triangle (▲): Long signal confirmed
Red triangle (▼): Short signal confirmed
Dashboard shows:
Active agent (highlighted row with ► marker)
Win rate per agent (green >60%, yellow 40-60%, red <40%)
Confidence bars (█████ = maximum confidence)
Memory size (short-term buffer count)
Colored zones display:
Entry level (current close)
Stop-loss (1.5× ATR)
Take-profit 1 (2.0× ATR)
Take-profit 2 (3.5× ATR)
5. Risk Management:
Never risk >1-2% per signal (use ATR-based stops)
Signals are entry triggers, not complete strategies
Combine with your own market context analysis
Consider fundamental catalysts and news events
Use "Confirming" status to prepare entries (not to enter early)
6. Memory Persistence (Optional):
After 50-100 trades, check Memory Export Panel
Record displayed alpha/beta/weight values for each agent
Record VPIN and Kyle threshold values
Enable "Restore From Memory" and input saved values to continue learning
Useful when switching timeframes or restarting indicator
Visual Components
On-Chart Elements:
Spectral Layers: EMA8 ± 0.5 ATR bands (dynamic support/resistance, colored by trend)
Energy Radiance: Multi-layer glow boxes at signal points (intensity scales with confidence, configurable 1-5 layers)
Probability Cones: Projected price paths with uncertainty wedges (15-bar projection, width = confidence × ATR)
Connection Lines: Links sequential signals (solid = same direction continuation, dotted = reversal)
Kill Zones: Risk/reward boxes showing entry, stop-loss, and dual take-profit targets
Signal Markers: Triangle up/down at validated entry points
Dashboard (Configurable Position & Size):
Regime Indicator: 4-level trend classification (Strong Bull/Bear, Weak Bull/Bear)
Mode Status: Shows active system (Adaptive Blend, Locked Agent, or Consensus)
Agent Performance Table: Real-time win%, confidence, and memory stats
Order Flow Metrics: Toxicity and impact indicators (when microstructure enabled)
Signal Status: Current state (Long/Short/Confirming/Waiting) with confirmation progress
Memory Panel (Configurable Position & Size):
Live Parameter Export: Alpha, beta, and weight values per agent
Adaptive Thresholds: Current VPIN sensitivity and Kyle threshold
Save Reminder: Visual indicator if parameters should be recorded
What Makes This Original
This script's originality lies in three key innovations:
1. Genuine Meta-Learning Framework:
Unlike traditional indicator mashups that simply display multiple signals, this implements authentic reinforcement learning (multi-armed bandits) to learn which detection method works best in current conditions. The Thompson Sampling implementation with beta distribution tracking (alpha for successes, beta for failures) is statistically rigorous and adapts continuously. This is not post-hoc optimization—it's real-time learning.
2. Episodic Memory Architecture with Transfer Learning:
The dual-layer memory system mimics human learning patterns:
Short-term memory captures recent performance (recency bias)
Long-term memory preserves historical patterns (experience)
Automatic transfer mechanism consolidates knowledge
Memory boost creates positive feedback loops (successful strategies become stronger)
This architecture allows the system to adapt without retraining , unlike static ML models that require batch updates.
3. Institutional Microstructure Integration:
Combines retail-focused technical analysis (RSI, Bollinger Bands, VWAP) with institutional-grade microstructure metrics (VPIN, Kyle's Lambda, Hawkes processes) typically found in academic finance literature and professional trading systems, not standard retail platforms. While simplified for Pine Script constraints, these metrics provide insight into informed vs. uninformed trading , a dimension entirely absent from traditional technical analysis.
Mashup Justification:
The four agents are combined specifically for risk diversification across failure modes:
Spoofing Detector: Prevents false breakout losses from manipulation
Exhaustion Detector: Prevents chasing extended trends into reversals
Liquidity Void: Exploits volatility compression (different regime than trending)
Mean Reversion: Provides mathematical anchoring when patterns fail
The bandit system ensures the optimal tool is automatically selected for each market situation, rather than requiring manual interpretation of conflicting signals.
Why "ML-lite"? Simplifications and Approximations
This is the "lite" version due to necessary simplifications for Pine Script execution:
1. Simplified VPIN Calculation:
Academic Implementation: True VPIN uses volume bucketing (fixed-volume bars) and tick-by-tick buy/sell classification via Lee-Ready algorithm or exchange-provided trade direction flags
This Implementation: 20-bar rolling window with simple open/close heuristic (close > open = buy volume)
Impact: May misclassify volume during ranging/choppy markets; works best in directional moves
2. Pseudo-Random Sampling:
Academic Implementation: Thompson Sampling requires true random number generation from beta distributions using inverse transform sampling or acceptance-rejection methods
This Implementation: Deterministic pseudo-randomness derived from price and volume decimal digits: (close × 100 - floor(close × 100)) + (volume % 100) / 100
Impact: Not cryptographically random; may have subtle biases in specific price ranges; provides sufficient variation for agent selection
3. Hawkes Process Approximation:
Academic Implementation: Full Hawkes process uses maximum likelihood estimation with exponential kernels: λ(t) = μ + Σ α·exp(-β(t-tᵢ)) fitted via iterative optimization
This Implementation: Simple exponential decay (0.9 multiplier) with binary event triggers (volume spike = event)
Impact: Captures self-exciting property but lacks parameter optimization; fixed decay rate may not suit all instruments
4. Kyle's Lambda Simplification:
Academic Implementation: Estimated via regression of price impact on signed order flow over multiple time intervals: Δp = λ × Δv + ε
This Implementation: Simplified ratio: price_change / sqrt(volume_sum) without proper signed order flow or regression
Impact: Provides directional indicator of impact but not true market depth measurement; no statistical confidence intervals
5. Entropy Calculation:
Academic Implementation: True Shannon entropy requires probability distribution: H(X) = -Σ p(x)·log₂(p(x)) where p(x) is probability of each price change magnitude
This Implementation: Simple ratio of unique price changes to total observations (variety measure)
Impact: Measures diversity but not true information entropy with probability weighting; less sensitive to distribution shape
6. Memory System Constraints:
Full ML Implementation: Neural networks with backpropagation, experience replay buffers (storing state-action-reward tuples), gradient descent optimization, and eligibility traces
This Implementation: Fixed-size array queues with simple averaging; no gradient-based learning, no state representation beyond raw scores
Impact: Cannot learn complex non-linear patterns; limited to linear performance tracking
7. Limited Feature Engineering:
Advanced Implementation: Dozens of engineered features, polynomial interactions (x², x³), dimensionality reduction (PCA, autoencoders), feature selection algorithms
This Implementation: Raw agent scores and basic market metrics (RSI, ATR, volume ratio); minimal transformation
Impact: May miss subtle cross-feature interactions; relies on agent-level intelligence rather than feature combinations
8. Single-Instrument Data:
Full Implementation: Multi-asset correlation analysis (sector ETFs, currency pairs, volatility indices like VIX), lead-lag relationships, risk-on/risk-off regimes
This Implementation: Only OHLCV data from displayed instrument
Impact: Cannot incorporate broader market context; vulnerable to correlated moves across assets
9. Fixed Performance Horizon:
Full Implementation: Adaptive horizon based on trade duration, volatility regime, or profit target achievement
This Implementation: Fixed 8-bar evaluation window
Impact: May evaluate too early in slow markets or too late in fast markets; one-size-fits-all approach
Performance Impact Summary:
These simplifications make the script:
✅ Faster: Executes in milliseconds vs. seconds (or minutes) for full academic implementations
✅ More Accessible: Runs on any TradingView plan without external data feeds, APIs, or compute servers
✅ More Transparent: All calculations visible in Pine Script (no black-box compiled models)
✅ Lower Resource Usage: <500 bars lookback, minimal memory footprint
⚠️ Less Precise: Approximations may reduce statistical edge by 5-15% vs. academic implementations
⚠️ Limited Scope: Cannot capture tick-level dynamics, multi-order-book interactions, or cross-asset flows
⚠️ Fixed Parameters: Some thresholds hardcoded rather than dynamically optimized
When to Upgrade to Full Implementation:
Consider professional Python/C++ versions with institutional data feeds if:
Trading with >$100K capital where precision differences materially impact returns
Operating in microsecond-competitive environments (HFT, market making)
Requiring regulatory-grade audit trails and reproducibility
Backtesting with tick-level precision for strategy validation
Need true real-time adaptation with neural network-based learning
For retail swing/day trading and position management, these approximations provide sufficient signal quality while maintaining usability, transparency, and accessibility. The core logic—multi-agent detection with adaptive selection—remains intact.
Technical Notes
All calculations use standard Pine Script built-in functions ( ta.ema, ta.atr, ta.rsi, ta.bb, ta.sma, ta.stdev, ta.vwap )
VPIN and Kyle's Lambda use simplified formulas optimized for OHLCV data (see "Lite" section above)
Thompson Sampling uses pseudo-random noise from price/volume decimal digits for beta distribution sampling
No repainting: All calculations use confirmed bar data (no forward-looking)
Maximum lookback: 500 bars (set via max_bars_back parameter)
Performance evaluation: 8-bar forward-looking window for reward calculation (clearly disclosed)
Confidence threshold: Minimum 0.25 (25%) enforced on all signals
Memory arrays: Dynamic sizing with FIFO queue management
Limitations and Disclaimers
Not Predictive: This indicator identifies patterns in historical data. It cannot predict future price movements with certainty.
Requires Human Judgment: Signals are entry triggers, not complete trading strategies. Must be confirmed with your own analysis, risk management rules, and market context.
Learning Period Required: The adaptive system requires 50-100 bars minimum to build statistically meaningful performance data for bandit algorithms.
Overfitting Risk: Restoring memory parameters from one market regime to a drastically different regime (e.g., low volatility to high volatility) may cause poor initial performance until system re-adapts.
Approximation Limitations: Simplified calculations (see "Lite" section) may underperform academic implementations by 5-15% in highly efficient markets.
No Guarantee of Profit: Past performance, whether backtested or live-traded, does not guarantee future performance. All trading involves risk of loss.
Forward-Looking Bias: Performance evaluation uses 8-bar forward window—this creates slight look-ahead for learning (though not for signals). Real-time performance may differ from indicator's internal statistics.
Single-Instrument Limitation: Does not account for correlations with related assets or broader market regime changes.
Recommended Settings
Timeframe: 15-minute to 4-hour charts (sufficient volatility for ATR-based stops; adequate bar volume for learning)
Assets: Liquid instruments with >100k daily volume (forex majors, large-cap stocks, BTC/ETH, major indices)
Not Recommended: Illiquid small-caps, penny stocks, low-volume altcoins (microstructure metrics unreliable)
Complementary Tools: Volume profile, order book depth, market breadth indicators, fundamental catalysts
Position Sizing: Risk no more than 1-2% of capital per signal using ATR-based stop-loss
Signal Filtering: Consider external confluence (support/resistance, trendlines, round numbers, session opens)
Start With: Balanced mode, Thompson Sampling, Blend mode, default agent sensitivities (1.0)
After 30+ Signals: Review agent win rates, consider increasing sensitivity of top performers or locking to dominant agent
Alert Configuration
The script includes built-in alert conditions:
Long Signal: Fires when validated long entry confirmed
Short Signal: Fires when validated short entry confirmed
Alerts fire once per bar (after confirmation requirements met)
Set alert to "Once Per Bar Close" for reliability
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
VWAP + Volume Spikes See Where Smart Money ExhaustsVolume tells the truth. VWAP tells the bias. This script shows both — live.
If you trade intraday momentum, reversals, or liquidity sweeps, this indicator is built for you.
It shows where volume spikes hit extreme levels, anchored around VWAP and its dynamic bands, so you can instantly spot capitulation or hidden absorption.
🎯 What This Indicator Does
✅ Plots VWAP — session-anchored, updates automatically
✅ Adds dynamic VWAP bands — standard deviation envelopes showing volatility context
✅ Highlights volume spikes — colored candles + background for abnormal prints
✅ Includes alerts — “Volume Spike”, “VWAP Cross”, or a combined alert with direction
✅ Clean visual design — instantly readable in fast markets
It’s your visual orderflow radar — whether you’re trading gold, indices, or small caps.
🔍 Why It Works
Institutions build and unwind positions around VWAP.
Retail often chases volume… this script shows you when that volume becomes too extreme.
A spike above VWAP near resistance? → Likely distribution.
A spike below VWAP near support? → Likely capitulation.
Combine volume exhaustion + VWAP context, and you’ll see market turning points form before most indicators react.
⚙️ Inputs You Can Tune
Bands lookback: adjusts how reactive the VWAP bands are
Band width (σ): set how tight or wide your deviation envelope is
Volume baseline length: controls how “abnormal” a spike must be
Spike threshold: multiplier vs. average volume
Toggle color-coding, bands, and labels
Default settings work well across 1m–15m intraday charts and 1h–4h swing frames.
💡 How Traders Use It
1️⃣ Fade Parabolics:
When a green spike candle pierces upper VWAP band on high volume → smart money unloading.
Look for rejection and short into VWAP.
2️⃣ Catch Capitulations:
When a red spike candle dumps below lower VWAP band → panic selling.
Watch for stabilization and long back to VWAP.
3️⃣ VWAP Rotation Plays:
Alerts for price crossing VWAP help you spot shift in intraday control.
Above VWAP = buyers in charge.
Below VWAP = sellers in charge.
🧠 Best Practices
Pair it with Volume Profile or Delta/Flow tools to confirm exhaustion.
Don’t chase — wait for spike confirmation + reversal candle.
Use it on liquid tickers (NASDAQ, SPY, GOLD, BTC, etc.).
Great for Dux-style small-cap shorts or index pullbacks.
🔔 Alerts Ready
Choose from:
Volume Spike (single-bar explosion)
VWAP Cross Up/Down (trend shift confirmation)
One Combined Alert (any signal, includes ticker, price, and volume)
Set once — get real-time push notifications, Telegram, or webhook signals.
📊 My Favorite Setups
US100 / NASDAQ: fade rallies above VWAP + spike
Gold / Silver: trade reversals from VWAP bands
Small caps: short back-side after volume climax
ES, DAX, Oil: scalp VWAP rotation with confluence
❤️ Support This Work
I release free and premium scripts weekly — combining smart money concepts, VWAP tools, and volume analytics.
👉 Follow me on TradingView for more indicators and setups.
👉 Comment “🔥” if you want me to post the multi-timeframe VWAP + Volume Pressure version next.
👉 Share this with your team — it helps the community grow.
grinpapedro
pedro02599
En línea
Canal de texto
No Somos Liquidez:【📖】biblioteca
Buscar No Somos Liquidez
Hilos
Hermit.exe
Hermit.exe
hace >30 días
Notion Trade Tracker
Herramientas
0
Hermit.exe
Hermit.exe
hace >30 días
Notion Journal
Herramientas
0
9
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador Judas Swing
SMC
Herramientas
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Indicador TV Samurái V1
SMC
Herramientas
0
2
Hermit.exe
Hermit.exe
22 de septiembre de 2024
Hábitos Atómicos
Psicologia
0
Hermit.exe
Hermit.exe
22 de septiembre de 2024
El trading como negocio
Psicologia
0
Hilo
Hilo:Indicador TV Samurái V1
Chat de Indicador TV Samurái V1
Indicador TV Samurái V1
SMC
22 de septiembre de 2024
Hermit.exe
NSL
Senior Mod
AO
Autor(a) original — 22/09/2024 16:06domingo, 22 de septiembre de 2024 16:06
@VIP
Primero agradecer al compañero @Romulo por su generosidad y compartir el indicador para la comunidad, todos los créditos de creación para el
El indicador tal como su nombre indica sirve para marcar el horario de operativa y elementos de la estrategia Samurái V1. Este indicador no esta publico en TV por lo que tendrán que añadirlo de manera manual a través de un script a TradingView, cabe recalcar que no es nada complicado, para hacerlo aquí les dejamos un pequeño tutorial:
www.youtube.com
Indicaciones para agregarlo de manera manual:
Entramos a TV y buscamos "editor de Pine" en la parte inferior izquierda de la pantalla.,
Le damos click y aparecerá un nuevo menú,
Posteriormente eliminamos todo lo que este dentro del menú,
Ahora copiamos todo el texto del archivo del indicador y lo pegamos en el menú de TV,
Finalmente le damos a "añadir al grafico" que se encuentra en la parte derecha de la misma barra donde estaba "editor de pine".,
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST) - DST Start : Second Sunday in March at 2:00 - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
... (413 líneas restantes)
Contraer
Contraer (513 líneas)
Ver todo el archivo
SAMURAI v1.txt
SAMURAI v1.txt (23 KB)
23 KB
SAMURAI v1.txt (23 KB)
Descargar SAMURAI v1.txt (23 KB)Cambiar de idioma
Reenviar
Más
2
Seguir
Añade esta publicación a tu lista de canales y recibe notificaciones sobre ella.
Copiar enlace
No tienes permiso para enviar mensajes en este canal.
// This work is by modifiec for me.
// © ARAYA
//@version=5
indicator('SAMURAI v1 ', overlay = true, max_lines_count = 500, max_labels_count = 100)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
group_ln = 'London Time Settings'
lnSummerTime = 0
group_m07 = 'SAMURAI INVIERNO/ New York 07:00 AM 07:10 '
m07000710 = input.bool(false, '07:00 AM 07:10', group = group_m07)
m07_top = input.bool(true, 'Top Line', inline = 'mc07', group = group_m07)
m07_mid = input.bool(true, 'Mid Line', inline = 'mc07', group = group_m07)
m07_bot = input.bool(true, 'Bottom Line', inline = 'mc07', group = group_m07)
m07_ext = input.bool(true, 'Extending Lines', inline = 'mc07', group = group_m07)
group_ny = 'New York Time Settings'
nySummerTime = input.bool(true , 'New York Daylight Saving Time (DST)', group = group_ny, tooltip = 'New York : Daylight Saving Time (DST) - DST Start : Second Sunday in March at 2:00 - DST End : First Sunday in November at 2:00')
group_m08 = ' SAMURAI 08:00 PM 08:10 '
m08000810 = input.bool(true , '08:00 PM 08:10', group = group_m08)
m08_top = input.bool(true, 'Top Line', inline = 'mc08', group = group_m08)
m08_mid = input.bool(true, 'Mid Line', inline = 'mc08', group = group_m08)
m08_bot = input.bool(true, 'Bottom Line', inline = 'mc08', group = group_m08)
m08_ext = input.bool(true, 'Extending Lines', inline = 'mc08', group = group_m08)
group_c = 'ESTRUCTURA'
pLen = 0
pLoc = label.style_none
aColor = input.color(color.gray, ' Color del Rango', group = group_c)
mColor = aColor
eColor = aColor
mcText = input.string('Small', "Tamaño del Texto", options= )
mcSize = switch mcText
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
=> size.tiny
mcAlert = 0
mcAlertM = 0
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
type macro
int t // unix time
int x2 // end bar_index
int len // macro length
float o // macro open price value
float top // macro top price value
float bottom // macro bottom price value
float mid // macro mid price value
float co // macro close open price value
float ch // macro close high price value
float cl // macro close low price value
float cc // macro close close price value
line lnh // macro top line
line lnhe // macro top line - extended
line lnl // macro bottom line
line lnle // macro bottom line - extended
line lnm // macro mid line
line lnme // macro mid line - extended
line lnf // next macro start
linefill lf // macro box (linefill)
label lb // macro label
string xloc = xloc.bar_index
color color = chart.fg_color
color nocolor = chart.bg_color
type pivotPoint
int ht // pivot high unix time
int lt // pivot low unix time
float h // last pivot high price value
float h1 // previous pivot high price value
float l // last pivot low price value
float l1 // previous pivot low price value
//-----------------------------------------------------------------------------}
//Methods / Functions
//-----------------------------------------------------------------------------{
// @function updates horizontal line's y1 and y2 value
// @param _ln (line) line to be updated
// @param _y (float) The new value
// @returns none
method set_y(line _ln, float _y) => _ln.set_y1(_y), _ln.set_y2(_y)
// @function get the current bar's unix time, hour and minute
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _utcTimeOffset (array) array storing the utc info
// @param _utcCity (array) array storing the major city info
// @param _inAd (int) ofsset value in minutes
// @param _tf_m (int) timeframe multiplier
// @returns A tuple containing (int) index, (int) hour and (int) minute
method f_getBarTime(string _utc, _dst, _utcTimeOffset, _utcCity, _inAd, _tf_m) =>
utcTime = (array.get(_utcTimeOffset, array.indexof(_utcCity, _utc)) + (_dst ? 1 : 0)) * 3600000 + _inAd * 60000 + time
h = math.floor(utcTime / 3600000) % 24
m = math.floor(utcTime / 60000) % 60
int idx = 0
if _tf_m == 3
if m == 48
m := m + 2
idx := 2
else if m == 9
m := m + 1
idx := 1
//else if m == 12 or m == 42
// idx := 0
else if _tf_m == 5
if (m == 0 and h == 9) or (m == 30 and h == 7)
m := m + 3
idx := 3
// @function calculate and get customized pivot points high low and time values
// @param _len (int) length for the pivot points high low calculation
// @param _loc (string) if set to 'wick' highest/lowest values of the detected pivot points high low will be calculated
// if set to 'Body' the highest/lowest values of the candel bodies will be returend as pivot points high low
// @returns A tuple containing (float) ph - pivot high, (float) pl - pivot low, (int) pht - pivot high unix time (int) plt - pivot low unix time
method f_getPivotPoint(int _len, _loc) =>
ph = ta.pivothigh(_len, _len)
if ph and _loc == 'Body'
ph := math.max(open , close )
pl = ta.pivotlow (_len, _len)
if pl and _loc == 'Body'
pl := math.min(open , close )
pht = ph ? time : na
plt = pl ? time : na
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
tf_m = timeframe.multiplier
bi = bar_index
var a_majorCity = array.new_string(), var a_utcTimeOffset = array.new_float(), var a_utcCity = array.new_string()
if barstate.isfirst
array.push(a_majorCity, 'NEW YORK'), array.push(a_utcTimeOffset, -5), array.push(a_utcCity, '(UTC-05:00) NEW YORK')
array.push(a_majorCity, 'LONDON' ), array.push(a_utcTimeOffset, 0 ), array.push(a_utcCity, '(UTC+00:00) LONDON' )
// Lower TF bar UDT array
ltfB = request.security_lower_tf(syminfo.tickerid, '1', bar.new())
// Lower TF pivotPoint UDT arrays
var pivotPoint p = pivotPoint.new()
= request.security_lower_tf(syminfo.tickerid, '1', f_getPivotPoint(pLen, pLoc))
if not na(array.min(a_pL))
p.l := array.min(a_pL)
p.lt := array.min(a_pLt)
if not na(array.max(a_pH))
p.h := array.max(a_pH)
p.ht := array.max(a_pHt)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//units and multipliers for versatility across asset classes
pUnits = syminfo.type== 'index' or syminfo.type == 'futures'? ' $':
syminfo.type=='forex'?' pips':na
mult= str.tonumber(timeframe.period)<=5? 1: str.tonumber(timeframe.period)<=240? 60: timeframe.isdwm? 1440:na
pMult = syminfo.type== 'index' or syminfo.type == 'futures'? 1:
syminfo.type=='forex'? 100:1
tUnits = mult==1? ' mins': mult==60? ' hours':mult==1440? ' days':na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------}
//Detect ICT macros
//-----------------------------------------------------------------------------{
var macro mc = macro.new()
// @function main function : detects macros, draws nad controls macro components and classifies macros
// @param _m (bool) enable/disable specific macro
// @param _msh (int) macro start hour
// @param _msm (int) macro start minute
// @param _mh (bool) macro top line control option
// @param _ml (bool) macro bottom line control option
// @param _mm (bool) macro middle line control option
// @param _me (bool) macro extended lines control option
// @param _mt (bool) macro label text value
//
// @param _utc (string) utc and major city in the form of '(UTC-05:00) NEW YORK'
// @param _dst (bool) daylight saving time
// @param _tf_m (int) timeframe multiplier
// @param _alert (bool) next macro time start location, displays in _alertM minutes
// @param _alertM (int) alert in _alertM minutes
// @returns macro UDT components created
processMacro(_m, _msh, _msm, _mh, _ml, _mm, _me, _mt, _utc, _dst, _tf_m, _alert, _alertM) =>
if _m
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, _alertM, _tf_m)
if ha == _msh and ma == _msm
alert(_mt + ' macro will be in play in ' + str.tostring(_alertM) + ' minutes for instrument ' + syminfo.ticker)
if _alert
mc.lnf := line.new(time + _alertM * 60000 , high, time + _alertM * 60000, low, xloc.bar_time, extend.both, mc.color, line.style_solid , 1)
= f_getBarTime(_utc, _dst, a_utcTimeOffset, a_utcCity, 0, _tf_m)
if h == 08 or h == 07 or h == 1 or h == 3 or h == 5
if m == 0
mc.len := 10
else
mc.len := 180
if h == 11
if m == 0
mc.len := 10
else
mc.len := 300
if h == _msh and m == _msm
mc.lnf.delete()
if ltfB.size() > idx
if not na(ltfB.get(idx).h)
mc.t := ltfB.get(idx).t
mc.o := ltfB.get(idx).o
mc.top := ltfB.get(idx).h
mc.bottom := ltfB.get(idx).l
if idx == 0
mc.x2 := bi + math.round(mc.len / _tf_m)
else
mc.x2 := bi + math.round(mc.len / _tf_m) + 1
mc.lnh := line.new(bi, mc.top, int(mc.x2), mc.top, color = _mh ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnhe := line.new(int(mc.x2), mc.top, int(mc.x2), mc.top, color = _me ? _mh ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnl := line.new(bi, mc.bottom, int(mc.x2), mc.bottom, color =_ml ? mc.color : mc.nocolor, style = line.style_solid , width = 2)
mc.lnle := line.new(int(mc.x2), mc.bottom, int(mc.x2), mc.bottom, color = _me ? _ml ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 2)
mc.lnm := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _mm ? mc.color : mc.nocolor, style = line.style_dotted, width = 1)
mc.lnme := line.new(bi, math.avg(mc.top, mc.bottom), int(mc.x2), math.avg(mc.top, mc.bottom), color = _me ? _mm ? mc.color : mc.nocolor : mc.nocolor, style = line.style_dotted, width = 1)
mc.lf := linefill.new(mc.lnh, mc.lnl, color.new(color.gray, 100))
mc.lb := label.new(bi + int(mc.len / _tf_m / 2), mc.top, mcText != 'None' ? 'SAMURAI ' + _mt : '', xloc.bar_index, yloc.price, #00000000, label.style_label_down, chart.fg_color, mcSize, text.align_left, '')
p.l1 := p.l
p.h1 := p.h
else if bi < int(mc.x2) and time >= mc.t
mc.top := math.max(high, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(low , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(high, mc.lnh.get_y1()), math.min(low , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(high, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if bi == int(mc.x2)
if ltfB.size() > idx
if not na(ltfB.get(idx).c)
mc.co := ltfB.get(idx).o
mc.ch := ltfB.get(idx).h
mc.cl := ltfB.get(idx).l
mc.cc := ltfB.get(idx).c
mc.top := math.max(mc.ch, mc.lnh.get_y1())
mc.lnh.set_y(mc.top), mc.lnhe.set_y(mc.top)
mc.bottom := math.min(mc.cl , mc.lnl.get_y1())
mc.lnl.set_y(mc.bottom), mc.lnle.set_y(mc.bottom)
mc.mid := math.avg(math.max(mc.top, mc.lnh.get_y1()), math.min(mc.bottom , mc.lnl.get_y1()))
mc.lnm.set_y(mc.mid), mc.lnme.set_y(mc.mid)
mc.lb.set_y(math.max(mc.top, mc.lb.get_y()))
if not na(array.min(a_pL)) and p.lt < mc.t
p.l1 := array.min(a_pL)
if not na(array.max(a_pH)) and p.ht < mc.t
p.h1 := array.max(a_pH)
else if mc.t == mc.t
mc.lnhe.set_x2(bi), mc.lnle.set_x2(bi), mc.lnme.set_x2(bi)
if bi == int(mc.x2) + 1 and not str.contains(mc.lb.get_text(), 'on NSL')
mc.lb.set_tooltip('mc open : '+ str.tostring(mc.o , format.mintick) +
' mc close : ' + str.tostring(mc.cc , format.mintick) +
' mc top : ' + str.tostring(mc.top , format.mintick) +
' mc mid : ' + str.tostring(mc.mid , format.mintick) +
' mc bottom : ' + str.tostring(mc.bottom, format.mintick) )
if mc.bottom < p.l1 and mc.top > p.h1
if (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(mColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else if mc.bottom < p.l1 or mc.top > p.h1
if (mc.co > mc.mid and mc.cc < mc.mid) or (mc.co < mc.mid and mc.cc > mc.mid) or (mc.o < mc.mid and mc.cc < mc.mid) or (mc.o > mc.mid and mc.cc > mc.mid) // pL > pmcPL or pmcPH < pH
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
if p.l == p.l1 and p.h == p.h1 and (mc.o < math.avg(mc.bottom, mc.mid) and mc.cc > math.avg(mc.top, mc.mid)) or (mc.o > math.avg(mc.top, mc.mid) and mc.cc < math.avg(mc.bottom, mc.mid))
mc.lf.set_color(color.new(eColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
else
mc.lf.set_color(color.new(aColor, 73))
if mcText != 'None'
mc.lb.set_text(' ' + mc.lb.get_text())
//-----------------------------------------------------------------------------}
//Process macros
//-----------------------------------------------------------------------------{
if tf_m <= 15
processMacro(m07000710, 11, 00, m07_top, m07_bot, m07_mid, m07_ext, '07:00 AM - 07:10', '(UTC+00:00) LONDON' , lnSummerTime, tf_m, mcAlert, mcAlertM)
processMacro(m08000810, 08, 00, m08_top, m08_bot, m08_mid, m08_ext, '08:00 AM - 08:10', '(UTC-05:00) NEW YORK', nySummerTime, tf_m, mcAlert, mcAlertM)
else
var table note = table.new(position.bottom_right, 1, 1)
if barstate.islast
table.cell(note, 0, 0, 'ICT Macros are supported on: 1 min, 3, 5 mins and 15 mins charts ', text_size=size.small, text_color=chart.fg_color)
//-----------------------------------------------------------------------------}
//OPEN RANGO DE ESTRATEGIA
// INPUTS
i_time = input.session ('0800-0801:1234567', "OPEN SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz = input ("GMT-4", "Timezone")
i_vline = input.bool (true, "VLine", inline="in1")
i_vcol = input.color (#006eff, "", inline="in1")
i_txtcol = input.color (#006eff, " Text color", inline="in1")
i_vstyle = input.string ("Solid", "Style", options= )
i_hline = label.style_none
i_linecol = label.style_none
i_linestyle = label.style_none
i_ex = label.style_none
i_ex2 = label.style_none
i_ex3 = label.style_none
// MISC
nymidz = time ("1", i_time, i_tz)
linestyle = i_linestyle == "Solid" ? line.style_solid : i_linestyle == "Dotted" ? line.style_dotted : line.style_dashed
vstyle = i_vstyle == "Solid" ? line.style_solid : i_vstyle == "Dotted" ? line.style_dotted : line.style_dashed
ex = i_ex == "1 Day" ? extend.none : i_ex == "2 Days" ? extend.none : i_ex == "Right" ? extend.right : extend.both
htime = i_ex == "2 Days" ? 172800000 : 86400000
hourtime = label.style_none
// CALC
var openprice = 0.0
if nymidz
if not nymidz
openprice := open
else
openprice := math.max(open, openprice)
// OBJECTS
var label lb = na
if openprice != openprice
var line lne = na
line.set_x2(lne, nymidz)
line.set_extend(lne, extend.none)
if i_vline and nymidz == nymidz
vl1 = line.new(nymidz, high, nymidz, low, xloc.bar_time, extend.both, i_vcol, vstyle, 1)
if line.get_y1(vl1) == line.get_y2(vl1)
line.delete(vl1)
///////////////////////////////////////////////////////////////////////////////////
//CLOSE RANGO DE ESTRATEGIA
// INPUTS
i_time0 = input.session ('0810-0811:1234567', "CLOSE SAMURAI", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz0 = i_tz
i_vline0 = i_vline
i_vcol0 = i_vcol
i_txtcol0 = i_txtcol
i_vstyle0 = i_vstyle
i_hline0 = label.style_none
i_linecol0 = label.style_none
i_linestyle0 = label.style_none
i_ex0 = label.style_none
i_ex20 = label.style_none
i_ex30 = label.style_none
// MISC
nymid0 = time ("1", i_time0, i_tz0)
linestyle0 = i_linestyle0 == "Solid" ? line.style_solid : i_linestyle0 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle0 = i_vstyle0 == "Solid" ? line.style_solid : i_vstyle0 == "Dotted" ? line.style_dotted : line.style_dashed
ex0 = i_ex0 == "1 Day" ? extend.none : i_ex0 == "2 Days" ? extend.none : i_ex0 == "Right" ? extend.right : extend.both
htime0 = i_ex0 == "2 Days" ? 172800000 : 86400000
hourtime0 = label.style_none
// CALC
var openprice0 = 0.0
if nymid0
if not nymid0
openprice0 := open
else
openprice0 := math.max(open, openprice0)
// OBJECTS
var label lb0 = na
if openprice0 != openprice0
var line lne0 = na
line.set_x2(lne0, nymid0)
line.set_extend(lne0, extend.none)
if i_vline0 and nymid0 == nymid0
vl10 = line.new(nymid0, high, nymid0, low, xloc.bar_time, extend.both, i_vcol0, vstyle0, 1)
if line.get_y1(vl10) == line.get_y2(vl10)
line.delete(vl10)
///////////////////////////////////////////////////////////////////////////////////////////////
//CLOSE MAX 8:45
// INPUTS
i_time1 = input.session ('0845-0846:1234567', "END", tooltip="Different exchanges will have difference time zones so change accordingly.")
i_tz1 = i_tz
i_vline1 = i_vline
i_vcol1 = i_vcol
i_txtcol1 = i_txtcol
i_vstyle1 = i_vstyle
i_hline1 = label.style_none
i_linecol1 = label.style_none
i_linestyle1 = label.style_none
i_ex1 = label.style_none
i_ex21 = label.style_none
i_ex31 = label.style_none
// MISC
nymid1 = time ("1", i_time1, i_tz1)
linestyle1 = i_linestyle1 == "Solid" ? line.style_solid : i_linestyle1 == "Dotted" ? line.style_dotted : line.style_dashed
vstyle1 = i_vstyle1 == "Solid" ? line.style_solid : i_vstyle1 == "Dotted" ? line.style_dotted : line.style_dashed
ex1 = i_ex1 == "1 Day" ? extend.none : i_ex1 == "2 Days" ? extend.none : i_ex1 == "Right" ? extend.right : extend.both
htime1 = i_ex1 == "2 Days" ? 172800000 : 86400000
hourtime1 = label.style_none
// CALC
var openprice1 = 0.0
if nymid1
if not nymid1
openprice1 := open
else
openprice1 := math.max(open, openprice1)
// OBJECTS
var label lb1 = na
if openprice1 != openprice1
var line lne1 = na
line.set_x2(lne1, nymid1)
line.set_extend(lne1, extend.none)
if i_vline1 and nymid1 == nymid1
vl11 = line.new(nymid1, high, nymid1, low, xloc.bar_time, extend.both, i_vcol1, vstyle1, 1)
if line.get_y1(vl11) == line.get_y2(vl11)
line.delete(vl11)
// EN
TraderDemircan (Triz Global) Automatic Extend FibonacciDescription
What This Indicator Does:
This indicator automatically identifies the most significant swing low and swing high points within a customizable lookback period and plots comprehensive Fibonacci retracement and extension levels between them. Unlike manual Fibonacci tools, this script continuously updates the levels based on the most recent price action, making it ideal for traders who want to identify key support/resistance zones without constantly redrawing Fibonacci levels.
Key Features:
Automatic Swing Point Detection: Scans the specified lookback period to find the lowest low (starting point) and the highest high (ending point) to establish the Fibonacci range
Comprehensive Level Coverage: Plots 18 Fibonacci levels ranging from 0.0 (minimum) to 3.618 (maximum extension), including standard retracement levels (0.236, 0.382, 0.5, 0.618, 0.786) and popular extension levels (1.272, 1.414, 1.618, 2.0, 2.272, 2.382, 2.618, 3.0, 3.272, 3.618)
Visual Clarity: Each level is color-coded and can be individually toggled on/off for cleaner charts
Price and Percentage Labels: Shows both the actual price level and the Fibonacci percentage for easy reference
Flexible Display Options: Customize line width, style (solid/dashed/dotted), and extension direction
Dynamic Updates: Automatically recalculates levels as new price data becomes available
How It Works:
The indicator uses a left-to-right methodology, starting from the swing low (marked as 0.0 with a green diamond) and extending to the swing high (marked as 1.0 with a blue diamond). This approach follows natural price movement and makes the Fibonacci levels intuitive to read. The algorithm:
Identifies the lowest point within the lookback period (this becomes the 0.0 level)
Finds the highest point that occurred after the low point (this becomes the 1.0 level)
Calculates all retracement levels (0.0-1.0) and extension levels (above 1.0) based on this range
Plots horizontal lines with customizable styling and labels
How to Use:
For Retracement Trading: Watch for price reactions at key levels like 0.382, 0.5, and 0.618 (the Golden Ratio) during pullbacks in an uptrend
For Extension Targets: Use levels above 1.0 (especially 1.272, 1.414, and 1.618) to project potential profit targets
Adjust Sensitivity: Increase the "Pivot Sensibility" parameter for major swings only, or decrease it to capture more frequent price movements
Customize Lookback: Shorter periods (50-100 bars) work well for intraday trading, while longer periods (200-500 bars) suit swing trading and position trading
Settings:
Lookback Period: Controls how many candles back to search (10-500)
Pivot Sensibility: Determines the strength required to identify swing points (1-20)
Individual Level Toggles: Enable/disable any of the 18 Fibonacci levels
Visual Customization: Change colors, line thickness (1-5), and line style for each level
Label Options: Toggle price labels and percentage labels independently
Extension Controls: Choose to extend lines left, right, or both directions
What Makes This Original:
This indicator combines automatic swing detection with an extensive range of Fibonacci levels (18 total) that go well beyond the standard retracement tool. The left-to-right calculation methodology ensures logical level placement, while the comprehensive customization options allow traders to adapt the visual presentation to their specific trading style and chart setup.
Note: This indicator is designed for visual analysis and does not generate buy/sell signals. It's a tool to help identify potential support/resistance zones based on Fibonacci ratios. Always combine with other technical analysis methods and proper risk management.
dhruv private 91400//@version=5
//
VERSION = '7.9-X'// 2024.3.20
strategy(
'LE VAN DO® - Swing Signals & Overlays Private™ 7.9-X',
shorttitle = 'LE VAN DO® - Swing Signals & Overlays Private™ 7.9-X' + VERSION,
overlay = true,
explicit_plot_zorder = true,
pyramiding = 0,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 50,
calc_on_every_tick = false,
process_orders_on_close = true,
max_bars_back = 500,
initial_capital = 5000,
commission_type = strategy.commission.percent,
commission_value = 0.02,
max_lines_count = 500
)
//Truncate Function
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
//
// === INPUTS ===
TPSType = input.string('Trailing', 'What TPS should be taken : ', options = )
setupType = input.string('Open/Close', title='What Trading Setup should be taken : ', options= )
scolor = input(true, title='Show coloured Bars to indicate Trend?')
almaRibbon = input(false, title='Enable Ribbon?')
//tradeType = input.string('BOTH', title='What trades should be taken : ', options= )
// === /INPUTS ===
// Display the probabilities in a table
//text01_ = str.tostring(timeframe.multiplier * intRes, '####')
//t = timenow + math.round(ta.change(time) * 25)
//var label lab01 = na
//label.delete(lab01)
//lab01 := label.new(t, close, text=text01_, style=label.style_label_left, yloc=yloc.price, xloc=xloc.bar_time, textalign=text.align_left, textcolor=color.white)
// Constants colours that include fully non-transparent option.
green100 = #008000FF
lime100 = #66bb6a
red100 = #f7525f
blue100 = #0000FFFF
aqua100 = #00FFFFFF
darkred100 = #8B0000FF
gray100 = #808080FF
/////////////////////////////////////////////
// Create non-repainting security function
rp_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src )
//
f_tfInMinutes() =>
_tfInMinutes = timeframe.period == '1' ? '3' : timeframe.period == '3' ? '5' : timeframe.period == '5' ? '15' : timeframe.period == '15' ? '30' : timeframe.period == '30' ? '60' : timeframe.period == '60' ? '240' : 'D'
_tfInMinutes
my_time1 = f_tfInMinutes()
tfmult = 18 //input.int(18, "Input Timeframe Multiplier")
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 10080. :
timeframe.ismonthly ? 43800. : na)
my_time = str.tostring(f_resInMinutes()*tfmult)
useSource = close //input.string('Close', 'What Source to be used?', options = )
enableFilter = input(true, "Enable Backtesting Range Filtering")
fromDate = input.time(timestamp("01 Jan 2023 00:00 +0300"), "Start Date")
toDate = input.time(timestamp("31 Dec 2099 00:00 +0300"), "End Date")
tradeDateIsAllowed = not enableFilter or (time >= fromDate and time <= toDate)
filter1 = 'Filter with Atr'
filter2 = 'Filter with RSI'
filter3 = 'Atr or RSI'
filter4 = 'Atr and RSI'
filter5 = 'No Filtering'
filter6 = 'Entry Only in sideways market(By ATR or RSI)'
filter7 = 'Entry Only in sideways market(By ATR and RSI)'
typefilter = input.string(filter5, title='Sideways Filtering Input', options= , group='Strategy Options')
RSI = truncate(ta.rsi(close, input.int(7, group='RSI Filterring')), 2)
toplimitrsi = input.int(45, title='TOP Limit', group='RSI Filterring')
botlimitrsi = input.int(10, title='BOT Limit', group='RSI Filterring')
//ST = input.bool(true, title='Show Supertrend?', group='Supertrend Indicator')
//period = input.int(1440, group='Supertrend Indicator')
//mult = input.float(2.612, group='Supertrend Indicator')
atrfiltLen = 5 //input.int(5, minval=1, title='atr Length', group='Sideways Filtering Input')
atrMaType = 'EMA' //input.string('EMA', options= , group='Sideways Filtering Input', title='atr Moving Average Type')
atrMaLen = 5 //input.int(5, minval=1, title='atr MA Length', group='Sideways Filtering Input')
//filtering
atra = request.security(syminfo.tickerid, '', ta.atr(atrfiltLen))
atrMa = atrMaType == 'EM' ? ta.ema(atra, atrMaLen) : ta.sma(atra, atrMaLen)
updm = ta.change(high)
downdm = -ta.change(low)
plusdm = na(updm) ? na : updm > downdm and updm > 0 ? updm : 0
minusdm = na(downdm) ? na : downdm > updm and downdm > 0 ? downdm : 0
cndSidwayss1 = atra >= atrMa
cndSidwayss2 = RSI > toplimitrsi or RSI < botlimitrsi
cndSidways = cndSidwayss1 or cndSidwayss2
cndSidways1 = cndSidwayss1 and cndSidwayss2
Sidwayss1 = atra <= atrMa
Sidwayss2 = RSI < toplimitrsi and RSI > botlimitrsi
Sidways = Sidwayss1 or Sidwayss2
Sidways1 = Sidwayss1 and Sidwayss2
trendType = typefilter == filter1 ? cndSidwayss1 : typefilter == filter2 ? cndSidwayss2 : typefilter == filter3 ? cndSidways : typefilter == filter4 ? cndSidways1 : typefilter == filter5 ? RSI > 0 : typefilter == filter6 ? Sidways : typefilter == filter7 ? Sidways1 : na
// === /INPUTS ===
tf = my_time //input('15')
r = ticker.heikinashi(syminfo.tickerid)
openSeriesAlt = request.security(r, tf, open, lookahead=barmerge.lookahead_on)
closeSeriesAlt = request.security(r, tf, close, lookahead=barmerge.lookahead_on)
//openP = plot(almaRibbon ? openSeriesAlt : na, color=color.new(color.lime, 0), linewidth=3)
//closeP = plot(almaRibbon ? closeSeriesAlt : na, color=color.new(color.red, 0), linewidth=3)
BUYOC = ta.crossover(closeSeriesAlt, openSeriesAlt) and setupType == "Open/Close" and trendType
SELLOC = ta.crossunder(closeSeriesAlt, openSeriesAlt) and setupType == "Open/Close" and trendType
//strategy.entry('sell', direction=strategy.short, qty=trade_size, comment='sell', when=sel_entry)
//strategy.entry('buy', direction=strategy.long, qty=trade_size, comment='buy', when=buy_entry)
//trendColour = closeSeriesAlt > openSeriesAlt ? color.green : color.red
//bcolour = closeSeriesAlt > openSeriesAlt ? lime100 : red100
//barcolor(scolor ? bcolour : na, title='Bar Colours')
//closeP = plot(almaRibbon ? closeSeriesAlt : na, title='Close Series', color=color.new(trendColour, 20), linewidth=2, style=plot.style_line)
//openP = plot(almaRibbon ? openSeriesAlt : na, title='Open Series', color=color.new(trendColour, 20), linewidth=2, style=plot.style_line)
//fill(closeP, openP, color=color.new(trendColour, 80))
//
//rt = input(true, title="ATR Based REnko is the Default, UnCheck to use Traditional ATR?")
atrLen = 3 //input.int(3, title="RENKO_ATR", group = "Renko Settings")
isATR = true //input.bool(true, title="RENKO_USE_RENKO_ATR", group = "Renko Settings")
tradLen1 = 1000 //input.int(1000, title="RENKO_TRADITIONAL", group = "Renko Settings")
//Code to be implemented in V2
//mul = input(1, "Number Of minticks")
//value = mul * syminfo.mintick
tradLen = tradLen1 * 1
param = isATR ? ticker.renko(syminfo.tickerid, "ATR", atrLen) : ticker.renko(syminfo.tickerid, "Traditional", tradLen)
renko_close = request.security(param, my_time, close, lookahead=barmerge.lookahead_on)
renko_open = request.security(param, my_time, open, lookahead=barmerge.lookahead_on)
//============================================
//Sniper------------------------------------------------------------------------------------------------------------------------------------- // Signal 2
//============================================
//============================================
//EMA_CROSS-------------------------------------------------------------------------------------------------------------------------------- // Signal 4
//============================================
EMA1_length=input.int(2, "EMA1_length", group = "Renko Settings")
EMA2_length=input.int(10, "EMA2_length", group = "Renko Settings")
a = ta.ema(renko_close, EMA1_length)
b = ta.ema(renko_close, EMA2_length)
//BUY = ta.cross(a, b) and a > b and renko_open < renko_close
//SELL = ta.cross(a, b) and a < b and renko_close < renko_open
///////////////////////////////
// Determine long and short conditions
BUYR = ta.crossover(a, b) and setupType == "Renko" and trendType
SELLR = ta.crossunder(a, b) and setupType == "Renko" and trendType
sel_color = setupType == "Open/Close" ? closeSeriesAlt < openSeriesAlt : setupType == "Renko" ? renko_close < renko_open : na
buy_color = setupType == "Open/Close" ? closeSeriesAlt > openSeriesAlt : setupType == "Renko" ? renko_close > renko_open : na
sel_entry = setupType == "Open/Close" ? SELLOC : setupType == "Renko" ? SELLR : na
buy_entry = setupType == "Open/Close" ? BUYOC : setupType == "Renko" ? BUYR : na
trendColour = buy_color ? color.green : color.red
bcolour = buy_color ? lime100 : red100
barcolor(scolor ? bcolour : na, title='Bar Colours')
p11=plot(almaRibbon and setupType == "Open/Close" ? closeSeriesAlt : almaRibbon and setupType == "Renko" ? renko_close : na, style=plot.style_circles, linewidth=1, color=color.new(trendColour, 80), title="RENKO_1")
p22=plot(almaRibbon and setupType == "Open/Close" ? openSeriesAlt : almaRibbon and setupType == "Renko" ? renko_open : na, style=plot.style_circles, linewidth=1, color=color.new(trendColour, 80), title="RENKO_2")
fill(p11, p22, color=color.new(trendColour, 50), title="RENKO_fill")
//
lxTrigger = false
sxTrigger = false
leTrigger = buy_entry
seTrigger = sel_entry
// === /ALERT conditions.
buy = leTrigger //ta.crossover(closeSeriesAlt, openSeriesAlt)
sell = seTrigger //ta.crossunder(closeSeriesAlt, openSeriesAlt)
varip wasLong = false
varip wasShort = false
if barstate.isconfirmed
wasLong := false
else
if buy
wasLong := true
if barstate.isconfirmed
wasShort := false
else
if sell
wasShort := true
plotshape(wasLong, color = color.yellow)
plotshape(wasShort, color = color.yellow)
//plotshape(almaRibbon ? buy : na, title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= #39ff14, textcolor = #FFFFFF, size = size.tiny)
//plotshape(almaRibbon ? sell : na, title = "Exit", text = 'Exit', style = shape.labeldown, location = location.abovebar, color= #ff1100, textcolor = #FFFFFF, size = size.tiny)
// === STRATEGY ===
i_alert_txt_entry_long = "Short Exit" //input.text_area(defval = "Short Exit", title = "Long Entry Message", group = "Alerts")
i_alert_txt_exit_long = "Long Exit" //input.text_area(defval = "Long Exit", title = "Long Exit Message", group = "Alerts")
i_alert_txt_entry_short = "Go Short" //input.text_area(defval = "Go Short", title = "Short Entry Message", group = "Alerts")
i_alert_txt_exit_short = "Go Long" //input.text_area(defval = "Go Long", title = "Short Exit Message", group = "Alerts")
// Entries and Exits with TP/SL
//tradeType
if buy and TPSType == "Trailing" and tradeDateIsAllowed
strategy.close("Short" , alert_message = i_alert_txt_exit_short)
strategy.entry("Long" , strategy.long , alert_message = i_alert_txt_entry_long)
if sell and TPSType == "Trailing" and tradeDateIsAllowed
strategy.close("Long" , alert_message = i_alert_txt_exit_long)
strategy.entry("Short" , strategy.short, alert_message = i_alert_txt_entry_short)
//tradeType
if buy and TPSType == "Options" and tradeDateIsAllowed
// strategy.close("Short" , alert_message = i_alert_txt_exit_short)
strategy.entry("Long" , strategy.long , alert_message = i_alert_txt_entry_long)
if sell and TPSType == "Options" and tradeDateIsAllowed
strategy.close("Long" , alert_message = i_alert_txt_exit_long)
// strategy.entry("Short" , strategy.short, alert_message = i_alert_txt_entry_short)
G_RISK = '■ ' + 'Risk Management'
//#region ———— <↓↓↓ G_RISK ↓↓↓> {
//ATR SL Settings
atrLength = 20 //input.int(20, minval=1, title='ATR Length')
profitFactor = 2.5 //input(2.5, title='Take Profit Factor')
stopFactor = 1 //input(1.0, title='Stop Loss Factor')
// Calculate ATR
tpatrValue = ta.atr(atrLength)
// Calculate take profit and stop loss levels for buy signals
takeProfit1_buy = 1 * profitFactor * tpatrValue //close + profitFactor * atrValue
takeProfit2_buy = 2 * profitFactor * tpatrValue //close + 2 * profitFactor * atrValue
takeProfit3_buy = 3 * profitFactor * tpatrValue //close + 3 * profitFactor * atrValue
stopLoss_buy = close - takeProfit1_buy //stopFactor * tpatrValue
// Calculate take profit and stop loss levels for sell signals
takeProfit1_sell = 1 * profitFactor * tpatrValue //close - profitFactor * atrValue
takeProfit2_sell = 2 * profitFactor * tpatrValue //close - 2 * profitFactor * atrValue
takeProfit3_sell = 3 * profitFactor * tpatrValue //close - 3 * profitFactor * atrValue
stopLoss_sell = close + takeProfit1_sell //stopFactor * tpatrValue
// ———————————
//Tooltip
T_LVL = '(%) Exit Level'
T_QTY = '(%) Adjust trade exit volume'
T_MSG = 'Paste JSON message for your bot'
//Webhook Message
O_LEMSG = 'Long Entry'
O_LXMSGSL = 'Long SL'
O_LXMSGTP1 = 'Long TP1'
O_LXMSGTP2 = 'Long TP2'
O_LXMSGTP3 = 'Long TP3'
O_LXMSG = 'Long Exit'
O_SEMSG = 'Short Entry'
O_SXMSGSL = 'Short SL'
O_SXMSGA = 'Short TP1'
O_SXMSGB = 'Short TP2'
O_SXMSGC = 'Short TP3'
O_SXMSGX = 'Short Exit'
// on whole pips) for forex currency pairs.
pip_size = syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
// On the last historical bar, show the instrument's pip size
//if barstate.islastconfirmedhistory
// label.new(x=bar_index + 2, y=close, style=label.style_label_left,
// color=color.navy, textcolor=color.white, size=size.large,
// text=syminfo.ticker + "'s pip size is: " +
// str.tostring(pip_size))
// ——————————— | | | Line length guide |
i_lxLvlTP1 = leTrigger ? takeProfit1_buy : seTrigger ? takeProfit1_sell : na //input.float (1, 'Level TP1' , group = G_RISK, tooltip = T_LVL)
i_lxQtyTP1 = input.float (50, 'Qty TP1' , group = G_RISK, tooltip = T_QTY)
i_lxLvlTP2 = leTrigger ? takeProfit2_buy : seTrigger ? takeProfit2_sell : na //input.float (1.5, 'Level TP2' , group = G_RISK, tooltip = T_LVL)
i_lxQtyTP2 = input.float (30, 'Qty TP2' , group = G_RISK, tooltip = T_QTY)
i_lxLvlTP3 = leTrigger ? takeProfit3_buy : seTrigger ? takeProfit3_sell : na //input.float (2, 'Level TP3' , group = G_RISK, tooltip = T_LVL)
i_lxQtyTP3 = input.float (20, 'Qty TP3' , group = G_RISK, tooltip = T_QTY)
i_lxLvlSL = leTrigger ? takeProfit1_buy : seTrigger ? takeProfit1_sell : na //input.float (0.5, 'Stop Loss' , group = G_RISK, tooltip = T_LVL)
i_sxLvlTP1 = i_lxLvlTP1
i_sxQtyTP1 = i_lxQtyTP1
i_sxLvlTP2 = i_lxLvlTP2
i_sxQtyTP2 = i_lxQtyTP2
i_sxLvlTP3 = i_lxLvlTP3
i_sxQtyTP3 = i_lxQtyTP3
i_sxLvlSL = i_lxLvlSL
G_MSG = '■ ' + 'Webhook Message'
i_leMsg = O_LEMSG //input.string (O_LEMSG ,'Long Entry' , group = G_MSG, tooltip = T_MSG)
i_lxMsgSL = O_LXMSGSL //input.string (O_LXMSGSL ,'Long SL' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP1 = O_LXMSGTP1 //input.string (O_LXMSGTP1,'Long TP1' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP2 = O_LXMSGTP2 //input.string (O_LXMSGTP2,'Long TP2' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP3 = O_LXMSGTP3 //input.string (O_LXMSGTP3,'Long TP3' , group = G_MSG, tooltip = T_MSG)
i_lxMsg = O_LXMSG //input.string (O_LXMSG ,'Long Exit' , group = G_MSG, tooltip = T_MSG)
i_seMsg = O_SEMSG //input.string (O_SEMSG ,'Short Entry' , group = G_MSG, tooltip = T_MSG)
i_sxMsgSL = O_SXMSGSL //input.string (O_SXMSGSL ,'Short SL' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP1 = O_SXMSGA //input.string (O_SXMSGA ,'Short TP1' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP2 = O_SXMSGB //input.string (O_SXMSGB ,'Short TP2' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP3 = O_SXMSGC //input.string (O_SXMSGC ,'Short TP3' , group = G_MSG, tooltip = T_MSG)
i_sxMsg = O_SXMSGX //input.string (O_SXMSGX ,'Short Exit' , group = G_MSG, tooltip = T_MSG)
i_src = close
G_DISPLAY = 'Display'
//
i_alertOn = true //input.bool (true, 'Alert Labels On/Off' , group = G_DISPLAY)
i_barColOn = true //input.bool (true, 'Bar Color On/Off' , group = G_DISPLAY)
// ———————————
// @function Calculate the Take Profit line, and the crossover or crossunder
f_tp(_condition, _conditionValue, _leTrigger, _seTrigger, _src, _lxLvlTP, _sxLvlTP)=>
var float _tpLine = 0.0
_topLvl = _src + _lxLvlTP //TPSType == "Fixed %" ? _src + (_src * (_lxLvlTP / 100)) : _src + _lxLvlTP
_botLvl = _src - _lxLvlTP //TPSType == "Fixed %" ? _src - (_src * (_sxLvlTP / 100)) : _src - _sxLvlTP
_tpLine := _condition != _conditionValue and _leTrigger ? _topLvl :
_condition != -_conditionValue and _seTrigger ? _botLvl :
nz(_tpLine )
// @function Similar to "ta.crossover" or "ta.crossunder"
f_cross(_scr1, _scr2, _over)=>
_cross = _over ? _scr1 > _scr2 and _scr1 < _scr2 :
_scr1 < _scr2 and _scr1 > _scr2
// ———————————
//
var float condition = 0.0
var float slLine = 0.0
var float entryLine = 0.0
//
entryLine := leTrigger and condition <= 0.0 ? close :
seTrigger and condition >= 0.0 ? close : nz(entryLine )
//
slTopLvl = TPSType == "Fixed %" ? i_src + (i_src * (i_lxLvlSL / 100)) : i_src + i_lxLvlSL
slBotLvl = TPSType == "Fixed %" ? i_src - (i_src * (i_sxLvlSL / 100)) : i_src - i_lxLvlSL
slLine := condition <= 0.0 and leTrigger ? slBotLvl :
condition >= 0.0 and seTrigger ? slTopLvl : nz(slLine )
slLong = f_cross(low, slLine, false)
slShort = f_cross(high, slLine, true )
//
= f_tp(condition, 1.2,leTrigger, seTrigger, i_src, i_lxLvlTP3, i_sxLvlTP3)
= f_tp(condition, 1.1,leTrigger, seTrigger, i_src, i_lxLvlTP2, i_sxLvlTP2)
= f_tp(condition, 1.0,leTrigger, seTrigger, i_src, i_lxLvlTP1, i_sxLvlTP1)
tp3Long = f_cross(high, tp3Line, true )
tp3Short = f_cross(low, tp3Line, false)
tp2Long = f_cross(high, tp2Line, true )
tp2Short = f_cross(low, tp2Line, false)
tp1Long = f_cross(high, tp1Line, true )
tp1Short = f_cross(low, tp1Line, false)
switch
leTrigger and condition <= 0.0 => condition := 1.0
seTrigger and condition >= 0.0 => condition := -1.0
tp3Long and condition == 1.2 => condition := 1.3
tp3Short and condition == -1.2 => condition := -1.3
tp2Long and condition == 1.1 => condition := 1.2
tp2Short and condition == -1.1 => condition := -1.2
tp1Long and condition == 1.0 => condition := 1.1
tp1Short and condition == -1.0 => condition := -1.1
slLong and condition >= 1.0 => condition := 0.0
slShort and condition <= -1.0 => condition := 0.0
lxTrigger and condition >= 1.0 => condition := 0.0
sxTrigger and condition <= -1.0 => condition := 0.0
longE = leTrigger and condition <= 0.0 and condition == 1.0
shortE = seTrigger and condition >= 0.0 and condition == -1.0
longX = lxTrigger and condition >= 1.0 and condition == 0.0
shortX = sxTrigger and condition <= -1.0 and condition == 0.0
longSL = slLong and condition >= 1.0 and condition == 0.0
shortSL = slShort and condition <= -1.0 and condition == 0.0
longTP3 = tp3Long and condition == 1.2 and condition == 1.3
shortTP3 = tp3Short and condition == -1.2 and condition == -1.3
longTP2 = tp2Long and condition == 1.1 and condition == 1.2
shortTP2 = tp2Short and condition == -1.1 and condition == -1.2
longTP1 = tp1Long and condition == 1.0 and condition == 1.1
shortTP1 = tp1Short and condition == -1.0 and condition == -1.1
// ——————————— {
//
if strategy.position_size <= 0 and longE and TPSType == "ATR" and tradeDateIsAllowed
strategy.entry( 'Long', strategy.long, alert_message = i_leMsg, comment = 'LE')
if strategy.position_size > 0 and condition == 1.0 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'LXTP1', from_entry = 'Long', qty_percent = i_lxQtyTP1, limit = tp1Line, stop = slLine, comment_profit = 'LXTP1', comment_loss = 'SL', alert_profit = i_lxMsgTP1, alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.1 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'LXTP2', from_entry = 'Long', qty_percent = i_lxQtyTP2, limit = tp2Line, stop = slLine, comment_profit = 'LXTP2', comment_loss = 'SL', alert_profit = i_lxMsgTP2, alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.2 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'LXTP3', from_entry = 'Long', qty_percent = i_lxQtyTP3, limit = tp3Line, stop = slLine, comment_profit = 'LXTP3', comment_loss = 'SL', alert_profit = i_lxMsgTP3, alert_loss = i_lxMsgSL)
if longX and tradeDateIsAllowed
strategy.close( 'Long', alert_message = i_lxMsg, comment = 'LX')
//
if strategy.position_size >= 0 and shortE and TPSType == "ATR" and tradeDateIsAllowed
strategy.entry( 'Short', strategy.short, alert_message = i_leMsg, comment = 'SE')
if strategy.position_size < 0 and condition == -1.0 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'SXTP1', from_entry = 'Short', qty_percent = i_sxQtyTP1, limit = tp1Line, stop = slLine, comment_profit = 'SXTP1', comment_loss = 'SL', alert_profit = i_sxMsgTP1, alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.1 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'SXTP2', from_entry = 'Short', qty_percent = i_sxQtyTP2, limit = tp2Line, stop = slLine, comment_profit = 'SXTP2', comment_loss = 'SL', alert_profit = i_sxMsgTP2, alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.2 and TPSType == "ATR" and tradeDateIsAllowed
strategy.exit( id = 'SXTP3', from_entry = 'Short', qty_percent = i_sxQtyTP3, limit = tp3Line, stop = slLine, comment_profit = 'SXTP3', comment_loss = 'SL', alert_profit = i_sxMsgTP3, alert_loss = i_sxMsgSL)
if shortX and tradeDateIsAllowed
strategy.close( 'Short', alert_message = i_sxMsg, comment = 'SX')
// ———————————
c_tp = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.green
c_entry = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.blue
c_sl = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.red
p_tp1Line = plot ( condition == 1.0 or condition == -1.0 ? tp1Line : na, title = "TP Line 1", color = c_tp, linewidth = 1, style = plot.style_linebr)
p_tp2Line = plot ( condition == 1.0 or condition == -1.0 or condition == 1.1 or condition == -1.1 ? tp2Line : na, title = "TP Line 2", color = c_tp, linewidth = 1, style = plot.style_linebr)
p_tp3Line = plot ( condition == 1.0 or condition == -1.0 or condition == 1.1 or condition == -1.1 or condition == 1.2 or condition == -1.2 ? tp3Line : na, title = "TP Line 3", color = c_tp, linewidth = 1, style = plot.style_linebr)
p_entryLine = plot ( condition >= 1.0 or condition <= -1.0 ? entryLine : na, title = "Entry Line", color = c_entry, linewidth = 1, style = plot.style_linebr)
p_slLine = plot ( condition == 1.0 or condition == -1.0 or condition == 1.1 or condition == -1.1 or condition == 1.2 or condition == -1.2 ? slLine : na, title = "SL Line", color = c_sl, linewidth = 1, style = plot.style_linebr)
//fill( p_tp3Line, p_entryLine, color = leTrigger or seTrigger ? na :color.new(color.green, 90))
fill( p_entryLine, p_slLine, color = leTrigger or seTrigger ? na :color.new(color.red, 90))
//
plotshape( i_alertOn and longE, title = 'Long', text = 'Long', textcolor = color.white, color = color.green, style = shape.labelup, size = size.tiny, location = location.belowbar)
plotshape( i_alertOn and shortE, title = 'Short', text = 'Short', textcolor = color.white, color = color.red, style = shape.labeldown, size = size.tiny, location = location.abovebar)
plotshape( i_alertOn and (longX or shortX) ? close : na, title = 'Close', text = 'Close', textcolor = color.white, color = color.gray, style = shape.labelup, size = size.tiny, location = location.absolute)
l_tp = i_alertOn and (longTP1 or shortTP1) ? close : na
plotshape( l_tp, title = "TP1 Cross", text = "TP1", textcolor = color.white, color = #ec407a, style = shape.labelup, size = size.tiny, location = location.absolute)
plotshape( i_alertOn and (longTP2 or shortTP2) ? close : na, title = "TP2 Cross", text = "TP2", textcolor = color.white, color = #ec407a, style = shape.labelup, size = size.tiny, location = location.absolute)
plotshape( i_alertOn and (longTP3 or shortTP3) ? close : na, title = "TP3 Cross", text = "TP3", textcolor = color.white, color = #ec407a, style = shape.labelup, size = size.tiny, location = location.absolute)
plotshape( i_alertOn and (longSL or shortSL) ? close : na, title = "SL Cross", text = "SL", textcolor = color.white, color = color.maroon, style = shape.labelup, size = size.tiny, location = location.absolute)
//
plot( na, title = "─── ───", editable = false, display = display.data_window)
plot( condition, title = "condition", editable = false, display = display.data_window)
plot( strategy.position_size * 100, title = ".position_size", editable = false, display = display.data_window)
//#endregion }
// ——————————— <↑↑↑ G_RISK ↑↑↑>
//#region ———— <↓↓↓ G_SCRIPT02 ↓↓↓> {
// @function Queues a new element in an array and de-queues its first element.
f_qDq(_array, _val) =>
array.push(_array, _val)
_return = array.shift(_array)
_return
var line a_slLine = array.new_line(1)
var line a_entryLine = array.new_line(1)
var line a_tp3Line = array.new_line(1)
var line a_tp2Line = array.new_line(1)
var line a_tp1Line = array.new_line(1)
var label a_slLabel = array.new_label(1)
var label a_tp3label = array.new_label(1)
var label a_tp2label = array.new_label(1)
var label a_tp1label = array.new_label(1)
var label a_entryLabel = array.new_label(1)
newEntry = longE or shortE
entryIndex = 1
entryIndex := newEntry ? bar_index : nz(entryIndex )
lasTrade = bar_index >= entryIndex
l_right = 10
if TPSType == "ATR"
line.delete( f_qDq(a_slLine, line.new( entryIndex, slLine, last_bar_index + l_right, slLine, style = line.style_solid, color = c_sl)))
if TPSType == "ATR"
line.delete( f_qDq(a_entryLine, line.new( entryIndex, entryLine, last_bar_index + l_right, entryLine, style = line.style_solid, color = color.blue)))
if TPSType == "ATR"
line.delete( f_qDq(a_tp3Line, line.new( entryIndex, tp3Line, last_bar_index + l_right, tp3Line, style = line.style_solid, color = c_tp)))
if TPSType == "ATR"
line.delete( f_qDq(a_tp2Line, line.new( entryIndex, tp2Line, last_bar_index + l_right, tp2Line, style = line.style_solid, color = c_tp)))
if TPSType == "ATR"
line.delete( f_qDq(a_tp1Line, line.new( entryIndex, tp1Line, last_bar_index + l_right, tp1Line, style = line.style_solid, color = c_tp)))
if TPSType == "ATR"
label.delete( f_qDq(a_slLabel, label.new( last_bar_index + l_right, slLine, 'SL: ' + str.tostring(slLine, '##.###'), style = label.style_label_left, textcolor = color.white, color = c_sl)))
if TPSType == "ATR"
label.delete( f_qDq(a_entryLabel, label.new( last_bar_index + l_right, entryLine, 'Entry: ' + str.tostring(entryLine, '##.###'), style = label.style_label_left, textcolor = color.white, color = color.blue)))
if TPSType == "ATR"
label.delete( f_qDq(a_tp3label, label.new( last_bar_index + l_right, tp3Line, 'TP3: ' + str.tostring(tp3Line, '##.###') + " - Target Pips : - " + str.tostring(longE ? tp3Line - entryLine : entryLine - tp3Line, "#.##"), style = label.style_label_left, textcolor = color.white, color = c_tp)))
if TPSType == "ATR"
label.delete( f_qDq(a_tp2label, label.new( last_bar_index + l_right, tp2Line, 'TP2: ' + str.tostring(tp2Line, '##.###'), style = label.style_label_left, textcolor = color.white, color = c_tp)))
if TPSType == "ATR"
label.delete( f_qDq(a_tp1label, label.new( last_bar_index + l_right, tp1Line, 'TP1: ' + str.tostring(tp1Line, '##.###'), style = label.style_label_left, textcolor = color.white, color = c_tp)))
//#endregion }
// ——————————— <↑↑↑ G_SCRIPT02 ↑↑↑>
c_barCol = close > open ? color.rgb(120, 9, 139) : color.rgb(69, 155, 225)
barcolor(
i_barColOn ? c_barCol : na)
// ———————————
//
if longE or shortE or longX or shortX
alert(message = 'Any Alert', freq = alert.freq_once_per_bar_close)
if longE
alert(message = 'Long Entry', freq = alert.freq_once_per_bar_close)
if shortE
alert(message = 'Short Entry', freq = alert.freq_once_per_bar_close)
if longX
alert(message = 'Long Exit', freq = alert.freq_once_per_bar_close)
if shortX
alert(message = 'Short Exit', freq = alert.freq_once_per_bar_close)
//#endregion }
// ——————————— <↑↑↑ G_SCRIPT03 ↑↑↑>
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © TraderHalai
// This script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
//
//Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
//
//Full credit to the original author of this script. It can be found here: www.tradingview.com
//
// This script can be copied and airlifted onto existing strategy scripts of your own, and integrates out of the box without implementation of additional functions. I've also added Max Runup, Average Win and Average Loss per trade to the orignal script.
//
//Will look to add in more performance metrics in future, as I further develop this script.
//
//Feel free to use this display panel in your scripts and strategies.
//Thanks and enjoy! :)
//@version=5
//strategy("Strategy BackTest Display Statistics - TraderHalai", overlay=true, default_qty_value= 5, default_qty_type = strategy.percent_of_equity, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1)
//DEMO basic strategy - Use your own strategy here - Jaws Mean Reversion from my profile used here
//source = input(title = "Source", defval = close)
///////////////////////////// --- BEGIN TESTER CODE --- ////////////////////////
// COPY below into your strategy to enable display
////////////////////////////////////////////////////////////////////////////////
// Declare performance tracking variables
drawTester = input.bool(false, "Strategy Performance", group='Dashboards', inline="Show Dashboards")
var balance = strategy.initial_capital
var drawdown = 0.0
var maxDrawdown = 0.0
var maxBalance = 0.0
var totalWins = 0
var totalLoss = 0
// Prepare stats table
var table testTable = table.new(position.top_right, 5, 2, border_width=1)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + " " + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)
// Custom function to truncate (cut) excess decimal places
//truncate(_number, _decimalPlaces) =>
// _factor = math.pow(10, _decimalPlaces)
// int(_number * _factor) / _factor
// Draw stats table
var bgcolor = color.new(color.black,0)
if drawTester and tradeDateIsAllowed
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)
f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(strategy.initial_capital), bgcolor, color.white)
f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(truncate(strategy.initial_capital + strategy.netprofit,2)), bgcolor, color.white)
f_fillCell(testTable, 2, 0, "Avg Win:", "$"+ str.tostring(truncate(strategy.grossprofit / strategy.wintrades, 2)), bgcolor, color.white)
f_fillCell(testTable, 2, 1, "Avg Loss:", "$"+ str.tostring(truncate(strategy.grossloss / strategy.losstrades, 2)), bgcolor, color.white)
f_fillCell(testTable, 3, 0, "Profit Factor:", str.tostring(truncate(strategy.grossprofit / strategy.grossloss,2)), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(testTable, 3, 1, "Max Runup:", str.tostring(truncate(strategy.max_runup, 2 )), bgcolor, color.white)
f_fillCell(testTable, 4, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(truncate((dollarReturn / strategy.initial_capital)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)
f_fillCell(testTable, 4, 1, "Max DD:", str.tostring(truncate((strategy.max_drawdown / strategy.equity) * 100 ,2)) + "%", color.red, color.white)
// --- END TESTER CODE --- ///////////////
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © niceGear68734
//@version=5
//strategy("Table to filter trades per day", overlay=true, use_bar_magnifier = true, initial_capital = 5000, calc_on_every_tick = true, calc_on_order_fills = true, commission_type = strategy.commission.cash_per_contract)
//~ ___________________________________________________________________________
//~ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//~ !!!!!!!!!!!!!!!_________________ START _________________!!!!!!!!!!!!!!!!!
i_showweeklyPerformance = input.bool(false, 'Weekly Performance', group='Dashboards', inline="Show Dashboards")
//__________________________ User Inputs ___________________________________
var const string g_table = "Table Settings"
i_table_pos = "Top Left" //input.string(defval = "Top Left", title = "Position", options = , group = g_table, inline = "1", tooltip = "It sets the location of the table")
i_text_size = "Normal" //input.string(defval = "Normal", title = "Set the size of text", options = , tooltip = "This option is used to change the size of the text in the table")
var const string g_general = "General Settings"
i_check_open_close = "Opened" //input.string("Opened", "Check when the trade :", , group = g_general, tooltip = "This parameter defines what to check for. If opened is selected, the results will show the trades that opened on that day. If closed is selected, the results will show the trades that closed on that day")
i_timezone = "Exchange" //input.string("Exchange", title = "Set the Timezone", options = , group = g_general, tooltip = "You can use this setting whenever you want to change the time that the trade has closed/opened")
//~_____________________________ Switches ___________________________________
table_pos = switch i_table_pos
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
"Top Right" => position.top_right
"Top Left" => position.top_left
timezone_setting = i_timezone == "Exchange" ? syminfo.timezone : i_timezone
text_size = switch i_text_size
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
//__________________________ Array Declaration _____________________________
var string t_column_names = array.from( "", "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat") // Columns header names
var string t_row_names = array.from("", "Total Trades", "Loss", "Win", "Win Rate" ) // Rows header names
var t_column_size = array.size(t_column_names)
var t_row_size = array.size(t_row_names)
var string a_closed_trades = array.new_string() // Save the total number of trades
var string a_loss_trades = array.new_string() // Save the number of losing trades
var string a_win_trades = array.new_string() // Save the number of winning trades
var _a_day_week = array.new_int() // Save the day of the week to split data
// __________________________ Custom Functions ________________________________
//~ create a counter so that it gives a number to strategy.closed_trades.entry_time(counter)
var trade_number = -1
if strategy.closedtrades > strategy.closedtrades
trade_number += 1
f_strategy_closedtrades_hour() =>
switch
i_check_open_close =="Closed" => dayofweek(strategy.closedtrades.exit_time(trade_number), timezone_setting)
i_check_open_close =="Opened" => dayofweek(strategy.closedtrades.entry_time(trade_number), timezone_setting)
f_data(_i) =>
var _closed_trades = 0
var _loss_trades = 0
var _win_trades = 0
var _txt_closed_trades = ""
var _txt_loss_trades = ""
var _txt_win_trades = ""
if strategy.closedtrades > strategy.closedtrades and f_strategy_closedtrades_hour() == _i
_closed_trades += 1
_txt_closed_trades := str.tostring(_closed_trades)
if strategy.losstrades > strategy.losstrades and f_strategy_closedtrades_hour() == _i
_loss_trades += 1
_txt_loss_trades := str.tostring(_loss_trades)
if strategy.wintrades > strategy.wintrades and f_strategy_closedtrades_hour() == _i
_win_trades += 1
_txt_win_trades := str.tostring(_win_trades)
//__________________________
var string array1 = array.new_string(5)
var string array2 = array.new_string(5)
var string array3 = array.new_string(5)
var string array4 = array.new_string(5)
var string array5 = array.new_string(5)
var string array6 = array.new_string(5)
var string array7 = array.new_string(5)
f_pass_data_to_array(_i, _array) =>
= f_data(_i)
array.set(_array,1 , cl)
array.set(_array,2,loss)
array.set(_array,3,win)
if cl != ""
array.set(_array,4,str.tostring(str.tonumber(win) / str.tonumber(cl) * 100 , "##") + " %")
if cl != "" and win == ""
array.set(_array,4,"0 %")
for i = 1 to 7
switch
i == 1 => f_pass_data_to_array(i,array1)
i == 2 => f_pass_data_to_array(i,array2)
i == 3 => f_pass_data_to_array(i,array3)
i == 4 => f_pass_data_to_array(i,array4)
i == 5 => f_pass_data_to_array(i,array5)
i == 6 => f_pass_data_to_array(i,array6)
i == 7 => f_pass_data_to_array(i,array7)
f_retrieve_data_to_table(_i, _j) =>
switch
_i == 1 => array.get(array1, _j)
_i == 2 => array.get(array2, _j)
_i == 3 => array.get(array3, _j)
_i == 4 => array.get(array4, _j)
_i == 5 => array.get(array5, _j)
_i == 6 => array.get(array6, _j)
_i == 7 => array.get(array7, _j)
//~ ___________________________ Create Table ________________________________
create_table(_col, _row, _txt) =>
var table _tbl = table.new(position = table_pos, columns = t_column_size , rows = t_row_size, border_width=1)
color _color = _row == 0 or _col == 0 ? color.rgb(3, 62, 106) : color.rgb(2, 81, 155)
table.cell(_tbl, _col, _row, _txt, bgcolor = _color, text_color = color.white, text_size = text_size)
//~___________________________ Fill With Data _______________________________
if barstate.islastconfirmedhistory and i_showweeklyPerformance and tradeDateIsAllowed
for i = 0 to t_column_size - 1 by 1
for j = 0 to t_row_size - 1 by 1
_txt = ""
if i >= 0 and j == 0
_txt := array.get(t_column_names, i)
if j >= 0 and i == 0
_txt := array.get(t_row_names, j)
if i >= 1 and j >= 1 and j <= 5
_txt := f_retrieve_data_to_table( i , j)
create_table(i ,j , _txt)
//~ ___________________________ Notice ______________________________________
if timeframe.in_seconds() > timeframe.in_seconds("D")
x = table.new(position.middle_center,1,1,color.aqua)
table.cell_set_text(x,0,0,"Please select lower timeframes (Daily or lower)")
//~ !!!!!!!!!!!!!!!_________________ STOP _________________!!!!!!!!!!!!!!!!!!
//~ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//~ ___________________________________________________________________________
// Global Dashboard Variables
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Dashboard Table Text Size
i_tableTextSize = "Normal" //input.string(title="Dashboard Size", defval="Normal", options= , group="Dashboards")
table_text_size(s) =>
switch s
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
tableTextSize = table_text_size(i_tableTextSize)
// Monthly Table Performance Dashboard By @QuantNomad
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_showMonthlyPerformance = input.bool(false, 'Monthly Performance', group='Dashboards', inline="Show Dashboards")
i_monthlyReturnPercision = 2
if i_showMonthlyPerformance and tradeDateIsAllowed
new_month = month(time) != month(time )
new_year = year(time) != year(time )
eq = strategy.equity
bar_pnl = eq / eq - 1
cur_month_pnl = 0.0
cur_year_pnl = 0.0
// Current Monthly P&L;
cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl ) * (1 + bar_pnl) - 1
// Current Yearly P&L;
cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl ) * (1 + bar_pnl) - 1
// Arrays to store Yearly and Monthly P&Ls;
var month_pnl = array.new_float(0)
var month_time = array.new_int(0)
var year_pnl = array.new_float(0)
var year_time = array.new_int(0)
last_computed = false
if (not na(cur_month_pnl ) and (new_month or barstate.islastconfirmedhistory))
if (last_computed )
array.pop(month_pnl)
array.pop(month_time)
array.push(month_pnl , cur_month_pnl )
array.push(month_time, time )
if (not na(cur_year_pnl ) and (new_year or barstate.islastconfirmedhistory))
if (last_computed )
array.pop(year_pnl)
array.pop(year_time)
array.push(year_pnl , cur_year_pnl )
array.push(year_time, time )
last_computed := barstate.islastconfirmedhistory ? true : nz(last_computed )
// Monthly P&L; Table
var monthly_table = table(na)
if (barstate.islastconfirmedhistory)
monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1)
table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999, text_size=tableTextSize)
for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc, text_size=tableTextSize)
y_color = array.get(year_pnl, yi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.gray, transp = 40)
table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100, i_monthlyReturnPercision)), bgcolor = y_color, text_color=color.new(color.white, 0),text_size=tableTextSize)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = array.get(month_pnl, mi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.maroon, transp = 40)
table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100, i_monthlyReturnPercision)), bgcolor = m_color, text_color=color.new(color.white, 0), text_size=tableTextSize)
hide = timeframe.isintraday
// Input for EMA period
emaPeriod = 48 //input.int(48, title="EMA Period")
emaPeriod2 = 2 //input.int(2, title="EME Period 2")
emaPeriod3 = 21 //input.int(21, title="EMA Period")
// Input to toggle EMA Cloud
showcloud = input.bool(false, title="Plot EMA?", group='EMA & ATR', inline="Show EMA's & ATR")
useHTF = input.bool(true, title = "Use Higher Time Frame?")
matimeframe = useHTF ? my_time1 : ''
// EMA calculations
ema = request.security(syminfo.tickerid, matimeframe, ta.ema(close, emaPeriod))
ema2 = request.security(syminfo.tickerid, matimeframe, ta.ema(close,emaPeriod2))
ema3 = request.security(syminfo.tickerid, matimeframe,ta.ema(close, emaPeriod3))
emaColor = close > ema3 ? color.new(color.rgb(56, 142, 60, 63), 50) : color.new(color.rgb(147, 40, 51, 38), 50)
// Plotting EMA's
// plot_ema1 = plot(hide ? ema : na, style=plot.style_line, color=color.new(color.rgb(255, 255, 255, 100), 50), title="EMA", linewidth=2)
// plot_ema2 = plot(hide ? ema2 : na, style=plot.style_line, color=color.new(color.rgb(255, 255, 255, 100), 50), title="EMA", linewidth=1)
// plot_ema3 = plot(ema3, style=plot.style_line, color=emaColor, title="EMA", linewidth=1)
// EMA Cloud
cloudColor = ema2 > ema ? color.new(#0f8513, 80) : color.new(#a81414, 80)
cloudColor2 = ema2 > ema3 ? color.new(#0f8513, 50) : color.new(#a81414, 50)
cloudColor := showcloud ? cloudColor : na
// fill(plot_ema1, plot_ema2, color=cloudColor, title="EMA Cloud")
// fill(plot_ema3, plot_ema2, color=cloudColor, title="EMA Cloud")
/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © BackQuant
import TradingView/ta/4 as ta
//@version=5
//indicator(
// title="DEMA Adjusted Average True Range ",
// shorttitle = "DEMA ATR ",
// overlay=true,
// timeframe="",
// timeframe_gaps=true
// )
// Define User Inputs
simple bool showAtr = input.bool(false, "Plot Dema?", group='EMA & ATR', inline="Show EMA's & ATR")
simple bool haCandles = true //input.bool(true, "Use HA Candles?")
simple int periodDema = 7 //input.int(7, "Dema Period", group = "Dema Atr")
series float sourceDema = close //input.source(close, "Calculation Source", group = "Dema Atr")
simple int periodAtr = 14 //input.int(14, "Period", group = "Dema Atr")
simple float factorAtr = 1.7 //input.float(1.7, "Factor", step = 0.01, group = "Dema Atr")
simple color longColour = #66bb6a
simple color shortColour = #f23645
/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Use HA Candles?
heikinashi_close = request.security(
symbol = ticker.heikinashi(syminfo.tickerid),
timeframe = timeframe.period,
expression = close,
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_on
)
var series float source = close
if haCandles == true
source := heikinashi_close
if haCandles == false
source := sourceDema
/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Function
DemaAtrWithBands(periodDema, source, lookback, atrFactor)=>
ema1 = ta.ema(source, periodDema)
ema2 = ta.ema(ema1, periodDema)
demaOut = 2 * ema1 - ema2
atr = ta.atr(lookback)
trueRange = atr * atrFactor
DemaAtr = demaOut
DemaAtr := nz(DemaAtr , DemaAtr)
trueRangeUpper = demaOut + trueRange
trueRangeLower = demaOut - trueRange
if trueRangeLower > DemaAtr
DemaAtr := trueRangeLower
if trueRangeUpper < DemaAtr
DemaAtr := trueRangeUpper
DemaAtr
// Function Out
DemaAtr = DemaAtrWithBands(periodDema, source, periodAtr, factorAtr)
/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Conditions
DemaAtrLong = DemaAtr > DemaAtr
DemaAtrShort = DemaAtr < DemaAtr
// Colour Condtions
var color Trendcolor = #ffffff
if DemaAtrLong
Trendcolor := longColour
if DemaAtrShort
Trendcolor := shortColour
// Plotting
plot( showAtr ? DemaAtr : na, "ATR", color=Trendcolor, linewidth = 2 )
import DevLucem/ZigLib/1 as ZigZag
////////
// Fetch Ingredients
//
// ////////
// // Bake it with a simple oven this time
= ZigZag.zigzag(low, high, Depth, Deviation, Backstep)
string nowPoint = ""
var float lastPoint = z1.price
if bool(ta.change(direction))
lastPoint := z1.price
// ////////
// // Let it Cool And Serve
line zz = na
label point = na
if repaint
zz := line.new(z1, z2, xloc.bar_time, extend? extend.right: extend.none, color.new(direction>0? upcolor: dncolor, lines), width=line_thick)
nowPoint := direction<0? (z2.pricelastPoint? "HH": "LH")
point := label.new(z2, nowPoint, xloc.bar_time, yloc.price,
color.new(direction<0? upcolor: dncolor, labels), direction>0? label.style_label_down: label.style_label_up, color.new(direction>0? upcolor: dncolor, labels), label_size)
if direction == direction
line.delete(zz )
label.delete(point )
else
line.set_extend(zz , extend.none)
else
if direction != direction
zz := line.new(z1 , z2 , xloc.bar_time, extend.none, color.new(direction>0? upcolor: dncolor, lines), width=line_thick)
nowPoint := direction <0? (z2.price lastPoint ? "HH": "LH")
point := label.new(z2 , nowPoint, xloc.bar_time, yloc.price,
color.new(direction <0? upcolor: dncolor, labels), direction >0? label.style_label_down: label.style_label_up, color.new(direction >0? upcolor: dncolor, labels), label_size)
bgcolor(direction<0? color.new(dncolor, background): color.new(upcolor, background), title='Direction Background', display = display.none)
plotarrow(direction, "direction", display=display.status_line)
// ////////
// // Declare Meal Was Sweet By Force
alertcondition(nowPoint == "HH" and z2.price != z2.price , "New Higher High", 'Zigzag on {{ticker}} higher higher high detected at {{time}}')
alertcondition(nowPoint == "LH" and z2.price != z2.price , "New Lower High", 'Zigzag on {{ticker}} higher lower high detected at {{time}}')
alertcondition(nowPoint == "HL" and z2.price != z2.price , "New Higher Low", 'Zigzag on {{ticker}} higher lower low detected at {{time}}')
alertcondition(nowPoint == "LL" and z2.price != z2.price , "New Lower Low", 'Zigzag on {{ticker}} lower low detected at {{time}}')
alertcondition(direction != direction , 'Direction Changed', 'Zigzag on {{ticker}} direction changed at {{time}}')
alertcondition(direction != direction and direction>0, 'Bullish Direction', 'Zigzag on {{ticker}} bullish direction at {{time}}')
alertcondition(direction != direction and direction<0, 'Bearish Direction', 'Zigzag on {{ticker}} bearish direction at {{time}}')
if direction != direction
alert((direction<0? "Bearish": "Bullish") + " Direction Final ", alert.freq_once_per_bar_close)
MSG = "MARKET STRUCTURE"
VBG = "VOLUMETRIC ORDER BLOCKS"
MST = "Limit market structure calculation to improve memory speed time"
SLT = " Limit swing structure to tot bars back"
IDT = " Start date of the internal structure"
CST = "Color candle based on trend detection system"
OBT = "Display internal buy and sell activity"
OBD = "Show Last number of orderblock"
OBMT = " Use Length to adjust cordinate of the orderblocks Use whole candle body"
_ ='
------------
–––––––––––––––––––––––––– INPUTS –––––––––––––––––––––––––––
------------ '//{
bool windowsis = input.bool(true, "Window", inline="kla", group=MSG)
int mswindow = input.int(5000, "", tooltip=MST,group=MSG, inline="kla", minval=1000)
bool showSwing = input.bool(true, "Swing", inline="scss", group=MSG)
int swingLimit = input.int(100, "", tooltip=SLT, inline="scss", group=MSG, minval=10, maxval=200)
color swingcssup = input.color(#f7525f, "", inline="scss", group=MSG)
color swingcssdn = input.color(#66bb6a, "", inline="scss", group=MSG)
bool showMapping = input.bool(false, "Mapping Structure", inline="mapping", group=MSG)
string mappingStyle = input.string("----", "", options= , inline="mapping", group=MSG)
color mappingcss = input.color(color.silver, "", tooltip="Display Mapping Structure", inline="mapping", group=MSG)
bool candlecss = input.bool(false, "Color Candles", tooltip=CST, group=MSG, inline="txt")
string mstext = input.string("Tiny", "", options= ,
inline="txt", group=MSG)
string msmode = input.string("Adjusted Points", "Algorithmic Logic", options=
, inline="node", group=MSG)
int mslen = input.int(5, "", inline="node", group=MSG, minval=2)
bool buildsweep = input.bool(true, "Build Sweep (x)", "Build sweep on market structure", "znc", MSG)
bool msbubble = input.bool(true, "Bubbles", tooltip="Display Circle Bubbles", inline="bubbles", group=MSG)
bool obshow = input.bool(true, "Show Last", tooltip=OBD, group=VBG, inline="obshow")
int oblast = input.int(5, "", group=VBG, inline="obshow", minval=0)
color obupcs = input.color(color.new(#089981, 90), "", inline="obshow", group=VBG)
color obdncs = input.color(color.new(#f23645, 90), "", inline="obshow", group=VBG)
bool obshowactivity = input.bool(true, "Show Buy/Sell Activity", inline="act", group=VBG, tooltip=OBT)
color obactup = input.color(color.new(#089981, 50), "", inline="act", group=VBG)
color obactdn = input.color(color.new(#f23645, 50), "", inline="act", group=VBG)
obshowbb = input.bool(false, "Show Breakers", inline="bb", group=VBG, tooltip="Display Breakers")
color bbup = input.color(color.new(#089981, 100), "", inline="bb", group=VBG)
color bbdn = input.color(color.new(#f23645, 100), "", inline="bb", group=VBG)
obmode = input.string("Length", "Construction", options= , tooltip=OBMT, inline="atr", group=VBG)
len = input.int(5, "", inline="atr", group=VBG, minval=1)
obmiti = input.string("Close", "Mitigation Method", options= ,
tooltip="Mitigation method for when to trigger order blocks", group=VBG)
obtxt = input.string("Normal", "Metric Size", options= ,
tooltip="Order block Metrics text size", inline="txt", group=VBG)
showmetric = input.bool(true, "Show Metrics", group=VBG)
showline = input.bool(true, "Show Mid-Line", group=VBG)
overlap = input.bool(true, "Hide Overlap", group=VBG, inline="ov")
wichlap = input.string("Recent", "", options= , inline="ov", group=VBG)
fvg_enable = input.bool(false, "", inline="1", group="FAIR VALUE GAP", tooltip="Display fair value gap")
what_fvg = input.string("FVG", "", inline="1", group="FAIR VALUE GAP", tooltip="Display fair value gap",
options= )
fvg_num = input.int(5, "Show Last", inline="1a", group="FAIR VALUE GAP", tooltip="Number of fvg to show", minval=0)
fvg_upcss = input.color(color.new(#089981, 80), "", inline="1", group="FAIR VALUE GAP")
fvg_dncss = input.color(color.new(#f23645, 80), "", inline="1", group="FAIR VALUE GAP")
fvgbbup = input.color(color.new(#089981, 100), "", inline="1", group="FAIR VALUE GAP")
fvgbbdn = input.color(color.new(#f23645, 100), "", inline="1", group="FAIR VALUE GAP")
fvg_src = input.string("Close", "Mitigation",
inline="3",
group="FAIR VALUE GAP",
tooltip=" Use the close of the body as trigger Use the extreme point of the body as trigger",
options= )
fvgthresh = input.float(0, "Threshold", tooltip="Filter out non significative FVG", group="FAIR VALUE GAP",
inline="asd", minval=0, maxval=2, step=0.1)
fvgoverlap = input.bool(true, "Hide Overlap", "Hide overlapping FVG", group="FAIR VALUE GAP")
fvgline = input.bool(true, "Show Mid-Line", group="FAIR VALUE GAP")
fvgextend = input.bool(false, "Extend FVG", group="FAIR VALUE GAP")
dispraid = input.bool(false, "Display Raids", inline="raid", group="FAIR VALUE GAP")
//}
_ ='
------------
–––––––––––––––––––––––––– UDT –––––––––––––––––––––––––––
------------ '//{
type hqlzone
box pbx
box ebx
box lbx
label plb
label elb
label lbl
type Zphl
line top
line bottom
label top_label
label bottom_label
bool stopcross
bool sbottomcross
bool itopcross
bool ibottomcross
string txtup
string txtdn
float topy
float bottomy
float topx
float bottomx
float tup
float tdn
int tupx
int tdnx
float itopy
float itopx
float ibottomy
float ibottomx
float uV
float dV
type entered
bool normal = false
bool breaker = false
type store
line ln
label lb
box bx
linefill lf
type structure
int zn
float zz
float bos
float choch
int loc
int temp
int trend
int start
float main
int xloc
bool upsweep
bool dnsweep
string txt = na
type drawms
int x1
int x2
float y
string txt
color css
string style
type ob
bool bull
float top
float btm
float avg
int loc
color css
float vol
int dir
int move
int blPOS
int brPOS
int xlocbl
int xlocbr
bool isbb = false
int bbloc
type FVG
float top = na
float btm = na
int loc = bar_index
bool isbb = false
int bbloc = na
bool israid = false
float raidy = na
int raidloc = na
int raidx2 = na
bool active = false
color raidcs = na
type SFP
float y
int loc
float ancor
type sfpbuildlbl
int x
float y
string style
color css
string txt
type sfpbuildline
int x1
int x2
float y
color css
float ancor
int loc
type equalbuild
int x1
float y1
int x2
float y2
color css
string style
type equalname
int x
float y
string txt
color css
string style
type ehl
float pt
int t
float pb
int b
type sellbuyside
float top
float btm
int loc
color css
string txt
float vol
type timer
bool start = false
int count = 0
//}
_ ='
------------
–––––––––––––––––––––––––– SETUP –––––––––––––––––––––––––––
------------ '//{
var store bin = store.new(
array.new< line >()
, array.new< label >()
, array.new< box >()
, array.new()
)
var entered blobenter = entered.new()
var entered brobenter = entered.new()
var entered blfvgenter = entered.new()
var entered brfvgenter = entered.new()
var entered blarea = entered.new()
var entered brarea = entered.new()
var timer lc = timer.new ()
if barstate.islast
for obj in bin.ln
obj.delete()
for obj in bin.lb
obj.delete()
for obj in bin.bx
obj.delete()
for obj in bin.lf
obj.delete()
bin.ln.clear()
bin.lb.clear()
bin.bx.clear()
bin.lf.clear()
invcol = #ffffff00
float atr = (ta.atr(200) / (5/len))
//}
_ ='
------------
–––––––––––––––––––––––––– UTILITY –––––––––––––––––––––––––––
------------ '//{
method txSz(string s) =>
out = switch s
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
out
method lstyle(string style) =>
out = switch style
'⎯⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
ghl() => [high , low , close , open , close, open, high, low, high , low , ta.atr(200)]
method IDMIDX(bool use_max, int loc) =>
min = 99999999.
max = 0.
idx = 0
if use_max
for i = 0 to (bar_index - loc)
max := math.max(high , max)
min := max == high ? low : min
idx := max == high ? i : idx
else
for i = 0 to (bar_index - loc)
min := math.min(low , min)
max := min == low ? high : max
idx := min == low ? i : idx
idx
SFPData() => [high, high , high , low, low , low , close, volume, time, bar_index , time ]
SFPcords() =>
RealTF = barstate.isrealtime ? 0 : 1
= SFPData()
[h , h1 , h2 , l , l1 , l2 , c , v , t , n , t1 ]
method find(structure ms, bool use_max, bool sweep, bool useob) =>
min = 99999999.
max = 0.
idx = 0
if not sweep
if ((bar_index - ms.loc) - 1) > 0
if use_max
for i = 0 to (bar_index - ms.loc) - 1
max := math.max(high , max)
min := max == high ? low : min
idx := max == high ? i : idx
if useob
if high
Bull/Bear FVG Density RatioThis indicator tracks the directional frequency of Fair Value Gaps (FVGs) over a configurable lookback window, offering a clean, responsive measure of market imbalance.
🔍 What It Does:
Detects bullish and bearish FVGs using a 3-bar displacement logic
Calculates the ratio of FVGs to candles over the last N bars
Plots separate density curves for bullish and bearish FVGs
Includes a threshold line to help identify regime shifts (e.g., drought vs spate)
📈 How to Use:
Use rising density to confirm trend strength or breakout momentum
Watch for crossovers above the threshold to signal active imbalance regimes
Combine with price action or volume overlays for high-confluence setups
⚙️ Inputs:
Lookback Window: Number of candles used to calculate FVG density
Threshold: Visual guide for regime classification (default: 0.2)
This tool is ideal for traders who want to move beyond symptomatic signals and model structural causality. It pairs well with lifecycle scoring, retest velocity, and HTF overlays.
Intraday Technical Strength Dashboard — 5m (Universal) — FIXED2An Intraday Technical Strength Dashboard for RSI, OBV, MACD, ADX, and EMA Cloud
X Trade Plan [asset]A precision-structured execution framework designed to identify, map, and visualize targeted areas of interest derived from prior end-of-day AVWAP levels. These areas represent historically important zones where order flow has previously rotated, absorbed, or redistributed—making them highly relevant for future intraday decision-making.
This tool is intended to work in direct combination with the X Tail that Wags indicator, which calculates and projects the previous session’s ending AVWAP forward into the next trading day. The projected end-of-day AVWAP levels serve as a backbone for this Trade Plan: each level is wrapped, extended, and visually organized into a standardized zone structure that the trader can interpret quickly and consistently.
Purpose and Core Concept
Markets consistently respond to prior session value. The end-of-day AVWAP reflects the final consensus price where volume and time-weighted participation reached equilibrium before the session closed. When carried forward, these levels often act as real-world:
Reversion points
Liquidity pockets
Control centers
Continuation or rejection pivots
Absorption shelves and distribution tops
By framing these AVWAP-derived levels into controlled ranges—each with a slight configurable margin—the indicator transforms abstract numbers into objective, visually actionable trading zones.
How This Indicator Works
The user inputs up to fifteen prior AVWAP levels that came from X Tail that Wags’ “Previous End-of-Day AVWAP” readouts. For each active level, X Trade Plan automatically:
Builds a structured zone around the AVWAP using a user-defined ± margin
Draws a filled box from the anchor bar forward a customizable distance
Adds optional top/bottom price labels for precision
Optionally draws a mid-line representing the core of the zone
Displays custom text labels for classification, notes, or tiering
Refreshes anchor points at user-selected higher-timeframe boundaries (e.g., Daily) so zones “reset cleanly” at each new session
Everything is designed to ensure consistent, non-overlapping, visually efficient zones that maintain chart clarity even when multiple levels are active.
Intended Use in a Trade Plan
This indicator is not a signal generator.
It is a structural mapping tool designed for traders who build a daily plan around:
1. Prior Value → Future Reaction
Price commonly retests, respects, or rejects previous session AVWAP levels. These zones act as tactical reference points to evaluate:
Whether price is accepting value
Rejecting value
Targeting inefficiencies
Passing through low-resistance channels
2. Defining Areas of Interest (AOIs)
Each zone identifies where:
Positioning from previous sessions may still exist
Liquidity may sit
Algorithmic systems often pivot
High-volume traders previously accumulated or distributed
3. Enhancing Bias and Scenario Planning
When used with X Tail that Wags, traders can combine:
Current session AVWAP direction
Prior session ending AVWAP levels
The constructed Trade Plan zones
to produce:
Meaningful upside/downside targets
Control-center ranges
Lean / location for entries
Expected reaction points
This synergy turns raw historical AVWAP data into actionable structure.
Why These Levels Matter
End-of-day AVWAP levels are powerful because they encapsulate:
The final “fair value” of the prior session
Where the most volume-weighted agreement occurred
Where institutional inventory was likely set or hedged
The price many algos and funds benchmark against
When the next session opens, these prior value levels serve as magnets and decision boundaries, helping traders anticipate:
High-probability pullback zones
Reversals off previous value
Break-and-go continuation levels
Failure points where trapped participants are forced to exit
Summary
X Trade Plan
𝑎
𝑠
𝑠
𝑒
𝑡
asset transforms prior AVWAP levels—sourced from X Tail that Wags—into a structured visual map of the market’s most relevant historical value areas. These zones are used to shape a deliberate, rules-based Trade Plan that identifies where the market is likely to react, pause, rotate, or accelerate during the current session.
When paired with X Tail that Wags, this indicator provides a powerful, integrated workflow for traders who rely on value-based context, precise levels, and scenario-driven preparation.






















