DS Gurukul RoundupRoundup (Support & Resistance Indicator)  For Bank Nifty
By DS Gurukul
To be used only for Bank Nifty.
Indicator Overview
The Round Figure Indicator identifies key psychological support and resistance levels based on round numbers. These levels often act as strong turning points in price action due to trader psychology and institutional order placement.
How It Works
Key Levels:
Mid Band (Black Solid Line): Major round number 
Upper Band (Green Solid Line): Mid Band (resistance)
Lower Band (Red Solid Line): Mid Band (support)
Sub-Bands (Dotted Lines): ±100 levels for tighter zones
Alerts: Triggers when price touches any band, signaling potential reversals or breakouts.
Trading Strategy
✅ Bounce Trades:
Buy near Lower Band or Mid Sub-Lower with bullish confirmation (e.g., hammer candle).
Sell near Upper Band or Mid Sub-Upper with bearish rejection (e.g., shooting star).
✅ Breakout Trades:
Enter long on a close above Upper Band with volume.
Enter short on a close below Lower Band with momentum.
⚠️ Risk Management:
Place stops just beyond the opposite sub-band.
Avoid trading if price is stuck between mid/sub-bands (choppy market).
Why It Works
Round numbers attract limit orders (support/resistance).
Institutions use these levels for stop placements and profit targets.
Works across all timeframes (scalping to swing trading).
🔔 Tip: Combine with RSI/MACD for higher-probability trades!
"order"に関するスクリプトを検索
Kaito  Box with RSI Div(Dynamic Adjustment + MA + Long)The script implements a dynamic trading strategy that combines box range detection, RSI divergence signals, and moving average trend analysis. It is designed for use on OKX Signal Bots and includes features for dynamic position scaling and partial position closing. Below is a summary of its key functionalities:
Key Features:
Box Range Detection:
The script identifies price ranges using the highest high and lowest low of a configurable boxLength period.
These levels are plotted on the chart to visualize the price range.
RSI Divergence Detection:
The script calculates RSI using a configurable rsiLength.
Detects bullish divergence when price makes a lower low, but RSI makes a higher low.
Detects bearish divergence when price makes a higher high, but RSI makes a lower high.
Includes separate left and right lookback periods (leftLookback, rightLookback) for precise local extrema detection.
Customizable Moving Averages:
Supports multiple types of Moving Averages (SMA, EMA, SMMA, WMA, VWMA).
Calculates and plots MA20, MA50, MA100, and MA200 on a user-defined timeframe (custom_timeframe).
Identifies uptrends and downtrends based on the alignment of the moving averages and price levels.
Dynamic Position Scaling:
Implements dynamic position sizing for long entries and partial position closing for exits.
The percentage of position size added or closed is based on the difference between the current price and the average position price (avgPrice), with configurable minimum thresholds (minEnterPercent, minExitPercent).
Signal Integration for OKX Bots:
Sends buy/sell signals to OKX Signal Bots using the configured signalToken.
Supports market or limit orders with configurable price offsets and investment types.
Trend-Based Signal Filtering:
Only triggers long signals during downtrends and short signals during uptrends, ensuring trades align with the overall market context.
Visual Annotations:
Plots bullish and bearish divergence signals on the chart.
Displays labels showing dynamic position size adjustments and current average price during trades.
How It Works:
Long Signals:
Triggered when the price breaches the lower box range, and a bullish RSI divergence is detected.
Additional filtering ensures long trades are executed only during downtrend conditions.
Dynamically adjusts the position size based on the price difference from the average entry price.
Short Signals:
Triggered when the price breaches the upper box range, and a bearish RSI divergence is detected.
Additional filtering ensures short trades are executed only during uptrend conditions.
Dynamically closes portions of the position based on price movement relative to the average entry price.
Alerts:
Generates actionable alerts formatted for OKX bots, including order type, signal token, and dynamically calculated position sizes.
Use Case:
This strategy is well-suited for automated trading on platforms like OKX, where it can:
Exploit price ranges and RSI divergences for precise entries and exits.
Dynamically manage position sizes to optimize risk-reward.
Adapt to different market conditions using configurable parameters like moving averages, divergence lookbacks, and trend filters.
This script provides a robust foundation for traders looking to automate their strategies while maintaining flexibility and control over their trading logic.
Dynamic Liquidity Depth [BigBeluga]
 Dynamic Liquidity Depth    
 A liquidity mapping engine that reveals hidden zones of market vulnerability. This tool simulates where potential large concentrations of stop-losses may exist — above recent highs (sell-side) and below recent lows (buy-side) — by analyzing real price behavior and directional volume. The result is a dynamic two-sided volume profile that highlights where price is most likely to gravitate during liquidation events, reversals, or engineered stop hunts. 
 🔵 KEY FEATURES   
 
   Two-Sided Liquidity Profiles:   
Plots two separate profiles on the chart — one above price for potential  sell-side liquidity , and one below price for potential  buy-side liquidity . Each profile reflects the volume distribution across binned zones derived from historical highs and lows.
  
   Real Stop Zone Simulation:   
Each profile is offset from the current high or low using an ATR-based buffer. This simulates where traders might cluster their stop-losses above swing highs (short stops) or below swing lows (long stops).
  
   Directional Volume Analysis:   
Buy-side volume is accumulated only from bullish candles (close > open), while sell-side volume is accumulated only from bearish candles (close < open). This directional filtering enhances accuracy by capturing genuine pressure zones.
  
  
   Dynamic Volume Heatmap:   
Each liquidity bin is rendered as a horizontal box with a color gradient based on volume intensity:
  - Low activity bins are shaded lightly.
  - High-volume zones appear more vividly in red (sell) or lime (buy).
  - The  maximum volume bin  in each profile is emphasized with a brighter fill and a volume label.
   Extended POC Zones:   
The Point of Control (PoC) — the bin with the most volume — is extended backwards across the entire lookback period to mark critical resistance (sell-side) or support (buy-side) levels.
  
   Total Volume Summary Labels: 
At the center of each profile, a summary label displays  Total Buy Liquidity  and  Total Sell Liquidity  volume.
This metric helps assess directional imbalance — when buy liquidity is dominant, the market may favor upward continuation, and vice versa.
  
   Customizable Profile Granularity:   
You can fine-tune both  Resolution (Bins)  and  Offset Distance  to adjust how far profiles are displaced from price and how many levels are calculated within the ATR range.
 
 🔵 HOW IT WORKS   
 
  The indicator calculates an ATR-based buffer above highs and below lows to define the top and bottom of the liquidity zones.  
  Using a user-defined lookback period, it scans historical candles and divides the buffered zones into bins.  
  Each bin checks if bullish (or bearish) candles pass through it based on price wicks and body.  
  Volume from valid candles is summed into the corresponding bin.  
  When volume exists in a bin, a horizontal box is drawn with a width scaled by relative volume strength.  
  The bin with the highest volume is highlighted and optionally extended backward as a zone of importance.  
  Total buy/sell liquidity is displayed with a summary label at the side of the profile.
 
 🔵 USAGE/b]  
 
   Identify Stop Hunt Zones:  High-volume clusters near swing highs/lows are likely liquidation zones targeted during fakeouts.  
   Fade or Follow Reactions:  Price hitting a high-volume bin may reverse (fade opportunity) or break with strength (confirmation breakout).  
  
   Layer with Other Tools:  Combine with market structure, order blocks, or trend filters to validate entries near liquidity.  
   Adjust Offset for Sensitivity:  Use higher offset to simulate wider stop placement; use lower for tighter scalping zones.
 
 🔵 CONCLUSION   
 Dynamic Liquidity Depth   transforms raw price and volume into a spatial map of liquidity. By revealing areas where stop orders are likely hidden, it gives traders insight into price manipulation zones, potential reversal levels, and breakout traps. Whether you're hunting for traps or trading with the flow, this tool equips you to navigate liquidity with precision.
