Market Timing(Mastersinnifty)Overview
Market Timing (Mastersinnifty) is a proprietary visualization tool designed to help traders study historical market behavior through structural pattern similarity.
The script analyzes the most recent session’s price action and identifies the closest-matching historical sequence among thousands of past patterns. Once a match is found, the script projects the subsequent historical price path onto the current chart for easy visual reference.
Unlike traditional indicators, Market Timing (Mastersinnifty) does not generate trade signals. Instead, it offers a unique historical scenario analysis based on quantified structural similarity.
---
How It Works
- The script captures the last 20 closing prices and compares them to historical price sequences from the past 8000 bars.
- Similarity is computed using the Euclidean distance formula (sum of squared differences) between the current pattern and historical candidates.
- Upon finding the most similar past pattern, the subsequent historical movement is normalized relative to session opening and plotted onto the current chart using projection lines.
- The projection automatically adapts to intraday, daily, weekly, or monthly timeframes, with the option for manual or automatic projection length settings.
- Session start detection is handled automatically based on volume thresholds and price-time analysis to adjust for market openings across different instruments.
---
Key Features
- Historical Pattern Matching: Quantitative matching of the most similar past price structure.
- Dynamic Projections: Visualizes likely historical scenarios based on past market behavior.
- Auto/Manual Projection Length: Flexible control over the number of projected bars.
- Multi-Timeframe Support: Works seamlessly across intraday, daily, weekly, and monthly charts.
- Purely Visual Context: Designed to support human decision-making without replacing it with automatic trade signals.
---
Who Can Benefit
- Traders studying market structure repetition and price symmetry.
- Visual thinkers who prefer scenario-based planning over fixed indicator systems.
- Intraday, swing, and position traders looking for historical context to complement price action, volume, and momentum studies.
---
How to Use
- Apply the script to any asset — including indices, stocks, commodities, forex, or crypto.
- Select your preferred timeframe.
- Choose "Auto" or "Custom" for the projection length.
- Observe the projected lines:
- Upward slope = Historical bullish continuation.
- Downward slope = Historical bearish continuation.
- Flat movement = Historical sideways movement.
- Combine insights with volume, support/resistance, and price action for better decision-making.
---
Important Notes
- This script does not predict the future. It offers a visual reference based on historical similarity.
- Always validate projected scenarios with live market conditions.
- Market structure evolves; past behavior may not repeat under new market dynamics.
- Use this tool for educational and research purposes only.
---
Disclaimer
This is not financial advice. The Market Timing (Mastersinnifty) tool is intended for research and educational purposes only. Trading involves risk, and past performance does not guarantee future results. Always apply sound risk management practices.
Patternrecognition
Volume Predictor [PhenLabs]📊 Volume Predictor
Version: PineScript™ v6
📌 Description
The Volume Predictor is an advanced technical indicator that leverages machine learning and statistical modeling techniques to forecast future trading volume. This innovative tool analyzes historical volume patterns to predict volume levels for upcoming bars, providing traders with valuable insights into potential market activity. By combining multiple prediction algorithms with pattern recognition techniques, the indicator delivers forward-looking volume projections that can enhance trading strategies and market analysis.
🚀 Points of Innovation:
Machine learning pattern recognition using Lorentzian distance metrics
Multi-algorithm prediction framework with algorithm selection
Ensemble learning approach combining multiple prediction methods
Real-time accuracy metrics with visual performance dashboard
Dynamic volume normalization for consistent scale representation
Forward-looking visualization with configurable prediction horizon
🔧 Core Components
Pattern Recognition Engine : Identifies similar historical volume patterns using Lorentzian distance metrics
Multi-Algorithm Framework : Offers five distinct prediction methods with configurable parameters
Volume Normalization : Converts raw volume to percentage scale for consistent analysis
Accuracy Tracking : Continuously evaluates prediction performance against actual outcomes
Advanced Visualization : Displays actual vs. predicted volume with configurable future bar projections
Interactive Dashboard : Shows real-time performance metrics and prediction accuracy
🔥 Key Features
The indicator provides comprehensive volume analysis through:
Multiple Prediction Methods : Choose from Lorentzian, KNN Pattern, Ensemble, EMA, or Linear Regression algorithms
Pattern Matching : Identifies similar historical volume patterns to project future volume
Adaptive Predictions : Generates volume forecasts for multiple bars into the future
Performance Tracking : Calculates and displays real-time prediction accuracy metrics
Normalized Scale : Presents volume as a percentage of historical maximums for consistent analysis
Customizable Visualization : Configure how predictions and actual volumes are displayed
Interactive Dashboard : View algorithm performance metrics in a customizable information panel
🎨 Visualization
Actual Volume Columns : Color-coded green/red bars showing current normalized volume
Prediction Columns : Semi-transparent blue columns representing predicted volume levels
Future Bar Projections : Forward-looking volume predictions with configurable transparency
Prediction Dots : Optional white dots highlighting future prediction points
Reference Lines : Visual guides showing the normalized volume scale
Performance Dashboard : Customizable panel displaying prediction method and accuracy metrics
📖 Usage Guidelines
History Lookback Period
Default: 20
Range: 5-100
This setting determines how many historical bars are analyzed for pattern matching. A longer period provides more historical data for pattern recognition but may reduce responsiveness to recent changes. A shorter period emphasizes recent market behavior but might miss longer-term patterns.
🧠 Prediction Method
Algorithm
Default: Lorentzian
Options: Lorentzian, KNN Pattern, Ensemble, EMA, Linear Regression
Selects the algorithm used for volume prediction:
Lorentzian: Uses Lorentzian distance metrics for pattern recognition, offering excellent noise resistance
KNN Pattern: Traditional K-Nearest Neighbors approach for historical pattern matching
Ensemble: Combines multiple methods with weighted averaging for robust predictions
EMA: Simple exponential moving average projection for trend-following predictions
Linear Regression: Projects future values based on linear trend analysis
Pattern Length
Default: 5
Range: 3-10
Defines the number of bars in each pattern for machine learning methods. Shorter patterns increase sensitivity to recent changes, while longer patterns may identify more complex structures but require more historical data.
Neighbors Count
Default: 3
Range: 1-5
Sets the K value (number of nearest neighbors) used in KNN and Lorentzian methods. Higher values produce smoother predictions by averaging more historical patterns, while lower values may capture more specific patterns but could be more susceptible to noise.
Prediction Horizon
Default: 5
Range: 1-10
Determines how many future bars to predict. Longer horizons provide more forward-looking information but typically decrease accuracy as the prediction window extends.
📊 Display Settings
Display Mode
Default: Overlay
Options: Overlay, Prediction Only
Controls how volume information is displayed:
Overlay: Shows both actual volume and predictions on the same chart
Prediction Only: Displays only the predictions without actual volume
Show Prediction Dots
Default: false
When enabled, adds white dots to future predictions for improved visibility and clarity.
Future Bar Transparency (%)
Default: 70
Range: 0-90
Controls the transparency of future prediction bars. Higher values make future bars more transparent, while lower values make them more visible.
📱 Dashboard Settings
Show Dashboard
Default: true
Toggles display of the prediction accuracy dashboard. When enabled, shows real-time accuracy metrics.
Dashboard Location
Default: Bottom Right
Options: Top Left, Top Right, Bottom Left, Bottom Right
Determines where the dashboard appears on the chart.
Dashboard Text Size
Default: Normal
Options: Small, Normal, Large
Controls the size of text in the dashboard for various display sizes.
Dashboard Style
Default: Solid
Options: Solid, Transparent
Sets the visual style of the dashboard background.
Understanding Accuracy Metrics
The dashboard provides key performance metrics to evaluate prediction quality:
Average Error
Shows the average difference between predicted and actual values
Positive values indicate the prediction tends to be higher than actual volume
Negative values indicate the prediction tends to be lower than actual volume
Values closer to zero indicate better prediction accuracy
Accuracy Percentage
A measure of how close predictions are to actual outcomes
Higher percentages (>70%) indicate excellent prediction quality
Moderate percentages (50-70%) indicate acceptable predictions
Lower percentages (<50%) suggest weaker prediction reliability
The accuracy metrics are color-coded for quick assessment:
Green: Strong prediction performance
Orange: Moderate prediction performance
Red: Weaker prediction performance
✅ Best Use Cases
Anticipate upcoming volume spikes or drops
Identify potential volume divergences from price action
Plan entries and exits around expected volume changes
Filter trading signals based on predicted volume support
Optimize position sizing by forecasting market participation
Prepare for potential volatility changes signaled by volume predictions
Enhance technical pattern analysis with volume projection context
⚠️ Limitations
Volume predictions become less accurate over longer time horizons
Performance varies based on market conditions and asset characteristics
Works best on liquid assets with consistent volume patterns
Requires sufficient historical data for pattern recognition
Sudden market events can disrupt prediction accuracy
Volume spikes may be muted in predictions due to normalization
💡 What Makes This Unique
Machine Learning Approach : Applies Lorentzian distance metrics for robust pattern matching
Algorithm Selection : Offers multiple prediction methods to suit different market conditions
Real-time Accuracy Tracking : Provides continuous feedback on prediction performance
Forward Projection : Visualizes multiple future bars with configurable display options
Normalized Scale : Presents volume as a percentage of maximum volume for consistent analysis
Interactive Dashboard : Displays key metrics with customizable appearance and placement
🔬 How It Works
The Volume Predictor processes market data through five main steps:
1. Volume Normalization:
Converts raw volume to percentage of maximum volume in lookback period
Creates consistent scale representation across different timeframes and assets
Stores historical normalized volumes for pattern analysis
2. Pattern Detection:
Identifies similar volume patterns in historical data
Uses Lorentzian distance metrics for robust similarity measurement
Determines strength of pattern match for prediction weighting
3. Algorithm Processing:
Applies selected prediction algorithm to historical patterns
For KNN/Lorentzian: Finds K nearest neighbors and calculates weighted prediction
For Ensemble: Combines multiple methods with optimized weighting
For EMA/Linear Regression: Projects trends based on statistical models
4. Accuracy Calculation:
Compares previous predictions to actual outcomes
Calculates average error and prediction accuracy
Updates performance metrics in real-time
5. Visualization:
Displays normalized actual volume with color-coding
Shows current and future volume predictions
Presents performance metrics through interactive dashboard
💡 Note:
The Volume Predictor performs optimally on liquid assets with established volume patterns. It’s most effective when used in conjunction with price action analysis and other technical indicators. The multi-algorithm approach allows adaptation to different market conditions by switching prediction methods. Pay special attention to the accuracy metrics when evaluating prediction reliability, as sudden market changes can temporarily reduce prediction quality. The normalized percentage scale makes the indicator consistent across different assets and timeframes, providing a standardized approach to volume analysis.
AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend)The AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend) is a cutting-edge indicator that combines advanced mathematical modeling, AI-driven analytics, and segment-based pattern recognition to forecast price movements with precision. This tool is designed to provide traders with deep insights into market dynamics by leveraging multivariate pattern detection and sophisticated predictive algorithms.
👽 Core Features
Segment-Based Pattern Recognition
At its heart, the indicator divides price data into discrete segments, capturing key elements like candle bodies, high-low ranges, and wicks. These segments are normalized using ATR-based volatility adjustments to ensure robustness across varying market conditions.
AI-Powered k-Nearest Neighbors (kNN) Prediction
The predictive engine uses the kNN algorithm to identify the closest historical patterns in a multivariate dictionary. By calculating the distance between current and historical segments, the algorithm determines the most likely outcomes, weighting predictions based on either proximity (distance) or averages.
Dynamic Dictionary of Historical Patterns
The indicator maintains a rolling dictionary of historical patterns, storing multivariate data for:
Candle body ranges, High-low ranges, Wick highs and lows.
This dynamic approach ensures the model adapts continuously to evolving market conditions.
Volatility-Normalized Forecasting
Using ATR bands, the indicator normalizes patterns, reducing noise and enhancing the reliability of predictions in high-volatility environments.
AI-Driven Trend Detection
The indicator not only predicts price levels but also identifies market regimes by comparing current conditions to historically significant highs, lows, and midpoints. This allows for clear visualizations of trend shifts and momentum changes.
👽 Deep Dive into the Core Mathematics
👾 Segment-Based Multivariate Pattern Analysis
The indicator analyzes price data by dividing each bar into distinct segments, isolating key components such as:
Body Ranges: Differences between the open and close prices.
High-Low Ranges: Capturing the full volatility of a bar.
Wick Extremes: Quantifying deviations beyond the body, both above and below.
Each segment contributes uniquely to the predictive model, ensuring a rich, multidimensional understanding of price action. These segments are stored in a rolling dictionary of patterns, enabling the indicator to reference historical behavior dynamically.
👾 Volatility Normalization Using ATR
To ensure robustness across varying market conditions, the indicator normalizes patterns using Average True Range (ATR). This process scales each component to account for the prevailing market volatility, allowing the algorithm to compare patterns on a level playing field regardless of differing price scales or fluctuations.
👾 k-Nearest Neighbors (kNN) Algorithm
The AI core employs the kNN algorithm, a machine-learning technique that evaluates the similarity between the current pattern and a library of historical patterns.
Euclidean Distance Calculation:
The indicator computes the multivariate distance across four distinct dimensions: body range, high-low range, wick low, and wick high. This ensures a comprehensive and precise comparison between patterns.
Weighting Schemes: The contribution of each pattern to the forecast is either weighted by its proximity (distance) or averaged, based on user settings.
👾 Prediction Horizon and Refinement
The indicator forecasts future price movements (Y_hat) by predicting logarithmic changes in the price and projecting them forward using exponential scaling. This forecast is smoothed using a user-defined EMA filter to reduce noise and enhance actionable clarity.
👽 AI-Driven Pattern Recognition
Dynamic Dictionary of Patterns: The indicator maintains a rolling dictionary of N multivariate patterns, continuously updated to reflect the latest market data. This ensures it adapts seamlessly to changing market conditions.
Nearest Neighbor Matching: At each bar, the algorithm identifies the most similar historical pattern. The prediction is based on the aggregated outcomes of the closest neighbors, providing confidence levels and directional bias.
Multivariate Synthesis: By combining multiple dimensions of price action into a unified prediction, the indicator achieves a level of depth and accuracy unattainable by single-variable models.
Visual Outputs
Forecast Line (Y_hat_line):
A smoothed projection of the expected price trend, based on the weighted contribution of similar historical patterns.
Trend Regime Bands:
Dynamic high, low, and midlines highlight the current market regime, providing actionable insights into momentum and range.
Historical Pattern Matching:
The nearest historical pattern is displayed, allowing traders to visualize similarities
👽 Applications
Trend Identification:
Detect and follow emerging trends early using dynamic trend regime analysis.
Reversal Signals:
Anticipate market reversals with high-confidence predictions based on historically similar scenarios.
Range and Momentum Trading:
Leverage multivariate analysis to understand price ranges and momentum, making it suitable for both breakout and mean-reversion strategies.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
TechniTrend: Advance Custom Candle Finder (CCF)🟦 Description:
The TechniTrend: Advanced Custom Candle Finder (CCF) is a versatile tool designed to help traders identify custom candlestick patterns using various configurable criteria. This indicator provides a flexible framework to filter and highlight specific candles based on volume, volatility, candle characteristics, and other important metrics. Below is a detailed explanation of each filter and its customization options:
🟦 Volume-Based Filters
🔸Volume Spike Filter:
Enable filtering based on volume spikes. Use the Volume Spike Multiplier to define what constitutes a significant increase in volume compared to the average. A spike indicates unusually high trading interest.
🔸Volume Range Filter:
Filter candles based on specific volume ranges. Set Minimum Volume and Maximum Volume thresholds to isolate candles with trading volumes within your desired boundaries.
🟦 Candle Body & Wick Filters
🔸Body Size Filter:
Filter candles based on the size of their body. A Body Size Multiplier determines what is considered a large body relative to historical averages.
🔸Body Percentage Filter:
Filter based on the proportion of the body to the entire candle size. Use the Body Percentage Threshold to highlight candles where the body makes up a certain percentage of the total candle range.
🔸Wick-to-Body Ratio Filter:
Identify candles with specific wick-to-body ratios. A higher Wick-to-Body Ratio can indicate indecision or reversals.
🟦 Volatility & Range Filters
🔸Volatility Filter:
Highlight candles based on price changes relative to volume. The Volatility Multiplier sets the threshold for what is considered a volatile candle.
🔸Candle Range Filter:
Filter based on the range (High - Low) of each candle. Use Minimum Candle Range and Maximum Candle Range to specify your desired candle size in points or pips.
🔸Short-Term and Long-Term Volatility Filters:
Analyze volatility over different periods. Enable Short-Term Volatility or Long-Term Volatility filters to compare recent volatility against historical averages, helping you detect sudden market shifts.
🟦 Candle Color & Open/Close Filters
🔸Candle Color Filter:
Filter based on the candle's color. Choose between Bullish (close > open) or Bearish (close < open) to focus on specific market sentiments.
🔸Open/Close Price Range Filter:
Filter based on the difference between the open and close prices. Use Minimum Open/Close Range and Maximum Open/Close Range to specify your acceptable range in price movements.
🟦 Core Functionality
The CCF indicator combines these filters to provide a final signal whenever a candle meets all the enabled criteria. By default, it highlights any qualifying candle directly on the chart and changes the background color for added visibility.
🟦 Key Features:
🔸Highly Customizable Filters: Adjust the parameters for each filter to tailor the indicator to your specific needs.
🔸Multiple Conditions: Combine several conditions to identify complex candlestick patterns.
🔸Real-Time Alerts: Receive instant notifications when a matching candle pattern is found based on your custom criteria.
🟦 How to Use:
🔸Enable the filters you wish to apply (e.g., Volume Spike, Candle Body Size, Volatility).
🔸Adjust the thresholds for each filter to fine-tune the pattern recognition criteria.
🔸Observe the chart to see visual cues for candles that match your specified conditions.
🟦 Notes:
🔸Ensure that you clearly understand each filter’s role. Over-filtering with very strict criteria may reduce the number of signals.
🔸This indicator is designed to be a customizable tool, not providing buy or sell recommendations.
🔸Use in combination with other analysis tools and indicators for the best results.
Lune Technical Analysis Premium⬛️ Overview
Lune Technical Analysis is a state-of-the-art TradingView indicator, meticulously designed to provide real-time market insights. Distinguished by its non-repainting features that operate in real-time, this tool brings enhanced accuracy and timeliness to your market analysis.
🟦 Features
Lune Technical Analysis equips traders with an array of innovative features:
🔹 Candle Coloring: The Candle Coloring feature introduces an innovative approach to visualizing market sentiment by coloring chart candles. It is devised to streamline your market analysis, offering a readily digestible snapshot of market trends. For example, if you aim to gauge the predominant market sentiment promptly, enable this feature for instant candle color-coding in accordance with prevailing bullish or bearish market structures. Though it currently supports only Market Structure-based Candle Coloring, its settings can be manipulated for enabling or disabling this feature. This feature operates by applying predefined algorithms that interpret market sentiment, coloring the candles accordingly.
🔹 Chart Pattern Detection: This sophisticated tool automatically detects and illustrates common chart patterns on your chart, simplifying the process of pattern identification. It identifies a range of patterns such as Head & Shoulders, Inverted Head & Shoulders, Ascending/Descending Wedges, Broadening Wedges, various Triangles, and Double Tops/Bottoms, enhancing your confluence detection in the market. For example, upon detecting a Double Top pattern, you could anticipate a potential price reversal due to this bearish signal. The sensitivity of this tool can be customized according to your trading style, with lower settings for short-term changes and higher for long-term. This feature leverages predefined formulas and price action analysis to identify these patterns.
🔹 Trendlines: With the Automatic Trendline Drawing tool, your technical analysis becomes significantly more efficient and precise. This feature is engineered to identify upward and downward Trendlines, aiding in locating potential pivots, and market support/resistance. For instance, if the price consistently rebounds off a Trendline, it may continue to do so, serving as a support/resistance level. However, a break through the Trendline could signal potential volatility and trend change. This feature's sensitivity to price changes can be adjusted to either short or long-term. It works by tracing Trendlines based on price action and wick formations to detect potential pivots.
🔹 Liquidity Bubbles: Liquidity Bubbles is an advanced tool that pinpoints key liquidity areas and large positions in real-time. This feature significantly contributes to effective trading strategy formulation by highlighting potential entry and exit points. It operates in real-time, ensuring zero repaint or lag, and supports two modes: Enhanced Bubbles and Basic Bubbles. For instance, the detection of multiple bullish Liquidity Bubbles during a ranging market could suggest an upward price movement due to dominant bullish volume. This feature's settings include thresholds for insignificant bubble filtering and a mode selection feature. Liquidity Bubbles operates by applying a proprietary formula to volume data, determining general volume direction and potential positions.
🔹 Market Structure: The Market Structure tool identifies key market structures such as Break of Structures (BoS) and Change of Character (ChoCh), thereby enhancing your ability to read market trends and sentiment. This smart money concept gives you a unique insight into short-term and long-term market trends. For instance, the appearance of a bullish Break of Structure and Change of Character after a predominantly bearish market sentiment could suggest a new bullish trend. This feature allows users to select which Market Structures to display and calculates these structures based on the market's high and low points.
🔹 Order Blocks: Order Blocks provide a visual representation of areas where large market participants are likely to place orders. These zones, where significant buying or selling activity has occurred in the past, offer insightful data for future price movements. The Order Blocks feature operates in real-time, providing real-time Order Blocks without any lag. For instance, if the price enters a large Order Block with predominantly bullish volume, an upward price movement can be anticipated. However, if the price breaks through the block, it could suggest the block's invalidation and a likely continued price fall. You can configure the settings to enable an additional Order Block, customize timeframes, overlap functions, and apply a quality filter. This feature calculates Order Blocks using the volume and candle size data.
🔹 Supply/Demand Zones: This real-time tool identifies crucial supply and demand zones, revealing potential price reaction points. These zones, where supply (selling pressure) and demand (buying pressure) have historically impacted price significantly, provide traders with insights into potential areas of strong support (demand) and resistance (supply). For example, if the price enters a large supply zone, a price rejection could be anticipated due to historical selling pressure at this zone. The settings enable users to add an additional Supply/Demand Zone, customize the timeframe, and apply a quality filter. This feature identifies common Supply/Demand Zones patterns based on volume and the size of the zone and displays them on the chart.
🔹 Fair Value Gaps: The Fair Value Gaps tool is designed to identify potential price correction zones or "gaps". These areas, where the market price sharply deviated from the fair value, suggest potential price adjustments in the future. For instance, the formation of a bullish Fair Value Gap could indicate a future price drop to fill this gap, potentially followed by an upward movement if the gap was of fair value. The settings allow users to enable additional Fair Value Gaps, customize the timeframe, and apply a quality filter. This feature measures large market gaps based on the size of the gap and its volume.
These features and tools collectively offer a comprehensive solution for traders to understand and navigate the financial markets. It's important to remember that they are designed to assist in making informed trading decisions and should be used as part of a balanced trading strategy.
🟧 Usage
Lune Technical Analysis's unique feature set can be leveraged both individually and synergistically. It is important to understand each feature and experiment with different configurations to best suit your unique trading needs.
🔸 Example #1: The following example demonstrates how the Order Block and Liquidity Bubbles feature can be used together to enhance your market analysis.
Order Blocks work in real-time to identify key order zones based on price action. These zones are often crucial for predicting price fluctuations. Meanwhile, Liquidity Bubbles act as real-time visual cues that detect significant market positions, facilitating an understanding of market accumulation, distribution, and trapped positions.
In this instance, at point 1, a bearish Basic and Enhanced Liquidity Bubble is visible within a crucial Order Block. The combination of these indicators augments the bearish sentiment, leading to a potential price decrease. Similarly, at point 2, the conjunction of two bullish Basic Liquidity Bubbles within an Order Block strengthens the bullish sentiment, culminating in a subsequent price increase.
🔸 Example #2: The following example demonstrates how Supply and Demand Zones can be used to detect strong and quality supports and resistance.
Supply and Demand Zones operate in real-time, detecting crucial zones based on price action and volume. This feature is invaluable for predicting potential price reaction points.
At point 1, the price enters a Supply Zone, a historical hotspot for selling activity, which usually leads to a price rejection and consequent decrease. At point 2, a Demand Zone indicating a bullish sentiment suggests a potential reversal when the price touches this level.
🔸 Example #3: The following example demonstrates how the Chart Pattern Detection feature is able to detect chart patterns to help enhance your trades.
Chart Pattern Detection employs formulas and price action analysis to identify common chart patterns as they form. Here, it successfully detects a 'Head and Shoulders' pattern, a conventionally bearish pattern, indicating a potential price drop.
🟥 Conclusion
Lune Technical Analysis stands as an exceptional blend of real-time insights into market activity. Its real-time, non-repainting features offer traders a more precise and timely approach to market analysis, promoting improved decision making in ever-changing market conditions.
🔻 Access
You can see the Author's instructions below to get instant access to this indicator & our Premium Suite.
🔻 Disclaimer
Lune Technical Analysis is a tool for aiding in market analysis and is not a guarantee of future market performance or individual trading success. We strongly recommend that users combine our tool with their trading strategies and do their due diligence before making any trading decisions.
Remember, past performance is not indicative of future results. Please trade responsibly.
Sniffer
╭━━━╮╱╱╱╱╭━╮╭━╮
┃╭━╮┃╱╱╱╱┃╭╯┃╭╯
┃╰━━┳━╮╭┳╯╰┳╯╰┳━━┳━╮
╰━━╮┃╭╮╋╋╮╭┻╮╭┫┃━┫╭╯
┃╰━╯┃┃┃┃┃┃┃╱┃┃┃┃━┫┃
╰━━━┻╯╰┻╯╰╯╱╰╯╰━━┻╯
Overview
A vast majority of modern data analysis & modelling techniques rely upon the idea of hidden patterns, wether it is some type of visualisation tool or some form of a complex machine learning algorithm, the one thing that they have in common is the belief, that patterns tell us what’s hidden behind plain numbers. The same philosophy has been adopted by many traders & investors worldwide, there’s an entire school of thought that operates purely based on chart patterns. This is where Sniffer comes in, it is a tool designed to simplify & quantify the job of pattern recognition on any given price chart, by combining various factors & techniques that generate high-quality results.
This tool analyses bars selected by the user, and highlights bar clusters on the chart that exhibit similar behaviour across multiple dimensions. It can detect a single candle pattern like hammers or dojis, or it can handle multiple candles like morning/evening stars or double tops/bottoms, and many more. In fact, the tool is completely independent of such specific candle formations, instead, it works on the idea of vector similarity and generates a degree of similarity for every single combination of candles. Only the top-n matches are highlighted, users get to choose which patterns they want to analyse and to what degree, by customising the feature-space.
Background
In the world of trading, a common use-case is to scan a price chart for some specific candlestick formations & price structures, and then the chart is further analysed in reference to these events. Traders are often trying to answer questions like, when was the last time price showed similar behaviour, what are the instances similar to what price is doing right now, what happens when price forms a pattern like this, what were some of other indicators doing when this happened last(RSI, CCI, ADX etc), and many other abstract ideas to have a stronger confluence or to confirm a bias.Having such a context can be vital in making better informed decisions, but doing this manually on a chart that has thousands of candles can have many disadvantages. It’s tedious, human errors are rather likely, and even if it’s done with pin-point accuracy, chances are that we’ll miss out on many pieces of information. This is the thought that gave birth to Sniffer .
Sniffer tries to provide a general solution for pattern-based analysis by deploying vector-similarity computation techniques, that cover the full-breadth of a price chart and generate a list of top-n matches based on the criteria selected by the user. Most of these techniques come from the data science space, where vector similarity is often implemented to solve classification & clustering problems. Sniffer uses same principles of vector comparison, and computes a degree of similarity for every single candle formation within the selected range, and as a result generates a similarity matrix that captures how similar or dissimilar a set of candles is to the input set selected by the user.
How It Works
A brief overview of how the tool is implemented:
- Every bar is processed, and a set of features are mapped to it.
- Bars selected by the user are captured, and saved for later use.
- Once the all the bars have been processed, candles are back-tracked and degree of similarity is computed for every single bar(max-limit is 5000 bars).
- Degree of similarity is computed by comparing attributes like price range, candle breadth & volume etc.
- Similarity matrix is sorted and top-n results are highlighted on the chart through boxes of different colors.
A brief overview of the features space for bars:
- Range: Difference between high & low
- Body: Difference between close & open
- Volume: Traded volume for that candle
- Head: Upper wick for green candles & lower wick for red candles
- Tail: Lower wick for green candles & upper wick for red candles
- BTR: Body to Range ratio
- HTR: Head to Range ratio
- TTR: Tail to Range ratio
- HTB: Head to Body ratio
- TTB: Tail to Body ratio
- ROC: Rate of change for HL2 for four different periods
- RSI: Relative Strength Index
- CCI: Commodity Channel Index
- Stochastic: Stochastic Index
- ADX: DMI+, DMI- & ADX
A brief overview of how degree of similarity is calculated:
- Each bar set is compared to the inout bar set within the selected feature space
- Features are represented as vectors, and distance between the vectors is calculated
- Shorter the distance, greater the similarity
- Different distance calculation methods are available to choose from, such as Cosine, Euclidean, Lorentzian, Manhattan, & Pearson
- Each method is likely to generate slightly different results, users are expected to select the method & the feature space that best fits their use-case
How To Use It
- Usage of this tool is relatively straightforward, users can add this indicator to their chart and similar clusters will be highlighted automatically
- Users need to select a time range that will be treated as input, and bars within that range become the input formation for similarity calculations
- Boxes will be draw around the clusters that fit the matching criteria
- Boxes are color-coded, green color boxes represent the top one-third of the top-n matches, yellow boxes represent the middle third, red boxes are for bottom third, and white box represents user-input
- Boxes colors will be adjusted as you adjust input parameters, such as number of matches or look-back period
User Settings
Users can configure the following options:
- Select the time-range to set input bars
- Select the look-back period, number of candles to backtrack for similarity search
- Select the number of top-n matches to show on the chart
- Select the method for similarity calculation
- Adjust the feature space, this enables addition of custom features, such as pattern recognition, technical indicators, rate of change etc
- Toggle verbosity, shows degree of similarity as a percentage value inside the box
Top Features
- Pattern Agnostic: Designed to work with variable number of candles & complex patterns
- Customisable Feature Space: Users get to add custom features to each bar
- Comprehensive Comparison: Generates a degree of similarity for all possible combinations
Final Note
- Similarity matches will be shown only within last 4500 bars.
- In theory, it is possible to compute similarity for any size candle formations, indicator has been tested with formations of 50+ candles, but it is recommended to select smaller range for faster & cleaner results.
- As you move to smaller time frames, selected time range will provide a larger number of candles as input, which can produce undesired results, it is advised to adjust your selection when you change time frames. Seeking suggestions on how to directly receive bars as user input, instead of time range.
- At times, users may see array index out of bound error when setting up this indicator, this generally happens when the input range is not properly configured. So, it should disappear after you select the input range, still trying to figure out where it is coming from, suggestions are welcome.
Credits
- @HeWhoMustNotBeNamed for publishing such a handy PineScript Logger, it certainly made the job a lot easier.
FunctionPatternDecompositionLibrary "FunctionPatternDecomposition"
Methods for decomposing price into common grid/matrix patterns.
series_to_array(source, length) Helper for converting series to array.
Parameters:
source : float, data series.
length : int, size.
Returns: float array.
smooth_data_2d(data, rate) Smooth data sample into 2d points.
Parameters:
data : float array, source data.
rate : float, default=0.25, the rate of smoothness to apply.
Returns: tuple with 2 float arrays.
thin_points(data_x, data_y, rate) Thin the number of points.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, default=2.0, minimum threshold rate of sample stdev to accept points.
Returns: tuple with 2 float arrays.
extract_point_direction(data_x, data_y) Extract the direction each point faces.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
Returns: float array.
find_corners(data_x, data_y, rate) ...
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, minimum threshold rate of data y stdev.
Returns: tuple with 2 float arrays.
grid_coordinates(data_x, data_y, m_size) transforms points data to a constrained sized matrix format.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
m_size : int, default=10, size of the matrix.
Returns: flat 2d pseudo matrix.
Double Top/Bottom V2This is an enhanced version of Double Top/Bottom detector.
Initial basic version can be found here:
Concept of deriving pattern is similar but there are few major changes.
Double Top:
Get the highest pivot high from last X pivot highs ( DTHigh1 )
Look for next top most pivot high which happened after DTHigh1 ( DTHigh2 )
Look for lowest pivot low between DTHigh1 and DTHigh2 ( DTLow )
Double Bottom:
Get the lowest pivot low from last X pivot lows ( DBLow1 )
Look for next lowest pivot low which happened after DBLow1 ( DBLow2 )
Look for highest pivot high between DBLow1 and DBLow2 ( DbHigh )
Other Key parameters:
checkForAbsolutePeaks and absolutePeakLoopback work together. When selected, double top and double bottom is formed only if DTHigh1 / DBLow1 are highest/lowest points from last absolutePeakLoopback bars back.
considerPivotDistance will make sure distance between Highs(in double top) and lows(in double bottom) are below 2 ( MaxAtrDistanceBase ) times ATR. And distance between average Highs/Lows to Low/High forming triangle is less than 6 ( MaxAtrDistanceHighLow ) times ATR. This will avoid showing steep triangles as double top/bottoms.
showLastLevels option allows users to display dashed lines on double top/bottom confirmation and invalidation levels for last formed double bottom and tops. These can be treated as strong support and resistence. Dashed lines are permanently formed on double top/bottom setups when an invalidation or confirmation occurs by price crossing either lowest or highest points of double top/bottom triangles.
Alerts:
Probable double top/bottom - when double top or bottom triangles formed.
Double top/bottom confirmation - when double top or bottom is confirmed.
Double top/bottom invalidation - when double top or bottom is invalidated.
Few important points about adjusting parameters:
Lower pivot lengths will generate more signals. But, too frequent signals may not be desirable as well.
higher absolutePeakLoopback will reduce number of signals while strengthening them.
Unchecking consider pivot distance or reducing MaxAtrDistanceBase/MaxAtrDistanceHighLow may considerably increase the number of pivots specially when pivot lengths are lower side. This may result in reduced quality of signals as well.
Moving average condition which is part of basic script is not included in this. We can add Hull Suite or moving average crossover on the chart as confirmation of strong signal.
Pattern Recognition Probabilities [racer8]Brief 🌟
Pattern Recognition Probabilities (PRP) is a REALLY smart indicator. It uses the correlation coefficient formula to determine if the current set of bars resembles that of past patterns. It counts the number of times the current pattern has occurred in the past and looks at how it performed historically to determine the probability of an up move, down move, or neutral move.
I'd like to say, I'm proud of this indicator 😆🤙 This is the SMARTEST indicator I have ever made 🧠🧠🧠
Note: PRP doesn't give you actual probabilities, but gives you instead the historical occurrences of up, down, and neutral moves that resulted after the pattern. So you can calculate probabilities based on these valuable statistics. So for example, PRP can tell you this pattern has historically resulted in 55 up moves, 20 down moves, and 60 neutral moves.
Parameters 🌟
You can adjust the Pattern length, Minimum correlation, Statistics lookback, Exit after time, and Atr multiplier parameters.
Pattern length - determines how long the pattern is
Minimum correlation - determines the minimum correlation coefficient needed to pass as a similiar enough pattern.
Statistics lookback - lookback period for gathering all the patterns in the past.
Exit after time - determines when exit occurred (number of periods after pattern) ; is the point that represents the pattern's result.
Atr multiplier - determines minimum atr move needed to qualify whether result was an up/down move or a neutral move. If a particular historical pattern resulted in a move that was less than the min atr, then it is recorded as a neutral move in the statistics.
Thanks for reading! 🙏
Good luck 🍀 Stay safe 😷 Drink lots of water💧
Enjoy! 🥳 and Hit the like button! 👍
Test: Pattern RecognitionEXPERIMENTAL:
a test on how to compare price at different frequency's with static patterns.