Enhanced Zigzag [victhoreb]Enhanced Zigzag is an optimized version of the classic zigzag indicator, crafted using 50 lines of Pine Script code compared to TradingView’s native version which exceeds 300 lines. Its compact logic efficiently detects pivot highs and lows using customizable lookback periods, then dynamically connects these key points with clear, color-adjustable zigzag lines. With options to toggle the zigzag display and enable repainting, this indicator offers both performance and flexibility—providing traders with a streamlined tool for identifying market swings and potential reversals with minimal code complexity.
Motifs graphiques
Enhanced X1 Algo for Spot Trading with RSI, ATR, and MACDThe Enhanced X1 Algo is a versatile trading indicator for spot trading, integrating SMA, ROC, RSI, ATR, and MACD for robust buy and sell signals. It dynamically displays only the most recent trigger set, with clear entry, target, and stop levels. Ideal for various trading styles, this indicator provides real-time alerts and comprehensive market analysis, enhancing your trading strategy.
RSI Trend Bias█ OVERVIEW
The RSI Trend Bias indicator is a custom technical analysis tool that utilizes the Relative Strength Index (RSI) to gauge market momentum and identify potential trend shifts. By monitoring RSI crossovers and crossunders relative to customizable threshold levels, the indicator provides clear visual cues that distinguish between bullish and bearish market conditions. This flexible approach makes it suitable for both short-term scalping and longer-term trend analysis.
█ KEY FEATURES
Dynamic RSI Trend Detection
The indicator dynamically determines market bias by monitoring the RSI for crossovers above the upper threshold and crossunders below the lower threshold. This method ensures that only significant momentum shifts trigger a change in trend, reducing false signals in volatile markets.
Adaptive Visualizations
The RSI Trend Bias indicator enhances clarity by plotting the RSI with colors that reflect current market conditions. Additionally, it offers an optional background color change to further emphasize bullish or bearish states, providing immediate visual feedback to traders.
Clear Threshold Indicators
Upper and lower threshold levels are plotted as constant reference lines, clearly delineating overbought and oversold regions. These markers help traders quickly assess market conditions at a glance.
Customizable Settings
Users have full control over key parameters including the RSI length, threshold levels, and visual settings. This customization allows the indicator to be tailored for different markets and trading styles, ensuring optimal performance across various timeframes.
█ UNDERLYING METHODOLOGY & CALCULATIONS
RSI Calculation
The indicator computes the Relative Strength Index over a user-defined period (default is 14), providing a measure of market momentum that reflects price changes over time.
Trend Determination Logic
By detecting when the RSI crosses above the upper threshold, the indicator signals a shift towards bullish momentum. Conversely, a crossunder below the lower threshold indicates bearish conditions. This straightforward binary approach filters out minor fluctuations, ensuring clarity in trend analysis.
Visual Signal Integration
Based on the detected trend, the RSI line is dynamically colored—green for bullish conditions and red for bearish conditions. An optional background color change further reinforces these signals, offering an immediate visual cue of prevailing market sentiment.
█ HOW TO USE THE INDICATOR
1 — Apply the Indicator
• Add the RSI Trend Bias indicator to a separate pane in your trading platform.
2 — Adjust Settings for Your Market
• RSI Length – Define the period for RSI calculation (default is 14).
• Threshold Levels – Set the upper (default 70) and lower (default 30) thresholds to identify overbought and oversold conditions.
• Visual Customization – Choose the bullish (green) and bearish (red) colors, and enable background color changes to enhance visual trend recognition.
3 — Interpret the Signals
• RSI Line – Observe the dynamically colored RSI line; a shift to green signals bullish momentum, while red indicates bearish conditions.
• Threshold Levels – Use the constant upper and lower lines as reference points for overbought and oversold states.
• Signal Timing – A crossover above the upper threshold or a crossunder below the lower threshold suggests potential entry or exit points.
4 — Integrate with Your Trading Strategy
• Combine RSI Trend Bias signals with other technical analysis tools to confirm market direction.
• Utilize the visual cues for fine-tuning your entry and exit decisions, ensuring robust risk management and optimized trade timing.
█ CONCLUSION
The RSI Trend Bias indicator offers a streamlined yet effective approach to monitoring market momentum. By leveraging the established principles of RSI analysis alongside dynamic visual cues, it enables traders to quickly identify bullish and bearish trends. Its customizable features and clear threshold indicators make it a valuable tool for enhancing technical analysis and making informed trading decisions.
Whale Activity Indicator (WAI)Overview
The Whale Activity Indicator (WAI) is designed to detect institutional accumulation, dark pool trades, and high-volume transactions that often precede major price moves. By analyzing volume spikes, On-Balance Volume (OBV), and the Money Flow Index (MFI), this indicator identifies potential whale buy and sell zones, providing traders with an edge in spotting large player activity.
How It Works
1️⃣ Institutional & Dark Pool Volume Detection
🔹 Large financial institutions and hedge funds often execute trades in dark pools or through block trades to prevent price slippage.
🔹 The indicator compares the current volume to predefined institutional and dark pool volume thresholds to determine if a trade is large enough to be considered whale activity.
🛠 Calculation:
If the total volume exceeds the Dark Pool Volume Threshold, it’s flagged as a dark pool trade.
If the total volume exceeds the Institutional Volume Threshold, it’s flagged as an institutional trade.
2️⃣ Volume Spike Detection
🔹 A sudden spike in trading volume relative to historical averages often signals the presence of institutional traders.
🔹 Instead of using a strict Z-score, this indicator detects volume spikes based on a rolling percentile threshold to ensure better adaptability across different assets.
🛠 Calculation:
Computes the Simple Moving Average (SMA) of volume over a period.
Defines a volume spike as any bar where the volume is 1.5× above the SMA (adjustable for sensitivity).
3️⃣ Trend Confirmation Using OBV & MFI
🔹 Institutions rarely trade against the trend, so additional validation is done using On-Balance Volume (OBV) and the Money Flow Index (MFI).
🛠 Calculation:
OBV (On-Balance Volume): Measures buying and selling pressure. A rising OBV suggests accumulation, while a falling OBV suggests distribution.
MFI (Money Flow Index): Confirms whether the volume is being accompanied by price movement, filtering out false signals.
🔹 BUY Signal: When OBV & MFI are both rising, it confirms institutional accumulation.
🔹 SELL Signal: When OBV & MFI are both falling, it confirms institutional distribution.
Signals & Visualization
📊 Plots:
✅ Green Up Label (Whale Buy) → Indicates institutional accumulation and potential price increase.
❌ Red Down Label (Whale Sell) → Indicates institutional distribution and potential price drop.
📉 Volume Histogram & Threshold Line → Helps visualize volume spikes relative to historical levels.
How to Use It in Trading
✔ Use this indicator on highly liquid assets (e.g., SPY, AAPL, NVDA) for best results.
✔ Combine with options flow analysis for deeper insight into institutional positioning.
✔ Adjust volume thresholds based on the asset’s liquidity and average trading volume.
✔ Backtest with different sensitivity levels to find optimal settings for your strategy.
🔔 Optional Add-ons: Alerts can be added to notify traders of significant whale movements in real time!
ALL Candelstick Pattern✅ User Input for Shadow Ratio
✔ You can now set the shadow-to-body ratio in the settings.
✔ Default value = 2.0 (you can change it).
Bullish Hammer (Green Arrow & Label)
Bearish Inverted Hammer (Red Arrow & Label)
TOP & Bottom FinderThis script is designed to help traders identify potential market tops and bottoms using RSI-based calculations and ATR-based support detection.
Key Features:
✅ Top Finder – Uses a customized RSI-based method to detect overbought conditions.
✅ Bottom Finder – Identifies potential bottoming areas based on RSI, ATR, and bullish rejection candles.
✅ Arrow Signals – Plots visual markers at potential reversal points.
This tool is ideal for traders looking to spot trend reversals and make informed trading decisions. 📈📉🚀
5-8-13 EMA Strategy5-8-13 EMA Strategy Indicator
This indicator leverages three Exponential Moving Averages (EMAs) with periods of 5, 8, and 13 to identify trend direction and generate actionable trading signals for options, stocks, or other markets. Based on Fibonacci-inspired lengths, the strategy uses the fast-reacting 5 EMA, the smoothing 8 EMA, and the trend-setting 13 EMA to spot momentum shifts.
How It Works:
Buy Call Signal: Triggers when the 5 EMA crosses above the 8 EMA, signaling bullish momentum. Optionally, confirmation requires the candle to close above the 5 EMA with all EMAs stacked bullishly (5 > 8 > 13).
Buy Put Signal: Triggers when the 5 EMA crosses below the 8 EMA, indicating bearish momentum. Confirmation can require a close below the 5 EMA with a bearish stack (5 < 8 < 13).
Signals appear as "Buy Call" (green label below the bar) or "Buy Put" (red label above the bar).
Features:
Customizable signal modes: "Crossover Only" for faster triggers or "Crossover + Close Confirmation" for stricter entries.
Toggle signals on/off via settings.
Visual EMAs (blue 5, orange 8, red 13) overlay the chart for easy trend tracking.
Alert conditions for real-time notifications.
Best Use:
Ideal for day trading on shorter timeframes (e.g., 5-minute charts) or swing trading on longer ones (e.g., 15-minute). Works best in trending markets; pair with additional filters like volume or support/resistance to reduce noise in choppy conditions.
5-8-13 EMA StrategyHere’s a concise yet informative description for your 5-8-13 EMA strategy indicator that you can use in the script or share elsewhere. It captures the essence of what we’ve discussed—how it works, its purpose, and its flexibility—while keeping it trader-friendly.
5-8-13 EMA Strategy Indicator
This indicator leverages three Exponential Moving Averages (EMAs) with periods of 5, 8, and 13 to identify trend direction and generate actionable trading signals for options, stocks, or other markets. Based on Fibonacci-inspired lengths, the strategy uses the fast-reacting 5 EMA, the smoothing 8 EMA, and the trend-setting 13 EMA to spot momentum shifts.
How It Works:
Buy Call Signal: Triggers when the 5 EMA crosses above the 8 EMA, signaling bullish momentum. Optionally, confirmation requires the candle to close above the 5 EMA with all EMAs stacked bullishly (5 > 8 > 13).
Buy Put Signal: Triggers when the 5 EMA crosses below the 8 EMA, indicating bearish momentum. Confirmation can require a close below the 5 EMA with a bearish stack (5 < 8 < 13).
Signals appear as "Buy Call" (green label below the bar) or "Buy Put" (red label above the bar).
Accurate Trend IndicatorAccurate Trend Indicator
The Accurate Trend Indicator is a powerful trend-following tool designed to help traders identify optimal buy and sell opportunities with precision. Based on the Supertrend algorithm, this indicator dynamically tracks market trends and provides clear entry and exit signals.
Features:
✅ Supertrend-Based Signals – Uses ATR (Average True Range) to determine trend direction.
✅ Buy & Sell Alerts – Displays green "BUY" labels and red "SELL" labels when trend changes.
✅ Color-Coded Candles – Bullish candles turn green, and bearish candles turn red for better visualization.
✅ Works on Any Market – Compatible with Forex, Stocks, Crypto, and Commodities.
✅ Customizable Inputs – Adjust the ATR length and multiplier to fit your trading strategy.
How It Works:
A BUY signal appears when the price crosses above the Supertrend line.
A SELL signal appears when the price crosses below the Supertrend line.
Candle colors change based on trend direction to enhance clarity.
This indicator is ideal for traders who want a simple yet effective tool to follow market trends and make informed decisions.
🚀 Try it now and enhance your trading strategy! 🚀
Buy & Sell Signal Indicator based on 9 ema Script Summary: Buy & Sell Signal Indicator
This Pine Script v5 indicator is designed to generate buy and sell signals based on the relationship between the 9-period EMA (Exponential Moving Average) and trend structure (higher highs, higher lows for buy signals; lower highs, lower lows for sell signals).
Main Components:
9 EMA Calculation
ema9 = ta.ema(close, 9)
Acts as a trend filter for trade signals.
Trend Identification:
Higher Highs & Higher Lows → Indicates an uptrend
Lower Highs & Lower Lows → Indicates a downtrend
Buy Signal Condition:
close > ema9 and close > ema9 (above EMA)
Presence of higher highs and higher lows
Indicates a bullish trend → Plots a green "BUY" label below bars.
Sell Signal Condition:
close < ema9 and close < ema9 (below EMA)
Presence of lower highs and lower lows
Indicates a bearish trend → Plots a red "SELL" label above bars.
Chart Visuals:
Green "BUY" label below bars for buy signals.
Red "SELL" label above bars for sell signals.
Blue 9 EMA line for trend reference.
Usage & Interpretation:
Buy signals suggest potential long entries in an uptrend.
Sell signals suggest potential short entries in a downtrend.
Works best in trending markets rather than ranging conditions.
Color Code OverlayColor Code Overlay Indicator
The Color Code Overlay indicator is designed to provide a dynamic visualization of price action using color-coded candles. This overlay highlights trend reversals and bullish/bearish conditions by utilizing a custom candle calculation and the Average True Range (ATR) percentage threshold to detect significant price changes.
Key Features:
Custom Candle Calculation:
The Color Code Overlay is based on a modified candlestick calculation that takes the average of the open, high, low, and close prices to determine the candle’s close value. The open value is derived from the midpoint of the current candle's open and close or the previous Color Code Overlay close. The high and low values are based on the highest and lowest prices between the open, close, and the actual market high/low.
Color-Coding:
Green: The candle is colored green when the close is higher than the open, indicating a bullish trend.
Red: The candle is colored red when the close is lower than the open, indicating a bearish trend.
Color Change Detection:
The indicator detects significant color changes, signaling trend reversals. The transitions are determined based on the following conditions:
A bullish to bearish change (green to red) is identified when the current candle's close is lower than the open, and the price difference exceeds 1% of the candle's range (calculated using the current candle's high and low).
A bearish to bullish change (red to green) occurs when the current candle’s close is higher than the open, and the price difference also exceeds 1% of the candle's range.
Threshold Calculation:
The dynamic threshold for detecting significant price changes is based on the ATR percentage of the candle's range. By default, the indicator uses 1% of the range for detecting meaningful price movement. This ensures that only substantial changes trigger the color shifts, providing clear signals for potential trend reversals or market momentum.
Arrows for Color Changes:
A red triangle down is plotted above the bar when the color changes from green to red (bullish to bearish).
A green triangle up is plotted below the bar when the color changes from red to green (bearish to bullish).
Alerts:
The indicator includes alert conditions that notify you when:
The price is bullish (green candle).
The price is bearish (red candle).
There is a change from green to red (bullish to bearish).
There is a change from red to green (bearish to bullish).
How It Works:
The Color Code Overlay dynamically calculates the candle values based on market data and applies the ATR-based threshold to identify color changes. A shift from bullish to bearish or vice versa is only triggered when the price moves significantly beyond the calculated threshold, helping to avoid false signals from minor price fluctuations.
This indicator is particularly useful for traders looking to spot trend reversals and significant market shifts with a clear, color-coded visual representation of price action. The Color Code Overlay can be used alongside other technical indicators to enhance decision-making and improve trading strategies.
Color Code Overlay StrategyColor Code Overlay Strategy
This strategy utilizes a custom color-coded overlay to provide accurate buy and sell signals based on dynamic color changes of the candles. The indicator works by calculating a color shift between bullish (green) and bearish (red) candles, with the color change logic driven by both price movement and volatility.
How the Color Change is Calculated:
The color change is determined by comparing the closing price relative to the opening price of each candle, as is typical with a traditional bullish or bearish candle. However, to make this strategy more adaptive to market conditions, the color change is further refined by incorporating the Average True Range (ATR).
Volatility Adjusted Color Shift: The strategy calculates a dynamic threshold based on the ATR value, which represents market volatility. If the price movement between the open and close of the candle exceeds a specific percentage of the ATR, the color of the candle shifts from red (bearish) to green (bullish) or vice versa.
Threshold Calculation: A fixed percentage (e.g., 1%) of the ATR range is used to define the minimum price movement required for a color change. This ensures that only significant price movements, adjusted for volatility, trigger the color shift. The larger the ATR (higher volatility), the greater the price movement required to cause a change in color.
Bullish to Bearish (Green to Red): When the candle closes lower than the open, and the price movement exceeds the dynamic threshold based on ATR, the candle color changes from green to red, signaling a potential bearish reversal.
Bearish to Bullish (Red to Green): When the candle closes higher than the open, and the price movement exceeds the ATR-based threshold, the candle color shifts from red to green, signaling a potential bullish reversal.
Key Features:
Dynamic Color Change: The strategy identifies key color changes from bullish to bearish (green to red) and from bearish to bullish (red to green) based on specific thresholds in candle size.
Customizable Timeframe: You can specify a custom trading window to restrict the strategy’s actions to specific hours of the day.
Stop Loss and Take Profit: The strategy incorporates risk management features, allowing you to set a stop loss and take profit based on the price in pips.
Flexible Trade Types: Choose between "Both" (long and short), "Long Only," or "Short Only" trading options to suit your preferred trading style.
Visual Alerts: Receive visual alerts with arrows when color changes occur, signaling potential trade opportunities. Green arrows indicate a bullish shift, while red arrows show a bearish shift.
This strategy is ideal for traders who prefer a color-coded overlay to easily visualize price action and make informed decisions based on bullish or bearish trends. Whether you’re looking for quick, short-term opportunities or analyzing market reversals, this strategy offers an intuitive approach to identifying trade signals.
15-Year Seasonality ChartThis is 15 years seasonality line chat to help you make informed decision on your trading
FnO Intraday Strategy with ATR SL, EMA Slope & SignalsThis intraday strategy is designed for trading F&O (Futures & Options) stocks in the Indian stock market. It focuses on breakout trades based on the first hour of the market, combining VWAP, 9 EMA, EMA slope, and ATR-based stop-loss to maximize accuracy.
PSP [Daye's Theory]Precision Swing Point (PSP) is a distinct technical analysis tool designed to evaluate the price action of three synchronized tickers.
Once a crack in correlation is detected, the indicator will display a shape below the candle where the divergence occurs.
© 2025 Matan Amar. All rights reserved.
Vertical Lines at Specific Times### **Script Description**
This **Pine Script v6** indicator for **TradingView** plots **vertical dotted lines** at user-specified times, marking key time ranges during the day. It is designed to help traders visually track market movements within specific timeframes.
#### **Features:**
✔ **Custom Timeframes:**
- Two separate time ranges can be defined:
- **Morning Session:** (Default: 9 AM - 10 AM, New York Time)
- **Evening Session:** (Default: 9 PM - 10 PM, New York Time)
✔ **Adjustable Line Properties:**
- **Line Width:** Users can change the thickness of the vertical lines.
- **Line Colors:** Users can select different colors for morning and evening session lines.
✔ **New York Local Time Support:**
- Ensures that the vertical lines appear correctly based on **Eastern Time (ET)**.
✔ **Full-Height Vertical Lines:**
- Lines extend across the **entire chart**, from the highest high to the lowest low, for clear visibility.
- Uses **dotted line style** to avoid cluttering the chart.
#### **How It Works:**
1. The script retrieves the **current date** (year, month, day) in **New York time**.
2. Converts the **user-defined input times** into **timestamps** for accurate placement.
3. When the current time matches a specified session time, a **dotted vertical line** is drawn.
4. The script **repeats this process daily**, ensuring automatic updates.
#### **Customization Options (Inputs):**
- **Morning Start & End Time** (Default: 9 AM - 10 AM)
- **Evening Start & End Time** (Default: 9 PM - 10 PM)
- **Line Width** (Default: 2)
- **Morning Line Color** (Default: Blue)
- **Evening Line Color** (Default: Green)
#### **Use Case Scenarios:**
📈 Marking market **open & close** hours.
📊 Highlighting **key trading sessions** for day traders.
🔎 Identifying time-based **price action patterns**.
Percentage Based ZigZag█ OVERVIEW
The Percentage-Based ZigZag indicator is a custom technical analysis tool designed to highlight significant price reversals while filtering out market noise. Unlike many standard zigzag tools that rely solely on fixed price moves or generic trend-following methods, this indicator uses a configurable percentage threshold to dynamically determine meaningful pivot points. This approach not only adapts to different market conditions but also helps traders distinguish between minor fluctuations and truly significant trend shifts—whether scalping on shorter timeframes or analyzing longer-term trends.
█ KEY FEATURES & ORIGINALITY
Dynamic Pivot Detection
The indicator identifies pivot points by measuring the percentage change from the previous extreme (high or low). Only when this change exceeds a user-defined threshold is a new pivot recognized. This method ensures that only substantial moves are considered, making the indicator robust in volatile or noisy markets.
Enhanced ZigZag Visualization
By connecting significant highs and lows with a continuous line, the indicator creates a clear visual map of price swings. Each pivot point is labelled with the corresponding price and the percentage change from the previous pivot, providing immediate quantitative insight into the magnitude of the move.
Trend Reversal Projections
In addition to marking completed reversals, the script computes and displays potential future reversal points based on the current trend’s momentum. This forecasting element gives traders an advanced look at possible turning points, which can be particularly useful for short-term scalping strategies.
Customizable Visual Settings
Users can tailor the appearance by:
• Setting the percentage threshold to control sensitivity.
• Customizing colors for bullish (e.g., green) and bearish (e.g., red) reversals.
• Enabling optional background color changes that visually indicate the prevailing trend.
█ UNDERLYING METHODOLOGY & CALCULATIONS
Percentage-Based Filtering
The script continuously monitors price action and calculates the relative percentage change from the last identified pivot. A new pivot is confirmed only when the price moves a preset percentage away from this pivot, ensuring that minor fluctuations do not trigger false signals.
Pivot Point Logic
The indicator tracks the highest high and the lowest low since the last pivot. When the price reverses by the required percentage from these extremes, the algorithm:
1 — Labels the point as a significant high or low.
2 — Draws a connecting line from the previous pivot to the current one.
3 — Resets the extreme-tracking for detecting the next move.
Real-Time Reversal Estimation
Building on traditional zigzag methods, the script incorporates a projection calculation. By analyzing the current trend’s strength and recent percentage moves, it estimates where a future reversal might occur, offering traders actionable foresight.
█ HOW TO USE THE INDICATOR
1 — Apply the Indicator
• Add the Percentage-Based ZigZag indicator to your trading chart.
2 — Adjust Settings for Your Market
• Percentage Move – Set a threshold that matches your trading style:
- Lower values for sensitive, high-frequency analysis (ideal for scalping).
- Higher values for filtering out noise on longer timeframes.
• Visual Customization – Choose your preferred colors for bullish and bearish signals and enable background color changes for visual trend cues.
• Reversal Projection – Enable or disable the projection feature to display potential upcoming reversal points.
3 — Interpret the Signals
• ZigZag Lines – White lines trace significant high-to-low or low-to-high movements, visually connecting key swing points.
• Pivot Labels – Each pivot is annotated with the exact price level and percentage change, providing quantitative insight into market momentum.
• Trend Projections – When enabled, projected reversal levels offer insight into where the current trend might change.
4 — Integrate with Your Trading Strategy
• Use the indicator to identify support and resistance zones derived from significant pivots.
• Combine the quantitative data (percentage changes) with your risk management strategy to set optimal stop-loss and take-profit levels.
• Experiment with different threshold settings to adapt the indicator for various instruments or market conditions.
█ CONCLUSION
The Percentage-Based ZigZag indicator goes beyond traditional trend-following tools by filtering out market noise and providing clear, quantifiable insights into price action. With its percentage threshold for pivot detection and real-time reversal projections, this original methodology and customizable feature set offer traders a versatile edge for making informed trading decisions.
VTS Buy and SellAs a trader I want to create an indicator which triggers buy signal when 9 ema crosses 26 ema and sell signal when current candle close is less than previous candle.
Anchor Buy Sell LevelsDaily Validity:
The indicator generates a single horizontal line (either a Buy Level or a Sell Level) that remains valid throughout the entire trading day.
Source of the Signal:
The level (buy or sell) is determined using candles that were generated before the day in question.
Selection Logic:
When determining the level, the indicator checks past candles in descending order (from the most recent backward).
The very first candle encountered that meets the respective logic (either the buy or sell condition) sets the level.
Buy and Sell Logic:
Buy Signal: Generated when a candle’s close is lower than both the previous candle’s close and the next candle’s close (i.e., a local minimum). The Buy Level is drawn at the low of that qualifying candle.
Sell Signal: Generated when a candle’s close is higher than both the previous candle’s close and the next candle’s close (i.e., a local maximum). The Sell Level is drawn at the high of that qualifying candle.
One Signal per Day:
For any given day, the indicator will display either a Buy Level or a Sell Level—not both. The decision is based on which qualifying candle (and its corresponding condition) is found first when scanning the historical data in descending order.
Pullback ReversalPaints a white candle when the probability of entering on a pullback is at its highest level for the stock to move higher
This indicator is more suited to scalp trading bounces but it can also predict a breakout pullback entry for continuation
Order Block Signals//@version=5
indicator("Order Block Signals", overlay=true, max_lines_count=500, max_labels_count=500)
// Inputs
OB_Threshold = input.float(0.001, "OB Threshold (%)", step=0.001) / 100
Lookback = input.int(200, "Lookback Period")
min_diff = input.float(1.0, "Min Candle %", step=0.1)
max_diff = input.float(1.2, "Max Candle %", step=0.1)
tp_percent = input.float(1.3, "Take Profit %", step=0.1) / 100
sl2_percent = input.float(1.3, "Second SL %", step=0.1) / 100
// Order Block Detection
var float highRange = na
var float lowRange = na
highRange := ta.highest(high, Lookback)
lowRange := ta.lowest(low, Lookback)
Buy_OB = low >= lowRange * (1 - OB_Threshold) and low <= lowRange * (1 + OB_Threshold)
Sell_OB = high >= highRange * (1 - OB_Threshold) and high <= highRange * (1 + OB_Threshold)
// Candle Filter
candle_diff = ((high - low) / low) * 100
valid_candle = candle_diff >= min_diff and candle_diff <= max_diff
// Signal Generation
Buy_Signal = Buy_OB and valid_candle
Sell_Signal = Sell_OB and valid_candle
// Remove Excess Signals
var int lastSignal = 0
Buy_Signal := Buy_Signal and lastSignal <= 0
Sell_Signal := Sell_Signal and lastSignal >= 0
if Buy_Signal
lastSignal := 1
else if Sell_Signal
lastSignal := -1
// Price Levels
var float entryPrice = na
var float slPrice = na
var float tpPrice = na
var float sl2Price = na
if Buy_Signal
entryPrice := high
slPrice := low
tpPrice := entryPrice * (1 + tp_percent)
sl2Price := slPrice * (1 - sl2_percent)
else if Sell_Signal
entryPrice := low
slPrice := high
tpPrice := entryPrice * (1 - tp_percent)
sl2Price := slPrice * (1 + sl2_percent)
// Plotting
plot(entryPrice, "Entry", color.new(color.green, 0), 2)
plot(slPrice, "SL", color.new(color.red, 0), 2)
plot(tpPrice, "TP", color.new(color.blue, 0), 2)
plot(sl2Price, "SL2", color.new(color.orange, 0), 2)
// Enhanced Signal Markers
plotshape(Buy_Signal, style=shape.square, location=location.belowbar,
color=color.new(color.green, 0), size=size.tiny, offset=-40)
plotshape(Buy_Signal, style=shape.square, location=location.belowbar,
color=color.new(color.lime, 0), size=size.tiny, offset=-50)
plotshape(Buy_Signal, style=shape.triangleup, location=location.belowbar,
color=color.new(color.white, 0), size=size.small, offset=-45)
plotshape(Sell_Signal, style=shape.square, location=location.abovebar,
color=color.new(color.red, 0), size=size.tiny, offset=40)
plotshape(Sell_Signal, style=shape.square, location=location.abovebar,
color=color.new(color.orange, 0), size=size.tiny, offset=50)
plotshape(Sell_Signal, style=shape.triangledown, location=location.abovebar,
color=color.new(color.white, 0), size=size.small, offset=-45)
// Order Block Zones
bgcolor(Buy_OB ? color.new(color.green, 90) : na)
bgcolor(Sell_OB ? color.new(color.red, 90) : na)
// Dynamic Lines
var line entryLine = na
var line slLine = na
var line tpLine = na
var line sl2Line = na
if Buy_Signal or Sell_Signal
entryLine := line.new(bar_index, entryPrice, bar_index+1, entryPrice,
color=color.green, width=2)
slLine := line.new(bar_index, slPrice, bar_index+1, slPrice,
color=color.red, width=2)
tpLine := line.new(bar_index, tpPrice, bar_index+1, tpPrice,
color=color.blue, width=2)
sl2Line := line.new(bar_index, sl2Price, bar_index+1, sl2Price,
color=color.orange, width=2)
//@version=5
indicator("Order Block Signals - Exclusive & Dynamic", overlay=true, max_lines_count=500)
// Inputs
Lookback = input.int(200, "Lookback Period")
min_diff = input.float(1.0, "Min Candle %", step=0.1)
max_diff = input.float(1.2, "Max Candle %", step=0.1)
tp_percent = input.float(1.3, "Take Profit %", step=0.1) / 100
sl2_percent = input.float(1.3, "Second SL %", step=0.1) / 100
// Order Block Detection
var float highRange = na
var float lowRange = na
highRange := ta.highest(high, Lookback)
lowRange := ta.lowest(low, Lookback)
Buy_OB = low >= lowRange * (1 - OB_Threshold) and low <= lowRange * (1 + OB_Threshold)
Sell_OB = high >= highRange * (1 - OB_Threshold) and high <= highRange * (1 + OB_Threshold)
// Candle Filter
candle_diff = ((high - low) / low) * 100
valid_candle = candle_diff >= min_diff and candle_diff <= max_diff
// Signal Generation with Mutual Exclusivity
var int lastSignal = 0 // -1 = Sell active, 0 = Neutral, 1 = Buy active
var float entryPrice = na
var float slPrice = na
var float tpPrice = na
var float sl2Price = na
Buy_Signal = false
Sell_Signal = false
// Check for new signals
if Buy_OB and valid_candle and lastSignal <= 0
Buy_Signal := true
lastSignal := 1
entryPrice := high
slPrice := low
tpPrice := entryPrice * (1 + tp_percent)
sl2Price := slPrice * (1 - sl2_percent)
else if Sell_OB and valid_candle and lastSignal >= 0
Sell_Signal := true
lastSignal := -1
entryPrice := low
slPrice := high
tpPrice := entryPrice * (1 - tp_percent)
sl2Price := slPrice * (1 + sl2_percent)
// Check for TP/SL hit to reset signals
if lastSignal == 1 and (high >= tpPrice or low <= slPrice)
lastSignal := 0
entryPrice := na
slPrice := na
tpPrice := na
sl2Price := na
else if lastSignal == -1 and (low <= tpPrice or high >= slPrice)
lastSignal := 0
entryPrice := na
slPrice := na
tpPrice := na
sl2Price := na
// Plotting
plot(entryPrice, "Entry", color.new(color.green, 0), 2, linewidth=2)
plot(slPrice, "SL", color.new(color.red, 0), 2, linewidth=2)
plot(tpPrice, "TP", color.new(color.blue, 0), 2, linewidth=2)
plot(sl2Price, "SL2", color.new(color.orange, 0), 2, linewidth=2)
// Signal Markers
plotshape(Buy_Signal, style=shape.triangleup, location=location.belowbar,
color=color.new(color.green, 0), size=size.normal, text="BUY", textcolor=color.white)
plotshape(Sell_Signal, style=shape.triangledown, location=location.abovebar,
color=color.new(color.red, 0), size=size.normal, text="SELL", textcolor=color.white)
// Order Block Zones
bgcolor(Buy_OB ? color.new(color.green, 90) : na, title="Buy OB Zone")
bgcolor(Sell_OB ? color.new(color.red, 90) : na, title="Sell OB Zone")
// Dynamic Lines for TP/SL
var line entryLine = na
var line slLine = na
var line tpLine = na
var line sl2Line = na
if Buy_Signal or Sell_Signal
entryLine := line.new(bar_index, entryPrice, bar_index + 1, entryPrice,
color=color.new(color.green, 0), width=2)
slLine := line.new(bar_index, slPrice, bar_index + 1, slPrice,
color=color.new(color.red, 0), width=2)
tpLine := line.new(bar_index, tpPrice, bar_index + 1, tpPrice,
color=color.new(color.blue, 0), width=2)
sl2Line := line.new(bar_index, sl2Price, bar_index + 1, sl2Price,
color=color.new(color.orange, 0), width=2)
// Clear lines when position is closed
if lastSignal == 0
line.delete(entryLine)
line.delete(slLine)
line.delete(tpLine)
line.delete(sl2Line)