Time-Based Fair Value Gaps (FVG) with Inversions (iFVG)Overview 
The Time-Based Fair Value Gaps (FVG) with Inversions (iFVG) (ICT/SMT) indicator is a specialized tool designed for traders using Inner Circle Trader (ICT) methodologies. Inspired by LuxAlgo's Fair Value Gap indicator, this script introduces significant enhancements by integrating ICT principles, focusing on precise time-based FVG detection, inversion tracking, and retest signals tailored for institutional trading strategies. Unlike LuxAlgo’s general FVG approach, this indicator filters FVGs within customizable 10-minute windows aligned with ICT’s macro timeframes and incorporates ICT-specific concepts like mitigation, liquidity grabs, and session-based gap prioritization.
This tool is optimized for 1–5 minute charts, though probably best for 1 minute charts, identifying bullish and bearish FVGs, tracking their mitigation into inverted FVGs (iFVGs) as key support/resistance zones, and generating retest signals with customizable “Close” or “Wick” confirmation. Features like ATR-based filtering, optional FVG labels, mitigation removal, and session-specific FVG detection (e.g., first FVG in AM/PM sessions) make it a powerful tool for ICT traders.
 Originality and Improvements 
While inspired by LuxAlgo’s FVG indicator (credit to LuxAlgo for their foundational work), this script significantly extends the original concept by:
1.	 Time-Based FVG Detection:  Unlike LuxAlgo’s continuous FVG identification, this script filters FVGs within user-defined 10-minute windows each hour (:00–:10, :10–:20, etc.), aligning with ICT’s emphasis on specific periods of institutional activity, such as hourly opens/closes or kill zones (e.g., New York 7:00–11:00 AM EST). This ensures FVGs are relevant to high-probability ICT setups.
2.	 Session-Specific First FVG Option:  A unique feature allows traders to display only the first FVG in ICT-defined AM (9:30–10:00 AM EST) or PM (1:30–2:00 PM EST) sessions, reflecting ICT’s focus on initial market imbalances during key liquidity events.
3.	 ICT-Driven Mitigation and Inversion Logic:  The script tracks FVG mitigation (when price closes through a gap) and converts mitigated FVGs into iFVGs, which serve as ICT-style support/resistance zones. This aligns with ICT’s view that mitigated gaps become critical reversal points, unlike LuxAlgo’s simpler gap display.
4.	 Customizable Retest Signals:  Retest signals for iFVGs are configurable for “Close” (conservative, requiring candle body confirmation) or “Wick” (faster, using highs/lows), catering to ICT traders’ need for precise entry timing during liquidity grabs or Judas swings.
5.	 ATR Filtering and Mitigation Removal:  An optional ATR filter ensures only significant FVGs are displayed, reducing noise, while mitigation removal declutters the chart by removing filled gaps, aligning with ICT’s principle that mitigated gaps lose relevance unless inverted.
6.	 Timezone and Timeframe Safeguards:  A timezone offset setting aligns FVG detection with EST for ICT’s New York-centric strategies, and a timeframe warning alerts users to avoid ≥1-hour charts, ensuring accuracy in time-based filtering.
These enhancements make the script a distinct tool that builds on LuxAlgo’s foundation while offering ICT traders a tailored, high-precision solution.
 How It Works 
 FVG Detection 
FVGs are identified when a candle’s low is higher than the high of two candles prior (bullish FVG) or a candle’s high is lower than the low of two candles prior (bearish FVG). Detection is restricted to:
•	 User-selected 10-minute windows  (e.g., :00–:10, :50–:60) to capture ICT-relevant periods like hourly transitions.
•	 AM/PM session first FVGs  (if enabled), focusing on 9:30–10:00 AM or 1:30–2:00 PM EST for key market opens.
An optional ATR filter (default: 0.25× ATR) ensures only gaps larger than the threshold are displayed, prioritizing significant imbalances.
 Mitigation and Inversion
 
When price closes through an FVG (e.g., below a bullish FVG’s bottom), the FVG is mitigated and becomes an iFVG, plotted as a support/resistance zone. iFVGs are critical in ICT for identifying reversal points where institutional orders accumulate.
 Retest Signals
 The script generates signals when price retests an iFVG:
•	 Close:  Triggers when the candle body confirms the retest (conservative, lower noise).
•	 Wick:  Triggers when the candle’s high/low touches the iFVG (faster, higher sensitivity). Signals are visualized with triangular markers (▲ for bullish, ▼ for bearish) and can trigger alerts.
 Visualization 
•	 FVGs:  Displayed as colored boxes (green for bullish, red for bearish) with optional “Bull FVG”/“Bear FVG” labels.
•	 iFVGs:  Shown as extended boxes with dashed midlines, limited to the user-defined number of recent zones (default: 5).
•	Mitigation Removal: Mitigated FVGs/iFVGs are removed (if enabled) to keep the chart clean.
 How to Use 
 Recommended Settings 
•	 Timeframe:  Use 1–5 minute charts for precision, avoiding ≥1-hour timeframes (a warning label appears if misconfigured).
•	 Time Windows:  Enable :00–:10 and :50–:60 for hourly open/close FVGs, or use the “Show only 1st presented FVG” option for AM/PM session focus.
•	 ATR Filter:  Keep enabled (multiplier 0.25–0.5) for significant gaps; disable on 1-minute charts for more FVGs during volatility.
•	 Signal Preference:  Use “Close” for conservative entries, “Wick” for aggressive setups.
•	 Timezone Offset:  Set to -5 for EST (or -4 for EDT) to align with ICT’s New York session.
 Trading Strategy 
1.	 Macro Timeframes:  Focus on New York (7:00–11:00 AM EST) or London (2:00–5:00 AM EST) kill zones for high institutional activity.
2.	 FVG Entries:  Trade bullish FVGs as support in uptrends or bearish FVGs as resistance in downtrends, especially in :00–:10 or :50–:60 windows.
3.	 iFVG Retests:  Enter on retest signals (▲/▼) during liquidity grabs or Judas swings, using “Close” for confirmation or “Wick” for speed.
4.	 Session FVGs:  Use the “Show only 1st presented FVG” option to target the first gap in AM/PM sessions, often tied to ICT’s market maker algorithms.
5.	 Risk Management:  Combine with ICT concepts like order blocks or breaker blocks for confluence, and set stops beyond FVG/iFVG boundaries.
 Alerts
 
 Set alerts for: 
•	 “Bullish FVG Detected”/“Bearish FVG Detected”:  New FVGs in selected windows.
•	 “Bullish Signal”/“Bearish Signal”:  iFVG retest confirmations.
Settings Description
•	 Show Last (1–100, default: 5):  Number of recent iFVGs to display. Lower values reduce clutter.
•	 Show only 1st presented FVG : Limits FVGs to the first in 9:30–10:00 AM or 1:30–2:00 PM EST sessions (overrides time window checkboxes).
•	 Time Window Checkboxes:  Enable/disable FVG detection in 10-minute windows (:00–:10, :10–:20, etc.). All enabled by default.
•	 Signal Preference:  “Close” (default) or “Wick” for iFVG retest signals.
•	 Use ATR Filter:  Enables ATR-based size filtering (default: true).
•	 ATR Multiplier (0–∞, default: 0.25):  Sets FVG size threshold (higher values = larger gaps).
•	 Remove Mitigated FVGs:  Removes filled FVGs/iFVGs (default: true).
•	 Show FVG Labels:  Displays “Bull FVG”/“Bear FVG” labels (default: true).
•	 Timezone Offset (-12 to 12, default: -5):  Aligns time windows with EST.
•	 Colors:  Customize bullish (green), bearish (red), and midline (gray) colors.
 Why Use This Indicator?
 This indicator empowers ICT traders with a tool that goes beyond generic FVG detection, offering precise, time-filtered gaps and inversion tracking aligned with institutional trading principles. By focusing on ICT’s macro timeframes, session-specific imbalances, and customizable signal logic, it provides a clear edge for scalping, swing trading, or reversal setups in high-liquidity markets.
Entropy [ScorsoneEnterprises]This indicator calculates the entropy of price log returns over a user-defined lookback period, providing insights into market complexity and unpredictability. Entropy measures the randomness or disorder in price movements, helping traders identify periods of high or low market uncertainty.
How It Works
The indicator computes the entropy of log returns (log(close/close )) using a histogram-based approach with customizable bins. Log returns are stored in an array of size N (lookback period), and entropy is calculated by:
Binning the returns into bins intervals based on their range.
Computing the probability distribution across bins.
Calculating entropy as -Σ(p * log(p)), where p is the probability of each bin.
A reference Simple Moving Average (SMA) of the entropy, with a separate lookback period (SMA_N), is plotted to highlight trends in market complexity. The entropy plot uses a gradient color scheme (red for lower entropy, teal for higher), while the SMA color shifts based on whether entropy is above (teal) or below (red) the SMA.
Key Features
Inputs:
Lookback Period (default: 50): Number of bars for calculating log returns.
Reference SMA Lookback Period (default: 100): Period for the entropy SMA.
Number of Bins (default: 20): Number of histogram bins for entropy calculation.
Plots:
Entropy: Gradient-colored line reflecting market randomness.
Reference SMA: Trend line to compare entropy against its average.
Interpretation
High Entropy: Indicates chaotic, unpredictable price movements, often during volatile or trendless markets.
Low Entropy: Suggests more predictable, ordered price behavior, often in trending or stable markets.
Compare entropy to its SMA to gauge whether current market complexity is above or below its recent average.
Usage 
Use this indicator to assess market regimes. High entropy may signal choppy, range-bound conditions, while low entropy could indicate trending opportunities. Combine with price action or other indicators for confirmation.
Examples
  
 
We see on this  PEPPERSTONE:COCOA  chart that when entropy is low it signals a strong trend, either up or down. High entropy signals indecision and choppiness in the market. We can determine this by noticing when the value is above or below its recent average. 
  
 
Entropy is used in high frequency trading often. It is a nice tool for lower time frames to determine how predictable and strong a trend is. 
Inputs
Users can enter the lookback value for entropy, bin count, and the look back for the entropy moving average.
No tool is perfect, the Entropy value is also not perfect and should not be followed blindly. It is good to use any tool along with discretion and price action. 
Amihud Liquidity RatioCalculates liquidity as a sort of moving average over time
The Amihud Illiquidity Ratio (ILLIQ) measures the price impact of trading volume. It's calculated as the absolute daily return divided by the daily dollar volume:
𝐼𝐿𝐿𝐼𝑄ₜ = |𝑅ₜ| / 𝑉𝑂𝐿𝐷ₜ
Where:
|𝑅ₜ| is the absolute value on return day t
𝑉𝑂𝐿𝐷ₜ is the dollar trading volume on day t
Here's how you can incorporate this indicator into your analysis:
1. Identifying Liquidity Regimes:
High Liquidity (Low Indicator Values): When the indicator is consistently low, it suggests a market or asset where it's generally easier to enter and exit positions without significant slippage. This might be a more favorable environment for strategies that rely on tight spreads and efficient order execution.
Low Liquidity (High Indicator Values): When the indicator is consistently high or spiking, it signals periods of lower liquidity. This can lead to:
Increased Volatility: Fewer participants and larger bid-ask spreads can amplify price movements.
Higher Slippage: Executing large orders might result in getting a worse price than expected.
Gap Risk: Significant price gaps can occur between trading sessions due to a lack of continuous trading interest.
---------------------------------------------------------------------------------------------------------------------
2. Confirming Trends and Breakouts:
Trend Confirmation:
Uptrend with Increasing Liquidity (Falling Amihud): A healthy uptrend often sees increasing participation and ease of trading. A falling Amihud during an uptrend can provide confidence in the trend's sustainability.
Uptrend with Decreasing Liquidity (Rising Amihud): An uptrend accompanied by rising Amihud might be less stable. It could suggest that the price increase is driven by fewer participants and might be more prone to reversals.
The same logic applies to downtrends, but in reverse.
---------------------------------------------------------------------------------------------------------------------
Breakout Confirmation:
Breakout with Increasing Liquidity (Falling Amihud): A breakout accompanied by increasing liquidity (falling Amihud) can suggest strong conviction and a higher probability of the breakout being sustained.
Breakout with Decreasing Liquidity (Rising Amihud): A breakout on low liquidity might be more suspect and could be a "fakeout" if there isn't enough sustained buying or selling pressure.
---------------------------------------------------------------------------------------------------------------------
3. Identifying Potential Reversal Points:
Liquidity Exhaustion: Sometimes, a prolonged period of low liquidity (high Amihud) might precede a reversal. The lack of active trading interest at those levels could make the price more susceptible to a shift in sentiment.
Liquidity Surges: A sudden spike in liquidity (a sharp drop in Amihud) after a period of low liquidity could indicate renewed interest and potentially the start of a new trend or a reversal of the previous one.
-----------------------------------------------THANK YOU----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<3-----------------------------------------------
ICT Turtle Soup (Liquidity Reversal)ICT Turtle Soup — Liquidity Reversal Detection
Classic Liquidity Trap Reversal Strategy for Smart Money Traders
This indicator implements the ICT Turtle Soup concept — a classic liquidity-based reversal pattern — which occurs when price runs above or below a recent swing level to grab liquidity, then sharply reverses. This pattern is commonly used in Smart Money Concepts (SMC) and Inner Circle Trader (ICT) strategies to anticipate false breakouts and high-probability reversals.
🔍 What This Script Does:
Identifies Swing Highs & Lows
Detects recent swing highs and lows using a customizable lookback period.
Tracks Liquidity Grabs
A bearish Turtle Soup setup is triggered when price breaks above a recent swing high but closes back below it.
A bullish Turtle Soup setup is triggered when price breaks below a recent swing low but closes back above it.
These conditions often signal liquidity traps, where price sweeps resting orders before reversing.
Plots Signals Directly on the Chart
Turtle Soup setups are marked with 🐢🔻 (bearish) and 🐢🔺 (bullish) labels.
Optional full-text labels can also be displayed for clarity and journaling.
Includes Alert Conditions
Alerts can be enabled to notify you of bullish or bearish Turtle Soup reversals in real-time.
⚙️ Customization Features:
Adjustable swing lookback period
Enable/disable Turtle Soup labels
Set label font size
Choose your preferred bullish/bearish signal colors
💡 How to Use:
Add this script to your chart (ideally on intraday timeframes such as 5m–15m).
Wait for a Turtle Soup signal near a key swing high/low or liquidity zone.
Combine with other confirmation tools (e.g., FVGs, Order Blocks, OTE) for stronger setups.
Use alerts to stay ahead of fast-moving reversals.
🧠 Why It Works:
Turtle Soup setups are rooted in liquidity theory — they exploit the market’s tendency to sweep obvious swing levels before reversing. These moves often trap retail traders and mark the beginning of Smart Money entries.
🔗 Best Used With:
Maximize the edge by combining this with other SMC tools:
✅ First FVG — Opening Range Fair Value Gap Detector
✅ ICT SMC Liquidity Grabs + OB + Fibonacci OTE Levels
✅ Liquidity Levels — Smart Swing Lows
Together, they create a complete ecosystem for identifying, confirming, and executing liquidity-driven trade setups with precision.
[TehThomas] - ICT Inversion Fair value Gap (IFVG) The Inversion Fair Value Gap (IFVG) indicator is a powerful tool designed for traders who utilize ICT (Inner Circle Trader) strategies. It focuses on identifying and displaying Inversion Fair Value Gaps, which are critical zones that emerge when traditional Fair Value Gaps (FVGs) are invalidated by price action. These gaps represent key areas where price often reacts, making them essential for identifying potential reversals, trend continuations, and liquidity zones.
 What Are Inversion Fair Value Gaps? 
Inversion Fair Value Gaps occur when price revisits a traditional FVG and breaks through it, effectively flipping its role in the market. For example:
 
 A bullish FVG that is invalidated becomes a bearish zone, often acting as resistance.
 A bearish FVG that is invalidated transforms into a bullish zone, serving as support.
 
These gaps are significant because they often align with institutional trading activity. They highlight areas where large orders have been executed or where liquidity has been targeted. Understanding these gaps provides traders with a deeper insight into market structure and helps them anticipate future price movements with greater accuracy.
 Why This Strategy Works 
The IFVG concept is rooted in ICT principles, which emphasize liquidity dynamics, market inefficiencies, and institutional order flow. Traditional FVGs represent imbalances in price action caused by gaps between candles. When these gaps are invalidated, they become inversion zones that can act as magnets for price. These zones frequently serve as high-probability areas for price reversals or trend continuations.
This strategy works because it aligns with how institutional traders operate. Inversion gaps often mark areas of interest for "smart money," making them reliable indicators of potential market turning points. By focusing on these zones, traders can align their strategies with institutional behavior and improve their overall trading edge.
 How the Indicator Works 
This indicator simplifies the process of identifying and tracking IFVGs by automating their detection and visualization on the chart. It scans the chart in real-time to identify bullish and bearish FVGs that meet user-defined thresholds for inversion. Once identified, these gaps are dynamically displayed on the chart with distinct colors for bullish and bearish zones.
The indicator also tracks whether these gaps are mitigated or broken by price action. When an IFVG is broken, it extends the zone for a user-defined number of bars to visualize its potential role as a new support or resistance level. Additionally, alerts can be enabled to notify traders when new IFVGs form or when existing ones are broken, ensuring timely decision-making in fast-moving markets.
 Key Features 
 
 Automatic Detection: The indicator automatically identifies bullish and bearish IFVGs based on user-defined thresholds.
 Dynamic Visualization: It displays IFVGs directly on the chart with customizable colors for easy differentiation.
 Real-Time Updates: The status of each IFVG is updated dynamically based on price action.
 Zone Extensions: Broken IFVGs are extended to visualize their potential as support or resistance levels.
 Alerts: Notifications can be set up to alert traders when key events occur, such as the formation or breaking of an IFVG.
 
These features make the tool highly efficient and reduce the need for manual analysis, allowing traders to focus on execution rather than tedious chart work.
 Benefits of Using This Indicator 
The IFVG indicator offers several advantages that make it an indispensable tool for ICT traders. By automating the detection of inversion gaps, it saves time and reduces errors in analysis. The clearly defined zones improve risk management by providing precise entry points, stop-loss levels, and profit targets based on market structure.
This tool is also highly versatile and adapts seamlessly across different timeframes. Whether you’re scalping lower timeframes or swing trading higher ones, it provides actionable insights tailored to your trading style. Furthermore, by aligning your strategy with institutional logic, you gain a significant edge in anticipating market movements.
 Practical Applications 
 
 This indicator can be used across various trading styles:
 Scalping: Identify quick reversal points on lower timeframes using real-time alerts.
 Day Trading: Use inversion gaps as key levels for intraday support/resistance or trend continuation setups.
 Swing Trading: Analyse higher timeframes to identify major inversion zones that could act as critical turning points in larger trends.
 
By integrating this tool into your trading routine, you can streamline your analysis process and focus on executing high-probability setups.
 Conclusion 
The Inversion Fair Value Gap (IFVG) indicator is more than just a technical analysis tool—it’s a strategic ally for traders looking to refine their edge in the markets. By automating the detection and tracking of inversion gaps based on ICT principles, it simplifies complex market analysis while maintaining accuracy and depth. Whether you’re new to ICT strategies or an experienced trader seeking greater precision, this indicator will elevate your trading game by aligning your approach with institutional behavior.
If you’re serious about improving your trading results while saving time and effort, this tool is an essential addition to your toolkit. It provides clarity in chaotic markets, enhances precision in trade execution, and ensures you never miss critical opportunities in your trading journey.
 __________________________________________ 
 Thanks for your support! 
If you found this idea helpful or learned something new, drop a like 👍 and leave a comment, I’d love to hear your thoughts! 🚀
Make sure to follow me for more price action insights, free indicators, and trading strategies. Let’s grow and trade smarter together! 📈
Cartera SuperTrends v4 PublicDescription
This script creates a screener with a list of ETFs ordered by their average ROC in three different periods representing 4, 6 and 8 months by default. The ETF 
BIL
 is always included as a reference.
The previous average ROC value shows the calculation using the closing price from last month.
The current average ROC value shows the calculation using the current price.
The previous average column background color represents if the ETF average ROC is positive or negative.
The current average column background color represents if the ETF average ROC is positive or negative.
The current average column letters color represents if the current ETF average ROC is improving or not from the previous month.
Changes from V2 to V3
Added the option to make the calculation monthly, weekly or daily
Changes from V3 to V4
Adding up to 25 symbols
Highlight the number of tickers selected
Highlight the sorted column
Complete refactor of the code using a matrix of arrays
Options
The options available are:
Make the calculation monthly, weekly or daily
Adjust Data for Dividends
Manual calculation instead of using ta.roc function
Sort table
Sort table by the previous average ROC or the current average ROC
Number of tickers selected to highlight
First Period in months, weeks or days
Second Period in months, weeks or days
Third Period in months, weeks or days
Select the assets (max 25)
Usage
Just add the indicator to your favorite indicators and then add it to your chart.
Arbitrage Spot-Futures Don++Strategy: Spot-Futures Arbitrage Don++ 
This strategy has been designed to  detect and exploit arbitrage opportunities between the Spot and Futures markets  of the same trading pair (e.g. BTC/USDT). The aim is to take advantage of price differences (spreads) between the two markets, while minimizing risk through dynamic position management.
 [Operating principle 
The strategy is based on calculating the  spread  between Spot and Futures prices. When this spread exceeds a certain threshold (positive or negative), reverse positions are opened simultaneously on both markets:
- i] Long Spot + Short Futures  when the spread is positive.
- i] Short Spot + Long Futures  when the spread is negative.
Positions are closed when the spread returns to a value close to zero or after a user-defined maximum duration.
 [Strategy strengths 
1.  Adaptive thresholds  :
   - Entry/exit thresholds can be dynamic (based on moving averages and standard deviations) or fixed, offering greater flexibility to adapt to market conditions.
2.  Robust data management :
   - The script checks the validity of data before executing calculations, thus avoiding errors linked to missing or invalid data.
3.  Risk limitation  :
   - A position size based on a percentage of available capital (default 10%) limits exposure.
   - A time filter limits the maximum duration of positions to avoid losses due to persistent spreads.
4.  Clear visualization :
   - Charts include horizontal lines for entry/exit thresholds, as well as visual indicators for spread and Spot/Futures prices.
5.  Alerts and logs :
   - Alerts are triggered on entries and exits to inform the user in real time.
 [Points for improvement or completion 
Although this strategy is functional and robust, it still has a few limitations that could be addressed in future versions:
1.  [Limited historical data  :
   - TradingView does not retrieve real-time data for multiple symbols simultaneously. This can limit the accuracy of calculations, especially under conditions of high volatility.
2.  [Lack of liquidity management :
   - The script does not take into account the volumes available on the order books. In conditions of low liquidity, it may be difficult to execute orders at the desired prices.
3.  [Non-dynamic transaction costs  :
   - Transaction costs (exchange fees, slippage) are set manually. A dynamic integration of these costs via an external API would be more realistic.
4.  User-dependency for symbols :
   - Users must manually specify Spot and Futures symbols. Automatic symbol validation would be useful to avoid configuration errors.
5.  Lack of advanced backtesting :
   - Backtesting is based solely on historical data available on TradingView. An implementation with third-party data (via an API) would enable the strategy to be tested under more realistic conditions.
6.  [Parameter optimization  :
   - Certain parameters (such as analysis period or spread thresholds) could be optimized for each specific trading pair.
 [How can I contribute?
If you'd like to help improve this strategy, here are a few ideas:
 1. Add additional filters: 
   - For example, a filter based on volume or volatility to avoid false signals.
 2. Integrate dynamic costs: 
   - Use an external API to retrieve actual costs and adjust thresholds accordingly.
 3. Improve position management: 
   - Implement hedging or scalping mechanisms to maximize profits.
 4. Test on other pairs: 
   - Evaluate the strategy's performance on other assets (ETH, SOL, etc.) and adjust parameters accordingly.
 5. Publish backtesting results :
   - Share detailed analyses of the strategy's performance under different market conditions.
 [Conclusion 
This Spot-Futures arbitrage strategy is a powerful tool for exploiting price differentials between markets. Although it is already functional, it can still be improved to meet more complex trading scenarios. Feel free to test, modify and share your ideas to make this strategy even more effective!
 [Thank you for contributing to this open-source community!  
If you have any questions or suggestions, please feel free to comment or contact me directly.
Nirmal Fair Value GapsICT Fair Value Gaps
Trade Wisely 
How a Fair Value Gap Works
Formation:
A Fair Value Gap occurs when a strong price movement (usually from institutional orders) creates an imbalance between buyers and sellers.
This is typically seen in a three-candle pattern, where the middle candle has a large body, and the two surrounding candles have wicks but little overlap with the middle candle’s range.
Identification:
The FVG is marked between the high of the first candle and the low of the third candle (for bullish gaps).
For bearish gaps, it’s the low of the first candle and the high of the third candle.
Market Behavior Around FVG:
Price often retraces into the gap before resuming its original direction.
This happens because the market seeks to "fill" the imbalance where few trades occurred.
Traders use FVGs as potential entry zones for trend continuation trades.
Trading Fair Value Gaps
In an Uptrend:
Look for bullish fair value gaps as potential support zones for buy entries.
Price may dip into the gap and then continue upward.
In a Downtrend:
Look for bearish fair value gaps as potential resistance zones for sell entries.
Price may retrace into the gap and then drop further.
Confluence Factors:
FVGs work best when combined with other strategies like order blocks, liquidity zones, or key Fibonacci levels.
capital_managementLibrary   "capital_management" 
TODO: add library description here
 Volume_calculation(precent_risk, order_entry_price, stop_loss_price) 
  TODO: Volume calculation function by placing orders with fiven % risk
  Parameters:
     precent_risk (float) 
     order_entry_price (float) 
     stop_loss_price (float) 
  Returns: stop_loss_price: Price that place stop loss order
Arpeet MACDOverview
This strategy is based on the zero-lag version of the MACD (Moving Average Convergence Divergence) indicator, which captures short-term trends by quickly responding to price changes, enabling high-frequency trading. The strategy uses two moving averages with different periods (fast and slow lines) to construct the MACD indicator and introduces a zero-lag algorithm to eliminate the delay between the indicator and the price, improving the timeliness of signals. Additionally, the crossover of the signal line and the MACD line is used as buy and sell signals, and alerts are set up to help traders seize trading opportunities in a timely manner.
Strategy Principle
Calculate the EMA (Exponential Moving Average) or SMA (Simple Moving Average) of the fast line (default 12 periods) and slow line (default 26 periods).
Use the zero-lag algorithm to double-smooth the fast and slow lines, eliminating the delay between the indicator and the price.
The MACD line is formed by the difference between the zero-lag fast line and the zero-lag slow line.
The signal line is formed by the EMA (default 9 periods) or SMA of the MACD line.
The MACD histogram is formed by the difference between the MACD line and the signal line, with blue representing positive values and red representing negative values.
When the MACD line crosses the signal line from below and the crossover point is below the zero axis, a buy signal (blue dot) is generated.
When the MACD line crosses the signal line from above and the crossover point is above the zero axis, a sell signal (red dot) is generated.
The strategy automatically places orders based on the buy and sell signals and triggers corresponding alerts.
Advantage Analysis
The zero-lag algorithm effectively eliminates the delay between the indicator and the price, improving the timeliness and accuracy of signals.
The design of dual moving averages can better capture market trends and adapt to different market environments.
The MACD histogram intuitively reflects the comparison of bullish and bearish forces, assisting in trading decisions.
The automatic order placement and alert functions make it convenient for traders to seize trading opportunities in a timely manner, improving trading efficiency.
Risk Analysis
In volatile markets, frequent crossover signals may lead to overtrading and losses.
Improper parameter settings may cause signal distortion and affect strategy performance.
The strategy relies on historical data for calculations and has poor adaptability to sudden events and black swan events.
Optimization Direction
Introduce trend confirmation indicators, such as ADX, to filter out false signals in volatile markets.
Optimize parameters to find the best combination of fast and slow line periods and signal line periods, improving strategy stability.
Combine other technical indicators or fundamental factors to construct a multi-factor model, improving risk-adjusted returns of the strategy.
Introduce stop-loss and take-profit mechanisms to control single-trade risk.
Summary
The MACD Dual Crossover Zero Lag Trading Strategy achieves high-frequency trading by quickly responding to price changes and capturing short-term trends. The zero-lag algorithm and dual moving average design improve the timeliness and accuracy of signals. The strategy has certain advantages, such as intuitive signals and convenient operation, but also faces risks such as overtrading and parameter sensitivity. In the future, the strategy can be optimized by introducing trend confirmation indicators, parameter optimization, multi-factor models, etc., to improve the robustness and profitability of the strategy.
Finite Difference - Backward (mcbw_)In calculus there exists a 'derivative', which simply just measures the difference between two points on a curve.  For well behaved mathematical functions there are infinitely many points and so there exists a derivative at every point. Where there are infinitely many points in a curve that curve is called 'continuous'. Continuous curves are very nice to deal with since each point on it exists almost exactly where its neighbors are. However, if the curve does not have infinitely many points on it, but instead has a finite number of points on it, that curve is called 'discrete' instead of continuous. Taking the derivative of discrete curves is much trickier business since there are none of the mathematical conveniences that a continuous offers. In the real world everything we measure is a discrete curve, including Price (since we measure it a finite number of times, aka each candlestick)!
The branch of Discrete Mathematics has found an approach to measure the derivative along a discrete curve, that approach is aptly called " Finite Difference ". To get a more accurate approximation of a discrete derivative, the finite difference approach uses weighted combinations of neighboring points. The most common type of finite difference is a 'central' difference, this uses a combination of points before and after the point of interest to approximate the discrete derivative. This is great for historical analysis but is not of much use for trading algorithms since it technically means using future prices to calculate the derivative of the current point. Instead we can use a less common variant called a ' Backwards Difference ' that only uses a combination of points before the current one to help approximate the current derivative. 
In this script you can choose the " Order " of your derivative and the " Accuracy " of its approximation. This script is for educational purposes for folks building trading algorithms. Many trading algorithms often have an element of seeing how much Price has changed from the previous candle to the current candle. This approach is the lowest accuracy derivative possible, and using the backwards finite differences, made available for the first time on TradingView (!!), algorithms that use derivatives can now have higher orders of accuracy! 
Happy Trading/Developing! 
John Bob-Trading-BotDeveloped by Ayebale John Bob with the help of his bestie, this innovative strategy combines advanced Smart Money Concepts with practical risk management tools to help traders identify and capitalize on key market moves.
Key Features:
 
 Smart Money Concepts & Fair Value Gaps (FVG):
 The strategy monitors price action for fair value gaps, which are visualized as extremely faint horizontal lines on the chart. These FVGs signal potential areas where institutional traders might have entered or exited positions.
 
 Dynamic Entry Signals:
 Buy signals are triggered when the price crosses above the 50-bar lowest low or when a bullish FVG is detected. Conversely, sell signals are generated when the price falls below the 50-bar highest high or a bearish FVG is identified. Each signal is visually marked on the chart with clear buy (green) and sell (red) labels.
 
 Multi-Level Order Execution:
 Once an entry signal occurs, the strategy places five separate orders, each with its own take-profit (TP) level. The TP levels are calculated dynamically using the Average True Range (ATR) and a set of predefined multipliers. This allows traders to scale out of positions as the market moves favorably.
 Dynamic Risk Management:
 A stop-loss is automatically set at a distance determined by the ATR, ensuring that risk is managed in accordance with current market volatility.
 
 Real-Time Trade Information Table:
 In the bottom-right corner of the chart, a trade information table displays essential details about the current trade:
 Side: Displays "BUY NOW" (with a dark green background) for long entries or "SELL NOW" (with a dark red background) for short entries.
 Entry Price & Stop-Loss: Shows the entry price (highlighted in green) and the corresponding stop-loss level (highlighted in red).
 Take-Profit Levels: Lists the five TP levels, each of which turns green once the market price reaches that target.
 Timer: A live timer in minutes counts from the moment the current trade trigger started, helping traders track the duration of their active trades.
 Visual Progress Bar:
 A histogram-style progress bar is plotted on the chart, visually representing the percentage gain (or loss) relative to the entry price.
 
This strategy was meticulously designed to incorporate both technical analysis and smart risk management, offering a robust trading solution that adapts to changing market conditions. Whether you're a seasoned trader or just starting out, the AyebaleJohnBob Trading Bot equips you with the tools and visual cues needed to make well-informed trading decisions. Enjoy a seamless blend of strategy and style—crafted with passion by Ayebale John Bob and his bestie!
SPY/TLT Strategy█ STRATEGY OVERVIEW  
The "SPY/TLT Strategy" is a trend-following crossover strategy designed to trade the relationship between TLT and its Simple Moving Average (SMA). The default configuration uses TLT (iShares 20+ Year Treasury Bond ETF) with a 20-period SMA, entering long positions on bullish crossovers and exiting on bearish crossunders. **This strategy is NOT optimized and performs best in trending markets.**
█ KEY FEATURES  
   
  SMA Crossover System: Uses price/SMA relationship for signal generation (Default: 20-period)  
  Dynamic Time Window: Configurable backtesting period (Default: 2014-2099)  
  Equity-Based Position Sizing: Default 100% equity allocation per trade  
  Real-Time Visual Feedback: Price/SMA plot with trend-state background coloring  
  Event-Driven Execution: Processes orders at bar close for accurate backtesting  
   
█ SIGNAL GENERATION  
1. LONG ENTRY CONDITION  
   
  TLT closing price crosses ABOVE SMA  
  Occurs within specified time window  
  Generates market order at next bar open
   
2. EXIT CONDITION  
   
  TLT closing price crosses BELOW SMA  
  Closes all open positions immediately
   
█ ADDITIONAL SETTINGS  
   
  SMA Period: Simple Moving Average length (Default: 20)  
  Start Time and End Time: The time window for trade execution (Default: 1 Jan 2014 - 1 Jan 2099)  
  Security Symbol: Ticker for analysis (Default: TLT)  
   
█ PERFORMANCE OVERVIEW  
   
  Ideal Market Conditions: Strong trending environments  
  Potential Drawbacks: Whipsaws in range-bound markets  
  Backtesting results should be analyzed to optimize the MA Period and EMA Filter settings for specific instruments
   
Thin Liquidity Zones [PhenLabs]Thin Liquidity Zones with Volume Delta 
Our advanced volume analysis tool identifies and visualizes significant liquidity zones using real-time volume delta analysis. This indicator helps traders pinpoint and monitor critical price levels where substantial trading activity occurs, providing precise volume flow measurement through lower timeframe analysis.
The tool works by leveraging the fact that hedge funds, institutions, and other large market participants strategically fill their orders in areas of thin liquidity to minimize slippage and market impact. By detecting these zones, traders gain valuable insights into potential areas of accumulation, distribution, and liquidity traps, allowing for more informed trading decisions.
 🔍 Key Features 
 
 Real-time volume delta calculation using lower timeframe data
 Dynamic zone creation based on volume spikes
 Automatic timeframe optimization
 Size-filtered zones to avoid noise
 Custom delta timeframe scanning
 Flexible analysis period selection
 
 📊 Visual Demonstration 
 💡 How It Works 
The indicator continuously scans for high-volume areas where trading activity exceeds the specified threshold (default 6.0x average volume). When detected, it creates zones that display the net volume delta, showing whether buying or selling pressure dominated that price level.
Key zone characteristics:
 
 Size filtering prevents noise from large price swings
 Volume delta shows actual buying/selling pressure
 Zones automatically expire based on lookback period
 Real-time updates as new volume data arrives
 
 ⚙️ Settings 
 Time Settings 
 
 Analysis Timeframe: 15M to 1W options
 Custom Period: User-defined bar count
 Delta Timeframe: Automatic or manual selection
 
 Volume Analysis 
 
 Volume Threshold: Minimum spike multiple
 Volume MA Length: Averaging period
 Maximum Zone Size: Size filter percentage
 
 Display Options 
 
 Zone Color: Customizable with transparency
 Delta Display: On/Off toggle
 Text Position: Left/Center/Right alignment
 
 📌 Tips for Best Results 
 
 Adjust volume threshold based on instrument volatility
 Monitor zone clusters for potential support/resistance
 Consider reducing max zone size in volatile markets
 Use in conjunction with price action and other indicators
 
 ⚠️ Important Notes 
 
 Requires volume data from your data provider
 Lower timeframe scanning may impact performance
 Maximum 500 zones maintained for optimization
 Zone creation is filtered by both volume and size
 
 🔧 Volume Delta Calculation 
The indicator uses TradingView’s advanced volume delta calculation, which:
 
 Scans lower timeframe data for precision
 Measures actual buying vs selling pressure
 Updates in real-time with new data
 Provides clear positive/negative flow indication
 
This tool is ideal for traders focusing on volume analysis and order flow. It helps identify key levels where significant trading activity has occurred and provides insight into the nature of that activity through volume delta analysis.
 Note:  Performance may vary based on your chart’s timeframe. Adjust settings according to your trading style and the instrument’s characteristics.  Past performance is not indicative of future results, DYOR.
metaconnectorLibrary   "metaconnector" 
metaconnector
 buy_market_order(License_ID, symbol, lot) 
  Places a buy market order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
  Returns: String syntax for the buy market order
 sell_market_order(License_ID, symbol, lot) 
  Places a sell market order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
  Returns: String syntax for the sell market order
 buy_limit_order(License_ID, symbol, lot, price) 
  Places a buy limit order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     price (float) : Limit price for the order
  Returns: String syntax for the buy limit order
 sell_limit_order(License_ID, symbol, lot, price) 
  Places a sell limit order
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     price (float) : Limit price for the order
  Returns: String syntax for the sell limit order
 stoploss_for_buy_order(License_ID, symbol, lot, stoploss_price) 
  Places a stop-loss order for a buy position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     stoploss_price (float) 
  Returns: String syntax for the buy stop-loss order
 stoploss_for_sell_order(License_ID, symbol, lot, stoploss_price) 
  Places a stop-loss order for a sell position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     stoploss_price (float) 
  Returns: String syntax for the sell stop-loss order
 takeprofit_for_buy_order(License_ID, symbol, lot, target_price) 
  Places a take-profit order for a buy position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     target_price (float) 
  Returns: String syntax for the buy take-profit order
 takeprofit_for_sell_order(License_ID, symbol, lot, target_price) 
  Places a take-profit order for a sell position
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     target_price (float) 
  Returns: String syntax for the sell take-profit order
 buy_stop_order(License_ID, symbol, lot, price) 
  Places a buy stop order above the current market price
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to buy
     price (float) : Stop order price
  Returns: String syntax for the buy stop order
 sell_stop_order(License_ID, symbol, lot, price) 
  Places a sell stop order below the current market price
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to sell
     price (float) : Stop order price
  Returns: String syntax for the sell stop order
 close_all_positions(License_ID, symbol) 
  Closes all positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all positions
 close_buy_positions(License_ID, symbol) 
  Closes all buy positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all buy positions
 close_sell_positions(License_ID, symbol) 
  Closes all sell positions for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
  Returns: String syntax for closing all sell positions
 close_partial_buy_position(License_ID, symbol, lot) 
  Closes a partial buy position for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to close
  Returns: String syntax for closing a partial buy position
 close_partial_sell_position(License_ID, symbol, lot) 
  Closes a partial sell position for a specific symbol
  Parameters:
     License_ID (string) : Unique license ID of the user
     symbol (string) : Trading symbol
     lot (int) : Number of lots to close
  Returns: String syntax for closing a partial sell position
Directional Volume IndexDirectional Volume Index (DVI) (buying/selling pressure) 
This index is adapted from the Directional Movement Index (DMI), but based on volume instead of price movements. The idea is to detect building directional volume indicating a growing amount of orders that will eventually cause the price to follow. (DVI is not displayed by default)
The rough algorithm for the Positive Directional Volume Index (green bar):
 
 calculate the delta to the previous green bar's volume
 if the delta is positive (growing buying pressure) add it to an SMA, else add 0 (also for red bars)
 divide these average deltas by the average volume
 the result is the Positive Directional Volume Index (DVI+) (vice versa for DVI-)
 
 Differential Directional Volume Index (DDVI) (relative pressure) 
Creating the difference of both Directional Volume Indexes (DVI+ - DVI-) creates the Differential Directional Volume Index (DDVI) with rising values indicating a growing buying pressure, falling values a growing selling pressure.  (DDVI is displayed by default, smoothed by a custom moving average)
 Average Directional Volume Index (ADVX) (pressure strength) 
Putting the relative pressure (DDVI) in relation to the total pressure (DVI+ + DVI-) we can determine the strength and duration of the currently building volume change / trend. For the DMI/ADX usually 20 is an indicator for a strong trend, values above 50 suggesting exhaustion and approaching reversals. (ADVX is not displayed by default, smoothed by a custom moving average)
 Divergences of the Differential Directional Volume Index (DDVI) (imbalances) 
By detecting divergences we can detect situations where e.g. bullish volume starts to build while price is in a downtrend, suggesting that there is growing buying pressure indicating an imminent bullish pullback/order block or reversal. (strong and hidden divergences are displayed by default)
 Divergences Overview: 
 
 strong bull:  higher lows on volume, lower lows on price
 medium bull:  higher lows on volume, equal lows on price
 weak bull:  equal lows on volume, lower lows on price
 hidden bull:  lower lows on volume, higher lows on price
 strong bear:  lower highs on volume, higher highs on price
 medium bear:  lower highs on volume, equal highs on price
 weak bear:  equal highs on volume, higher highs on price
 hidden bear:  higher highs on volume, lower highs on price
 
 DDVI Bands (dynamic overbought/oversold levels) 
Using Bollinger Bands with DDVI as source we receive an averaged relative pressure with stdev band offsets. This can be used as dynamic overbought/oversold levels indicating reversals on sharp crossovers.
 Alerts 
As of now there are no alerts built in, but all internal data is exposed via plot and plotshape functions, so it can be used for custom crossover conditions in the alert dialog. This is still a personal research project, so if you find good setups, please let me know.
SiCInside Sweep Close (ISC):
This concept captures a specific price action behavior and can help refine trading strategies for better precision. Here's a detailed explanation:
Inside:
The closing price of the candle stays within the range of the previous candle.
This indicates a containment of price action, suggesting indecision or preparation for a significant move.
Sweep:
The wick of the candle takes out (or "sweeps") the low (or high) of the previous candle.
This sweep can trigger stop-losses of retail traders or activate pending orders, often used by smart money strategies.
Close:
The candle ultimately closes inside the range of the previous candle.
This close signifies that the sweep was a liquidity grab rather than a genuine breakout, providing an actionable trading signal.
How ISC Can Be Used in Trading:
Liquidity Grab Recognition:
ISC can indicate when liquidity is swept from the market, making it an ideal entry point for traders anticipating a reversal or continuation.
Smart Money Concept (SMC) Synergy:
If you follow SMC principles, ISC aligns with key concepts like liquidity sweeps, order blocks, and mitigation zones.
Risk Management:
By identifying the ISC setup, you can place tighter stop-loss levels just outside the sweep, optimizing risk-reward ratios.
Entry Signals:
When you spot an ISC, you can enter trades at the close of the candle, anticipating a move in the direction opposite to the sweep.
Example of ISC in Action:
Imagine a bearish candle:
The wick sweeps the low of the previous candle, possibly triggering stop-losses.
However, the close stays inside the previous candle’s range.
This setup might indicate a reversal, where price moves upward after grabbing liquidity.
Why This Name Works:
It’s concise, professional, and directly linked to the trading action you’re describing.
The short form, ISC, is easy to remember and discuss within trading circles or while teaching others.
It ties into widely known concepts like smart money, price action, and liquidity sweeps, making it relatable yet unique.
Does this align with how you envision using the concept? Let me know if you’d like more refinements or visual examples!
Hybrid Triple Exponential Smoothing🙏🏻 TV, I present you HTES aka Hybrid Triple Exponential Smoothing, designed by Holt & Winters in the US, assembled by me in Saint P. I apply exponential smoothing individually to the data itself, then to residuals from the fitted values, and lastly to one-point forecast (OPF) errors, hence 'hybrid'. At the same time, the method is a closed-form solution and purely online, no need to make any recalculations & optimize anything, so the method is O(1).
  
^^ historical OPFs and one-point forecasting interval plotted instead of fitted values and prediction interval
 Before the How-to, first let me tell you some non-obvious things about Triple Exponential smoothing (and about Exponential Smoothing in general) that not many catch. Expo smoothing seems very straightforward and obvious, but if you look deeper... 
1) The whole point of exponential smoothing is its incremental/online nature, and its O(1) algorithm complexity, making it dope for high-frequency streaming data that is also univariate and has no weights. Consequently:
  - Any hybrid models that involve expo smoothing and any type of ML models like gradient boosting applied to residuals rarely make much sense business-wise: if you have resources to boost the residuals, you prolly have resources to use something instead of expo smoothing;
  - It also concerns the fashion of using optimizers to pick smoothing parameters; honestly, if you use this approach, you have to retrain on each datapoint, which is crazy in a streaming context. If you're not in a streaming context, why expo smoothing? What makes more sense is either picking smoothing parameters once, guided by exogenous info, or using dynamic ones calculated in a minimalistic and elegant way (more on that in further drops).
2) No matter how 'right' you choose the smoothing parameters, all the resulting components (level, trend, seasonal) are not pure; each of them contains a bit of info from the other components, this is just how non-sequential expo smoothing works. You gotta know this if you wanna use expo smoothing to decompose your time series into separate components. The only pure component there, lol, is the residuals;
3) Given what I've just said, treating the level (that does contain trend and seasonal components partially) as the resulting fit is a mistake. The resulting fit is level (l) + trend (b) + seasonal (s). And from this fit, you calculate residuals;
4) The residuals component is not some kind of bad thing; it is simply the component that contains info you consciously decide not to include in your model for whatever reason;
5) Forecasting Errors and Residuals from fitted values are 2 different things. The former are deltas between the forecasts you've made and actual values you've observed, the latter are simply differences between actual datapoints and in-sample fitted values;
6) Residuals are used for in-sample prediction intervals, errors for out-of-sample forecasting intervals;
7) Choosing between single, double, or triple expo smoothing should not be based exclusively on the nature of your data, but on what you need to do as well. For example:
  - If you have trending seasonal data and you wanna do forecasting exclusively within the expo smoothing framework, then yes, you need Triple Exponential Smoothing;
  - If you wanna use prediction intervals for generating trend-trading signals and you disregard seasonality, then you need single (simple) expo smoothing, even on trending data. Otherwise, the trend component will be included in your model's fitted values → prediction intervals.
8) Kind of not non-obvious, but when you put one smoothing parameter to zero, you basically disregard this component. E.g., in triple expo smoothing, when you put gamma and beta to zero, you basically end up with single exponential smoothing.
  
^^ data smoothing, beta and gamma zeroed out, forecasting steps = 0
 About the implementation 
* I use a simple power transform that results in a log transform with lambda = 0 instead of the mainstream-used transformers (if you put lambda on 2 in Box-Cox, you won't get a power of 2 transform)
* Separate set of smoothing parameters for data, residuals, and errors smoothing
* Separate band multipliers for residuals and errors
* Both typical error and typical residuals get multiplied by math.sqrt(math.pi / 2) in order to approach standard deviation so you can ~use Z values and get more or less corresponding probabilities
* In script settings → style, you can switch on/off plotting of many things that get calculated internally:
  - You can visualize separate components (just remember they are not pure);
  - You can switch off fit and switch on OPF plotting;
  - You can plot residuals and their exponentially smoothed typical value to pick the smoothing parameters for both data and residuals;
  - Or you might plot errors and play with data smoothing parameters to minimize them (consult SAE aka Sum of Absolute Errors plot);
  
^^ nuff said
 More ideas on how to use the thing 
1) Use Double Exponential Smoothing (data gamma = 0) to detrend your time series for further processing (Fourier likes at least weakly stationary data);
2) Put single expo smoothing on your strategy/subaccount equity chart (data alpha = data beta = 0), set prediction interval deviation multiplier to 1, run your strat live on simulator, start executing on real market when equity on simulator hits upper deviation (prediction interval), stop trading if equity hits lower deviation on simulator. Basically, let the strat always run on simulator, but send real orders to a real market when the strat is successful on your simulator;
3) Set up the model to minimize one-point forecasting errors, put error forecasting steps to 1, now you're doing nowcasting;
4) Forecast noisy trending sine waves for fun.
  
^^ nuff said 2
All Good TV ∞
NIFTY - Heatmap [DRK]Nifty 50 Heatmap by Percentage Change
 
This Pine Script generates a dynamic heatmap for the top 40 weighted stocks in the Nifty 50 index, ordered by their percentage change. The heatmap visually represents the performance of these stocks, with green indicating positive changes and red indicating negative changes.
 Features :
 Real-time Updates : The heatmap updates in real-time, providing an up-to-date snapshot of market performance.
 Color Coding : Stocks are color-coded based on their percentage change, making it easy to identify gainers and losers at a glance.
Future Enhancements:
 Indicator  : Planned updates include popups or descriptions that provide additional insights, such as key indicators and their positive or negative signals.
 Detailed Analysis : Future versions will offer more detailed analysis and insights to help traders make informed decisions.
Stay tuned for these exciting updates!
BinaryInsertionSortLibrary   "BinaryInsertionSort" 
Library containing functions which can help create sorted array based on binary insertion sort.
This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
 method binary_search_basic(sortedArray, item, order) 
  binary_search_basic - finds the closest index of the value
  Namespace types: array
  Parameters:
     sortedArray (array) : array which is assumed to be sorted in the requested order
     item (float) : float item which needs to be searched in the sorted array
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns: int index at which the item can be inserted into sorted array
 method binary_search_basic(sortedArray, item, order) 
  binary_search_basic - finds the closest index of the value
  Namespace types: array
  Parameters:
     sortedArray (array) : array which is assumed to be sorted in the requested order
     item (int) : int item which needs to be searched in the sorted array
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns: int index at which the item can be inserted into sorted array
 method binary_insertion_sort(sortedArray, item, order) 
  binary insertion sort - inserts item into sorted array while maintaining sort order
  Namespace types: array
  Parameters:
     sortedArray (array) : array which is assumed to be sorted in the requested order
     item (float) : float item which needs to be inserted into sorted array
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns: int index at which the item is inserted into sorted array
 method binary_insertion_sort(sortedArray, item, order) 
  binary insertion sort - inserts item into sorted array while maintaining sort order
  Namespace types: array
  Parameters:
     sortedArray (array) : array which is assumed to be sorted in the requested order
     item (int) : int item which needs to be inserted into sorted array
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns: int index at which the item is inserted into sorted array
 update_sort_indices(sortIndices, newItemIndex) 
  adds the sort index of new item added to sorted array and also updates existing sort indices.
  Parameters:
     sortIndices (array) : array containing sort indices of an array.
     newItemIndex (int) : sort index of new item added to sorted array
  Returns: void
 get_array_of_series(item, order) 
  Converts series into array and sorted array.
  Parameters:
     item (float) : float series
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns:  
 get_array_of_series(item, order) 
  Converts series into array and sorted array.
  Parameters:
     item (int) : int series
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns:  
 get_sorted_arrays(item, order) 
  Converts series into array and sorted array. Also calculates the sort order of the value array
  Parameters:
     item (float) : float|int series
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns:  
 get_sorted_arrays(item, order) 
  Converts series into array and sorted array. Also calculates the sort order of the value array
  Parameters:
     item (int) : int series
     order (int) : Sort order - positive number means ascending order whereas negative number represents descending order
  Returns: 






















