Alan Kelland's BoxThose of you not familiar with Alan Kelland's trading method called the "Alan Square" or "DaBox" may find this indicator interesting. Here is a brief excerpt from the documentation:
Alan Kelland's Box Trading Method
A draw tool growing in popularity is the Alan Square, named after its inventor Alan Kelland. Alan's method is first and foremost price action. The square serves as a structure to create
Opportunities
Targets and
Protection
Cari dalam skrip untuk "range"
Percent change bar chart This histogram displays price or % change from previous bar.
Can be applied to any time frame.
Adaptive MACD Deluxe [AlgoAlpha]OVERVIEW
This script is an advanced rework of the classic MACD indicator, designed to be more adaptive, visually informative, and customizable. It enhances the original MACD formula using a dynamic feedback loop and a correlation-based weighting system that adjusts in real-time based on how deterministic recent price action is. The signal line is flexible, offering several smoothing types including Heiken Ashi, while the histogram is color-coded with gradients to help users visually identify momentum shifts. It also includes optional normalization by volatility, allowing MACD values to be interpreted as relative percentage moves, making the indicator more consistent across different assets and timeframes.
CONCEPTS
This version of MACD introduces a deterministic weight based on R-squared correlation with time, which modulates how fast or slow the MACD adapts to price changes. Higher correlation means smoother, slower MACD responses, and low correlation leads to quicker reaction. The momentum calculation blends traditional EMA math with feedback and damping components to create a smoother, less noisy series. Heiken Ashi is optionally used for signal smoothing to better visualize short-term trend bias. When normalization is enabled, the MACD is scaled by an EMA of the high-low range, converting it into a bounded, volatility-relative indicator. This makes extreme readings more meaningful across markets.
FEATURES
The script offers six distinct options for signal line smoothing: EMA, SMA, SMMA (RMA), WMA, VWMA, and a custom Heiken Ashi mode based on the MACD series. Each option provides a different response speed and smoothing behavior, allowing traders to match the indicatorโs behavior to their strategyโwhether it's faster reaction or reduced noise.
Normalization is another key feature. When enabled, MACD values are scaled by a volatility proxy, converting the indicator into a relative percentage. This helps standardize the MACD across different assets and timeframes, making overbought and oversold readings more consistent and easier to interpret.
Threshold zones can be customized using upper and lower boundaries, with inner zones for early warnings. These zones are highlighted on the chart with subtle background fills and directional arrows when MACD enters or exits key levels. This makes it easier to spot strong or weak reversals at a glance.
Lastly, the script includes multiple built-in alerts. Users can set alerts for MACD crossovers, histogram flips above or below zero, and MACD entries into strong or weak reversal zones. This allows for hands-free monitoring and quick decision-making without staring at the chart.
USAGE
To use this script, choose your preferred signal smoothing type, enable normalization if you want MACD values relative to volatility, and adjust the threshold zones to fit your asset or timeframe. Use the colored histogram to detect changes in momentum strengthโbrighter colors indicate rising strength, while faded colors imply weakening. Heiken Ashi mode smooths out noise and provides clearer signals, especially useful in choppy conditions. Use alert conditions for crossover and reversal detection, or monitor the arrow markers for entries into potential exhaustion zones. This setup works well for trend following, momentum trading, and reversal spotting across all market types.
Price Depth Analysis to the MAHello Traders! Today, I bring you an indicator that can greatly assist you in your trading. This indicator aims to analyze the Expansion and Contraction process of the price in relation to a moving average. We refer to "Expansion" when the price moves away from the moving average; a significant expansion could signal that the asset is in a strong trend. On the other hand, when we refer to "Contraction", it's when the price approaches or returns to the moving average. A contraction could signal that the asset is losing momentum and might be preparing for a trend change or consolidation.
To use the indicator, the first thing you need to do is define the type of analysis you want to perform (from the indicator settings) whether you want to evaluate prices above the moving average or below. You should also select the type of moving average and its period.
The indicator will search for the maximum distance in all the chart bars, which will be represented with a yellow label.
From that value, the indicator will generate a certain number of proportional levels (configurable up to 20) and will count all the bars that reached each level. This will be represented in a table showing both the number of bars that reached each range and the percentage in relation to the total bars of all ranges.
Additionally, there's the possibility to view the ranges directly for the current price, providing a good reference.
>> Alerts:
The indicator comes with alerts that notify traders about specific price movements in relation to a moving average (MA). These alerts are triggered when the price enters different ranges, either above or below the MA.
>> Settings:
- Type of Analysis: Users can choose to analyze the price either above or below the MA.
- Length of the moving average: Length of the MA.
- Source of the moving average: Source to calculate the MA (e.g., close, open).
- Type of moving average: Type of MA (SMA, EMA, WMA, VWMA, HMA).
- Show Moving Average: Option to display or hide the MA on the chart.
- Number of levels: Number of levels or ranges to categorize the distance between the price and the MA.
- Number of decimals: Number of decimals to display in labels and tables.
- Show Ranges: Option to display or hide the ranges on the chart.
- Extend Range: Extension of the ranges into future bars.
- Range Fill Transparency: Transparency of the range fill.
>> Potential Utility of the Indicator:
- Entry and Exit Optimization:
By understanding the percentages of each range, traders can identify optimal levels to enter or exit a trade, maximizing profits and minimizing losses.
- Risk Management:
Range percentages can help determine market volatility. A range with a high percentage indicates greater volatility, which can be useful for setting wider stop losses or adjusting position size.
- Overbought and Oversold Zone Identification:
If a price is at the upper or lower extreme of its percentage range, it may indicate overbought or oversold conditions, respectively. These zones can be opportunities for counter-trend trades.
- Momentum Assessment:
A rapid change in range percentages can indicate strong momentum in a particular direction. Traders can use this information to ride the momentum wave or prepare for a potential reversal.
- False Signal Filtering:
By combining range percentage knowledge with other indicators, traders can filter out signals that might be less reliable, thus improving trade accuracy.
- Strategic Planning:
Knowing range percentages allows traders to adapt their strategies according to market conditions. For instance, in a market with narrow ranges and low percentages, they might opt for range strategies. In markets with wide ranges and high percentages, they might look for trend strategies.
- Trend Strength Evaluation:
If range percentages show that the price consistently stays at one end of the range, this may signal a strong and sustained trend.
- Improved Trading Discipline:
By basing trading decisions on quantitative data like range percentages, traders can trade more objectively and disciplined, avoiding impulsive or emotion-based decisions.
>> Future Indicator Update:
- In future versions, we plan to incorporate a detailed analysis based on the historical behavior of candles after the price enters a specific range. For instance, if after an upward movement the price enters a certain range and historically, the next candle tends to be bearish in a high percentage of occasions, this information will be highlighted and presented clearly to the user. The idea behind this addition is to provide traders with a statistical edge, allowing them to anticipate potential market movements with greater accuracy. Moreover, this information could be used to seek trading opportunities in smaller timeframes, aligning the trade direction based on the probability of this mentioned candle.
>> Conclusions:
- In summary, a detailed understanding of each range's percentages in an indicator provides traders with a valuable tool to analyze the market, make informed decisions, and enhance their trading. By grasping the significance of these percentages, traders can adapt their strategies and techniques to fully leverage the opportunities the market presents.
Oscillator Volume Profile [Trendoscopeยฎ]The Oscillator Volume Profile indicator is designed to construct a volume profile based on predefined oscillator levels. It integrates volume data with oscillator readings to offer a unique perspective on market dynamics.
๐ฒ Selectable Oscillators:
Users can select from an array of oscillator options for the basis of the volume profile, including:
Relative Strength Index (RSI)
Chande Momentum Oscillator (CMO)
Center of Gravity (COG)
Money Flow Index (MFI)
Rate of Change (ROC)
Commodity Channel Index (CCI)
Stochastic Oscillator (Stoch)
True Strength Index (TSI)
Williams %R (WPR)
The length parameters - Length, Fast Length, Slow Length allows users to define the period over which the chosen oscillator is calculated, tailoring the sensitivity of the indicator to their trading strategy.
๐ฒ Dynamic Overbought/Oversold Ranges:
This indicator enhances traditional concepts by introducing dynamic overbought and oversold levels. These adaptable thresholds are calculated using various methods, including:
๐ฏ Highest/Lowest Range Method : This method establishes the range based on the highest and lowest values of the oscillator within the last N bars.
๐ฏ Moving Average Range Method : The range is derived from a moving average of the oscillator, providing a smoothed threshold that reflects more recent market conditions.
In addition to these methods, the indicator incorporates a unique 'Sticky Border' feature:
๐ฏ Sticky Border: With this option enabled, the dynamic ranges maintain their levels until the oscillator breaks out of the range. Once a breakout occurs, the levels are recalculated and updated. This mechanism ensures that the borders remain consistent and relevant, only adjusting to significant market movements that warrant a recalculation.
Users can select their preferred method for determining dynamic ranges, allowing for a customized approach that aligns with their analysis and trading strategy. The sticky border feature further refines this functionality, offering continuity until a decisive market move occurs.
๐ฒ Volume Profile Calculation Parameters:
๐ฏ Trend Filter: The indicator provides a versatile trend filter with four selectable options:
Uptrend: The volume profile is calculated when the oscillator indicates an uptrend.
Downtrend: The volume profile is calculated when the oscillator indicates a downtrend.
Any: The volume profile is calculated regardless of the trend.
External: Users can input values from an external indicator. The volume profile is then calculated only when the external indicator's value is non-zero, integrating external analysis into the volume profile construction.
๐ฏ Precision: Users have the option to define the precision for calculating the volume profile, which is crucial due to the varying scales of different oscillators (e.g., some oscillators range from 0 to 100, while others from -1 to 1). Selecting an appropriate precision ensures that the volume profile is accurately aligned with the minimal price range significant to the chosen oscillator. This setting requires user intervention for optimal configuration, as automatic calculation is not feasible due to the diverse nature of oscillator ranges.
๐ฏ Number of Bars: Users can select a specific number of bars for volume profile calculation, or opt to include all available historical bars for a comprehensive profile.
๐ฒ Selecting the right precision:
Users must select the right precision based on their choice of indicator. For example, RSI values range from 0-100. Hence, the default precision of 1 work fine on RSI as the volume profiles are plotted from 0 to 100 at the interval of 0.1
But, the default precision of 1 will not be ok on TSI because TSI values range from -1 to 1. Hence, using 1 as precision will result in very less volume profile lines as shown below.
Due to this, it is necessary to increase the precision for oscillators such as TSI where the range between highest and lowest value is far less. Once we set the precision to 2, we can see more appropriate volume profile division.
๐ฒ Note of thanks:
This publication uses polyline feature for drawing volume profiles. The advantage of using polyline is that we can overcome max 500 lines issue that we face by using the regular line objects. More details of polyline can be found in the tradingview blog post
Further, using polyline for display of volume profiles is inspired by the publications of fikira and KioseffTrading
Non-Psychological Levels๐ฉ Non-Psychological Levels is a structural analysis tool that segments price action into objective ranges, identifying Broken and Unbroken levels without relying on psychological or time-based assumptions. By emphasizing mechanically derived price behavior, it provides traders with a clear framework for analyzing support and resistance in a consistent and unbiased manner across various market conditions.
This indicator introduces a new approach to understanding market structure by focusing on price movement within defined segments, free from behavioral patterns, round numbers, or specific time intervals. While the indicator is time-agnostic in design, it works within the natural time progression of the chart, ensuring that segmentation aligns with the inherent structure of price movement. Broken levels, where price has breached a structural boundary, and Unbroken levels, which remain intact, are visualized with horizontal lines. These structural zones are complemented by dynamically boxed segments that contextualize both historical and ongoing price behavior.
By offering an objective perspective, the Non-Psychological Levels indicator complements psychology-based tools, helping traders explore market dynamics from multiple angles. When structural levels align with psychological zones, they reinforce critical price areas; when they differ, they provide opportunities to analyze price behavior from an alternative lens. This indicator is designed as both an educational framework and a practical tool, encouraging a deeper understanding of structural price behavior in technical analysis.
โญ THEORY AND CONCEPT โญ
The Non-Psychological Levels indicator is grounded in the principle of analyzing price behavior without reliance on psychological assumptions or time-based factors. Its primary purpose is to provide a structural framework for identifying support and resistance levels by focusing solely on price movement within mechanically defined segments. By removing external influences such as sentiment, time intervals, or market sessions, the indicator offers an unbiased lens through which traders can observe price dynamics.
Non-psychology, as defined here, refers to an approach that excludes behavioral and emotional patternsโlike fear, greed, or herd mentalityโfrom price analysis. Traditional tools often depend on these patterns to identify zones such as pivots or Fibonacci retracements, but these methods can be inconsistent in volatile markets. In contrast, the Non-Psychological Levels indicator focuses entirely on what price is doing, free from assumptions about trader behavior or external time constraints.
The indicatorโs time-agnostic and mechanically driven design segments price action into consistent ranges, highlighting "Broken" levels (where price breaches structural boundaries) and "Unbroken" levels (where price holds). These structural zones remain unaffected by subjective or external influences, ensuring clarity and consistency across different markets and timeframes. By doing so, the indicator reveals a pure view of price structure, independent of psychological biases.
Importantly, the Non-Psychological Levels indicator is not intended to replace psychology-based tools but to complement them. When its structural levels align with psychological zones like round numbers or session highs/lows, the significance of these areas is reinforced. Conversely, when the levels differ, the contrast provides traders with alternative insights into market dynamics. This dual perspectiveโblending mechanical objectivity with behavioral analysisโenhances the depth and flexibility of market evaluation.
The following principles outline the theoretical foundation of the indicator and its unique contribution to structural price analysis:
Time-Agnostic Design : The indicator avoids reliance on time-based factors like daily opens, session intervals, or specific events. Instead, it segments price action using bar indexes, ensuring that structural levels are identified independently of external time variables. While the x-axis of a chart inherently represents time, this indicator abstracts away its influence, allowing traders to focus purely on price movement without the bias of temporal context.
Mechanical and Neutral Framework : Every calculation within the indicator is predetermined by a set of mechanical rules, ensuring no subjective input or interpretation affects the results. This objectivity guarantees that levels are derived solely from observed price behavior, providing a reliable framework that traders can trust to remain consistent across different assets, timeframes, and market conditions.
Broken and Unbroken Levels : Broken levels represent zones where price has breached a structural boundary, while Unbroken levels highlight areas where price has consistently respected its range. This distinction provides a clear and systematic method for identifying key support and resistance levels, offering insights into where future price interactions are most likely to occur.
Neutral Price Behavior : By dividing price action into equal segments, the indicator removes the influence of external factors like trader sentiment or psychological expectations. Each segment independently determines significant levels based purely on price action, enabling a structural view of the market that abstracts away behavioral or emotional biases.
Complement to Psychological Tools : While the indicator itself avoids behavioral assumptions, its levels can align with psychological zones like round numbers, pivots, or Fibonacci levels. When these structural and psychological levels overlap, it reinforces the importance of key areas, while divergences offer opportunities to examine price behavior from a new perspective.
Educational Value : The indicator encourages traders to explore the contrast between structural and psychological analysis. By introducing a framework that isolates price behavior from external influences, it challenges traditional methods of technical analysis, fostering deeper insights into market structure and behavior.
๐ UNDERSTANDING STRUCTURAL LEVELS ๐
The Non-Psychological Levels indicator offers a straightforward yet powerful way to understand market structure by segmenting price action into mechanically defined ranges. This segmentation highlights two key elements: "Broken" levels, where price has breached structural boundaries, and "Unbroken" levels, which remain intact and respected by price action. Together, these components create a framework for identifying potential areas of support and resistance.
Broken Levels : These are structural boundaries that price has surpassed, indicating areas where previous support or resistance failed. Broken levels often signal transitions in price behavior, such as shifts in momentum or the start of trending movements. They provide insight into zones where price has already tested and moved beyond.
Unbroken Levels : These levels remain intact within a given price segment, marking areas where price has consistently respected boundaries. Unbroken levels are particularly useful for identifying potential reversal points or zones of continued support or resistance. Their persistence across price action often makes them reliable indicators of market structure.
The visual segmentation of price action into distinct ranges allows traders to observe how price transitions between structural zones. For example:
- Clusters of Unbroken levels near the current price may suggest strong support or resistance, offering areas of interest for reversals or breakouts.
- Gaps between Unbroken levels highlight areas of price inefficiency or low interaction, which may become significant if revisited.
By focusing solely on structural price behavior, the Non-Psychological Levels indicator enables traders to analyze price independently of time or psychological factors. This makes it a valuable tool for understanding price dynamics objectively, whether used on its own or alongside other indicators.
๐ ๏ธ SETTINGS ๐ ๏ธ
The Non-Psychological Levels indicator offers various customizable settings to help users tailor its visualization to their specific trading style and market conditions. These settings allow adjustments to sensitivity, level projection, and the source of price calculations (e.g., wicks or closing prices). Below, we outline each setting and its impact on the chart, along with examples to illustrate their functionality.
Custom Settings
Sensitivity : This setting adjusts the balance between detailed and broader structural levels by controlling the number of segments. Higher values result in more segments, revealing finer price levels, while lower values consolidate segments to highlight major price movements.
Source : Allows the user to choose between 'Wick' or 'Close' for detecting levels. Selecting 'Wick' emphasizes the absolute highs and lows of price action, while 'Close' focuses on closing prices within each segment.
Level Labels : Configures the visual representation of price levels, allowing users to toggle between price values, symbols (โฒ โผ), or disabling labels altogether. This setting ensures clarity in how Broken and Unbroken levels are displayed on the chart.
Unbroken Levels : - - - Users can customize the colors and label styles for Unbroken levels, which highlight areas where price has respected structural boundaries.
Broken Levels : -|- Similar to Unbroken levels, users can specify the visual appearance of Broken levels, including color customization for Broken highs and lows. These settings help distinguish areas where price has breached a structural boundary.
Projection Options : This setting allows users to control how broken and unbroken levels are visually extended on the chart. The Future option projects lines forward to the right of the current price, showing potential future relevance of levels. The All option extends lines both forward and backward, providing a comprehensive view of how levels align with historical and potential future price action. The None option disables projections, keeping the chart focused solely on current segment levels without any extensions.
Segments : Includes options for customizing the segment visualization:
- Live Segment : Toggles the display of a highlighted box representing the current developing segment, helping users focus on ongoing price action.
- Boxes : Allows users to display filled boxes around each segment for additional visual emphasis.
- Segment Colors : Users can define separate colors for support (lower) and resistance (upper) segments, making it easier to interpret directional trends.
- Boundaries : Enables or disables vertical lines to mark segment boundaries, providing a clearer view of structural divisions.
Repaint : This setting allows users to enable or disable triangle labels within the live segment. When enabled, the triangles dynamically update to reflect real-time price behavior during the live bar but will repaint until the bar is fully confirmed. Disabling this option prevents the triangles from appearing during the live bar, reducing potential confusion as they may otherwise flash on and off during price updates. This setting ensures users can choose their preferred visualization while maintaining clarity in real-time analysis.
Color Settings : Offers extensive customization for all visual elements, including Broken and Unbroken levels, segment boundaries, and live segments. These settings ensure the indicator can adapt to individual preferences for chart readability.
๐ผ๏ธ CHART EXAMPLES ๐ผ๏ธ
The following chart examples illustrate different configurations and features of the Non-Psychological Levels indicator. These examples highlight how the indicatorโs settings influence the visualization of structural price behavior, helping traders understand its functionality in various scenarios.
Broken and Unbroken Levels : Orange prices are Broken HIghs. Blue prices are Broken Lows. Green and Red are Unbroken.
Boundaries : Enable Boundaries to visualize segments.
High Sensitivity Setting : A high sensitivity setting produces fewer segments and levels, emphasizing broader price ranges and major structural zones. This configuration is better suited for higher timeframes or identifying overarching trends.
Low Sensitivity Setting : A low sensitivity setting results in a greater number of segments and levels, offering a granular view of price structure. This configuration is ideal for analyzing detailed price movements on lower timeframes.
Live Segment with Triangles Enabled : This example shows the live segment box with triangle labels enabled. These triangles update dynamically during the live bar but may repaint until the bar is confirmed, helping traders observe real-time price behavior.
Broken and Unbroken Levels : This example highlights Broken levels (where price has breached structural boundaries and are drawn through subsequent price action) and Unbroken levels (where price has respected structural boundaries). These distinctions visually identify areas of potential support and resistance.
Broken and Unbroken Levels with Projection: All : This example demonstrates the "Project All" feature, where broken and unbroken levels are extended both forward and backward on the chart. This visualization highlights historical and potential future support and resistance zones, helping traders better understand how price interacts with these structural levels over time.
Segment Boxes with Boundaries : Filled boxes around individual segments visually distinguish each price interval, offering clarity in observing structural price transitions.
๐ SUMMARY ๐
The Non-Psychological Levels indicator provides a unique framework for analyzing structural price behavior through the identification of Broken and Unbroken levels. These levels act as a mechanical representation of support and resistance, independent of psychological biases or time-based factors. By focusing purely on price movement within defined segments, the indicator offers a neutral and consistent approach to understanding market dynamics.
This method complements traditional tools by providing an unbiased perspective. When structural levels align with psychological zonesโsuch as round numbers or session-based highs and lowsโthey reinforce the significance of these areas as key price zones. When they diverge, the indicator introduces an alternative view, prompting further exploration of price behavior. This dual perspective enhances the depth of analysis by combining the mechanical and behavioral aspects of price action.
The Non-Psychological Levels indicator is not designed to generate trading signals or predict future price movements but serves as a visual and educational tool. Its adaptability across all markets and timeframes allows traders to integrate it into their broader strategies. By highlighting structural price dynamics, the indicator offers a fresh perspective on market analysis while remaining compatible with other technical tools.
โ๏ธ COMPATIBILITY AND LIMITATIONS โ๏ธ
Asset Compatibility :
The Non-Psychological Levels indicator is compatible with all asset classes, including cryptocurrencies, forex, stocks, and commodities. It can be applied to any chart or timeframe, making it a flexible tool for structural price analysis. Users should adjust the Sensitivity setting to ensure the segmentation aligns with the price behavior of the specific asset being analyzed. For instance, higher sensitivity values are more suitable for assets with large price ranges, while lower values work well for assets with tighter ranges.
Visual Range Dependency :
The indicator is optimized to perform calculations only within the visible range of the chart. This is a significant advantage, as it prevents unnecessary calculations and maintains efficient performance. However, because of this dependency, levels may appear to "recalculate" when the chart is zoomed in or out quickly or shifted abruptly. While this does not affect the integrity of the levels, it may cause a temporary lag as the indicator adjusts to the new visual range.
Persistence of Levels Beyond Visibility :
Even if levels are not visible on the chart due to zoom or scroll settings, they still exist in the background and are recalculated when revisited. This ensures that the structural price analysis remains consistent, regardless of the chart view.
Box Limitations in Pine Script :
The indicator is subject to Pine Script's inherent limitation of 500 boxes. This means that no more than 500 segments or level boxes can be drawn on the chart simultaneously. For most configurations, this limitation is mitigated by focusing on the visual range, but users employing very low sensitivity settings may exceed the limit. In such cases, only the most recent 500 boxes will be displayed, potentially omitting earlier segments.
Lag with Low Sensitivity Settings :
When sensitivity is set to a low value, the indicator creates many more segments, resulting in finer granularity and a higher number of boxes. While this provides detailed structural levels, it may increase the likelihood of exceeding Pine Scriptโs 500-box limit or cause a temporary lag when rendering a dense set of boxes over a wide visual range. Users should adjust sensitivity to balance detail with performance, especially on assets with high volatility or broad price ranges.
Live Segment Caution :
The live segment box updates in real time to reflect price movements as the segment is still developing. Since the segment high and segment low are not yet finalized, users should interpret this feature as a dynamic visualization of current price behavior rather than a definitive structural analysis. This ensures clarity during ongoing price action while maintaining the integrity of the indicator's framework.
Cross-Market Versatility :
The indicatorโs time-agnostic and mechanical design ensures that it functions identically across all markets and timeframes. However, users should consider the unique characteristics of different markets when interpreting the results, as certain assets (e.g., highly volatile cryptocurrencies) may require sensitivity adjustments for optimal segmentation.
Visual Range Dependency: Levels recalculate efficiently within the chart's visible range but may lag temporarily when zooming or scrolling quickly.
These considerations ensure that the Non-Psychological Levels indicator remains robust and versatile while highlighting some inherent limitations of Pine Script and real-time recalculations. Users can mitigate these constraints by carefully adjusting sensitivity and understanding how the visual range dependency affects performance.
โ ๏ธ DISCLAIMER โ ๏ธ
The Non-Psychological Levels indicator is a visual analysis tool and is not designed as a predictive or trading signal indicator. Its primary purpose is to highlight structural price levels, providing an objective framework for understanding support and resistance within mechanically segmented price action.
The indicator operates within the visible range of the chart to ensure efficiency and adaptiveness, but this recalculation should not be interpreted as a forecast of future price behavior. While the structural levels may align with significant price zones in hindsight, they are purely a reflection of observed price dynamics and should not be used as standalone trading signals.
This indicator is intended as an educational and visual aid to complement other analysis methods. Users are encouraged to integrate it into a broader trading strategy and make adjustments to the settings based on their individual needs and market conditions.
๐ง BEYOND THE CODE ๐ง
The Non-Psychological Levels indicator, like other xxattaxx indicators , is designed with education and community collaboration in mind. Its open-source nature encourages exploration, experimentation, and the development of new approaches to price analysis. By focusing on structural price behavior rather than psychological or time-based factors, this indicator introduces a fresh perspective for users to study.
Beyond its visual utility, the indicator serves as an educational framework for understanding the concept of non-psychological analysis. It offers traders an opportunity to explore price dynamics in a purely mechanical way, challenging conventional methods and fostering deeper insights into structural behavior. This approach is especially valuable for those interested in exploring new concepts or seeking alternative perspectives on market analysis.
Your comments, suggestions, and discussions are invaluable in shaping the future of this project. We actively encourage your feedback and contributions, which will directly help us refine and improve the Non-Psychological Levels indicator. We look forward to seeing the creative ways in which you use and enhance this tool. MVS
GIGANEVA V6.61 PublicThis enhanced Fibonacci script for TradingView is a powerful, all-in-one tool that calculates Fibonacci Levels, Fans, Time Pivots, and Golden Pivots on both logarithmic and linear scales. Its ability to compute time pivots via fan intersections and Range interactions, combined with user-friendly features like Bool Fib Right, sets it apart. The script maximizes TradingViewโs plotting capabilities, making it a unique and versatile tool for technical analysis across various markets.
1. Overview of the Script
The script appears to be a custom technical analysis tool built for TradingView, improving upon an existing script from TradingViewโs Community Scripts. It calculates and plots:
Fibonacci Levels: Standard retracement levels (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range.
Fibonacci Fans: Trendlines drawn from a high or low point, radiating at Fibonacci ratios to project potential support/resistance zones.
Time Pivots: Points in time where significant price action is expected, determined by the intersection of Fibonacci Fans or their interaction with key price levels.
Golden Pivots: Specific time pivots calculated when the 0.5 Fibonacci Fan (on a logarithmic or linear scale) intersects with its counterpart.
The script supports both logarithmic and linear price scales, ensuring versatility across different charting preferences. It also includes a feature to extend Fibonacci Fans to the right, regardless of whether the user selects the top or bottom of the range first.
2. Key Components Explained
a) Fibonacci Levels and Fans from Top and Bottom of the "Range"
Fibonacci Levels: These are horizontal lines plotted at standard Fibonacci retracement ratios (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range (the "Range"). The Range is typically the distance between a significant high (top) and low (bottom) on the chart.
Example: If the high is $100 and the low is $50, the 0.618 retracement level would be at $80.90 ($50 + 0.618 ร $50).
Fibonacci Fans: These are diagonal lines drawn from either the top or bottom of the Range, radiating at Fibonacci ratios (e.g., 0.382, 0.5, 0.618). They project potential dynamic support or resistance zones as price evolves over time.
From Top: Fans drawn downward from the high of the Range.
From Bottom: Fans drawn upward from the low of the Range.
Log and Linear Scale:
Logarithmic Scale: Adjusts price intervals to account for percentage changes, which is useful for assets with large price ranges (e.g., cryptocurrencies or stocks with exponential growth). Fibonacci calculations on a log scale ensure ratios are proportional to percentage moves.
Linear Scale: Uses absolute price differences, suitable for assets with smaller, more stable price ranges.
The scriptโs ability to plot on both scales makes it adaptable to different markets and user preferences.
b) Time Pivots
Time pivots are points in time where significant price action (e.g., reversals, breakouts) is anticipated. The script calculates these in two ways:
Fans Crossing Each Other:
When two Fibonacci Fans (e.g., one from the top and one from the bottom) intersect, their crossing point represents a potential time pivot. This is because the intersection indicates a convergence of dynamic support/resistance zones, increasing the likelihood of a price reaction.
Example: A 0.618 fan from the top crosses a 0.382 fan from the bottom at a specific bar on the chart, marking that bar as a time pivot.
Fans Crossing Top and Bottom of the Range:
A fan line (e.g., 0.5 fan from the bottom) may intersect the top or bottom price level of the Range at a specific time. This intersection highlights a moment where the fanโs projected support/resistance aligns with a key price level, signaling a potential pivot.
Example: The 0.618 fan from the bottom reaches the top of the Range ($100) at bar 50, marking bar 50 as a time pivot.
c) Golden Pivots
Definition: Golden pivots are a special type of time pivot calculated when the 0.5 Fibonacci Fan on one scale (logarithmic or linear) intersects with the 0.5 fan on the opposite scale (or vice versa).
Significance: The 0.5 level is the midpoint of the Fibonacci sequence and often acts as a critical balance point in price action. When fans at this level cross, it suggests a high-probability moment for a price reversal or significant move.
Example: If the 0.5 fan on a logarithmic scale (drawn from the bottom) crosses the 0.5 fan on a linear scale (drawn from the top) at bar 100, this intersection is labeled a "Golden Pivot" due to its confluence of key Fibonacci levels.
d) Bool Fib Right
This is a user-configurable setting (a boolean input in the script) that extends Fibonacci Fans to the right side of the chart.
Functionality: When enabled, the fans project forward in time, regardless of whether the user selected the top or bottom of the Range first. This ensures consistency in visualization, as the direction of the Range selection (top-to-bottom or bottom-to-top) does not affect the fanโs extension.
Use Case: Traders can use this to project future support/resistance zones without worrying about how they defined the Range, improving usability.
3. Why Is This Code Unique?
Original calculation of Log levels were taken from zekicanozkanli code. Thank you for giving me great Foundation, later modified and applied to Fib fans. The scriptโs uniqueness stems from its comprehensive integration of Fibonacci-based tools and its optimization for TradingViewโs plotting capabilities. Hereโs a detailed breakdown:
All-in-One Fibonacci Tool:
Most Fibonacci scripts on TradingView focus on either retracement levels, extensions, or fans.
This script combines:
Fibonacci Levels: Static horizontal lines for retracement and extension.
Fibonacci Fans: Dynamic trendlines for projecting support/resistance.
Time Pivots: Temporal analysis based on fan intersections and Range interactions.
Golden Pivots: Specialized pivots based on 0.5 fan confluences.
By integrating these functions, the script provides a holistic Fibonacci analysis tool, reducing the need for multiple scripts.
Log and Linear Scale Support:
Many Fibonacci tools are designed for linear scales only, which can distort projections for assets with exponential price movements. By supporting both logarithmic and linear scales, the script caters to a wider range of markets (e.g., stocks, forex, crypto) and user preferences.
Time Pivot Calculations:
Calculating time pivots based on fan intersections and Range interactions is a novel feature. Most TradingView scripts focus on price-based Fibonacci levels, not temporal analysis. This adds a predictive element, helping traders anticipate when significant price action might occur.
Golden Pivot Innovation:
The concept of "Golden Pivots" (0.5 fan intersections across scales) is a unique addition. It leverages the symmetry of the 0.5 level and the differences between log and linear scales to identify high-probability pivot points.
Maximized Plot Capabilities:
TradingView imposes limits on the number of plots (lines, labels, etc.) a script can render. This script is coded to fully utilize these limits, ensuring that all Fibonacci levels, fans, pivots, and labels are plotted without exceeding TradingViewโs constraints.
This optimization likely involves efficient use of arrays, loops, and conditional plotting to manage resources while delivering a rich visual output.
User-Friendly Features:
The Bool Fib Right option simplifies fan projection, making the tool intuitive even for users who may not consistently select the Range in the same order.
The scriptโs flexibility in handling top/bottom Range selection enhances usability.
4. Potential Use Cases
Trend Analysis: Traders can use Fibonacci Fans to identify dynamic support/resistance zones in trending markets.
Reversal Trading: Time pivots and Golden Pivots help pinpoint moments for potential price reversals.
Range Trading: Fibonacci Levels provide key price zones for trading within a defined range.
Cross-Market Application: Log/linear scale support makes the script suitable for stocks, forex, commodities, and cryptocurrencies.
The original code was from zekicanozkanli . Thank you for giving me great Foundation.
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.
Anchored Darvas Box## ANCHORED DARVAS BOX
---
### OVERVIEW
**Anchored Darvas Box** lets you drop a single timestamp on your chart and build a Darvas-style consolidation zone forward from that exact candle. The indicator freezes the first user-defined number of bars to establish the range, verifies that price respects that range for another user-defined number of bars, then waits for the first decisive breakout. The resulting rectangle captures every tick of the accumulation phase and the exact moment of expansionโno manual drawing, complete timestamp precision.
---
### HISTORICAL BACKGROUND
Nicolas Darvasโs 1950s box theory tracked institutional accumulation by hand-drawing rectangles around tight price ranges. A trade was triggered only when price escaped the rectangle.
The anchored version preserves Darvasโs logic but pins the entire sequence to a user-chosen candle: perfect for analysing a market open, an earnings release, FOMC minute, or any other catalytic bar.
---
### ALGORITHM DETAIL
1. **ANCHOR BAR**
*You provide a timestamp via the settings panel.* The script waits until the chart reaches that bar and records its index as **startBar**.
2. **RANGE DEFINITION โ BARS 1-7**
โข `rangeHigh` = highest high of bars 1-7 plus optional tolerance.
โข `rangeLow` = lowest low of bars 1-7 minus optional tolerance.
3. **RANGE VALIDATION โ BARS 8-14**
โข Price must stay inside ` `.
โข Any violation aborts the test; no box is created.
4. **ARMED STATE**
โข If bars 8-14 hold the range, two live guide-lines appear:
โ **Green** at `rangeHigh`
โ **Red** at `rangeLow`
โข The script is now โarmed,โ waiting indefinitely for the first true breakout.
5. **BREAKOUT & BOX CREATION**
โข **Up breakout** =`high > rangeHigh`โโ rectangle drawn in **green**.
โข **Down breakout**=`low < rangeLow`โโ rectangle drawn in **red**.
โข Box extends from **startBar** to the breakout bar and never updates again.
โข Optional labels print the dollar and percentage height of the box at its left edge.
6. **OPTIONAL COOLDOWN**
โข After the box is painted the script can stay silent for a user-defined number of bars, letting you study the fallout without another range immediately arming on top of it.
---
### INPUT PARAMETERS
โข **ANCHOR TIME** โ Precise yyyy-mm-dd HH:MM:SS that seeds the sequence.
โข **BARS TO DEFINE RANGE** โ Default 7; affects both definition and validation windows.
โข **OPTIONAL TOLERANCE** โ Absolute price buffer to ignore micro-wicks.
โข **COOLDOWN BARS AFTER BREAKOUT** โ Pause length before the indicator is allowed to re-anchor (set to zero to disable).
โข **SHOW BOX DISTANCE LABELS** โ Toggle to print ฮ\$ and ฮ% on every completed box.
---
### USER WORKFLOW
1. Add the indicator, open settings, and set **ANCHOR TIME** to the candle you care about (e.g., โ2025-04-23 09:30:00โ for NYSE open).
2. Watch live as the script:
โ Paints the seven-bar range.
โ Draws validation lines.
โ Locks in the box on breakout.
3. Use the box boundaries as structural stops, targets, or context for further trades.
---
### PRACTICAL APPLICATIONS
โข **OPENING RANGE BREAKOUTS** โ Anchor at the first second of the session; capture the initial 7-bar range and trade the first clean break.
โข **EVENT STUDIES** โ Anchor at a news candle to measure immediate post-event volatility.
โข **VOLUME PROFILE FUSION** โ Combine the anchored box with VPVR to see if the breakout occurs at a high-volume node or a low-liquidity pocket.
โข **RISK DISCIPLINE** โ Stop-loss can sit just inside the opposite edge of the anchored range, enforcing objective risk.
---
### ADVANCED CUSTOMISATION IDEAS
โข **MULTIPLE ANCHORS** โ Clone the indicator and anchor several boxes (e.g., London open, New York open).
โข **DYNAMIC WINDOW** โ Switch the 7-bar fixed length to a volatility-scaled length (ATR percentile).
โข **STRATEGY WRAPPER** โ Turn the indicator into a `strategy{}` script and back-test anchored boxes on decades of data.
---
### FINAL THOUGHTS
Anchored Darvas Boxes give you Darvasโs timeless range-break methodology anchored to any candle of interestโperfect for dissecting openings, economic releases, or your own bespoke โimportantโ bars with laboratory precision.
Statistics plot1. setting the price range
At the beginning of the script, set the price range (interval). Price ranges are used to divide prices into several groups (buckets) and record how many prices have been reached within each group. For example, setting the price range to โ10โ will divide the price into intervals 0-10, 10-20, 20-30, and so on.
The price range can also be set manually by the user or automatically calculated based on the initial price. This allows for flexibility in adjusting price ranges for different assets and different time frames.
2. aggregate the number of times a price is reached
Record how many times the price reached each price range (e.g., 100-110, 110-120, etc.). This aggregate data is stored in a data structure called an array.
Each element of the array corresponds to a price range, and when a price reaches that range, the corresponding array value is incremented by one. This process is performed in real time, tracking price movements.
3. initializing and extending price ranges
The first bar of the script (when the chart is first loaded) divides the price ranges into several groups and initializes a count of 0 for each range.
When a price reaches a new range, the array is expanded as needed to add the new price range. This allows the script to work with any price movement, even if the price range continues to grow.
4. visualize the number of price arrivals with a histogram
The aggregated number of arrivals per price range is visually displayed in the form of a histogram. This histogram is designed to allow the user to see at a glance which price range is being reached most frequently.
For example, if prices frequently reach the 100-110 range, the histogram bar corresponding to that range will appear higher than the other ranges. This allows you to visually identify price โdwell pointsโ or support and resistance levels.
5. display of moving averages
A moving average (MA) of the number of times a price has been reached is drawn above the histogram. Moving averages are indicators that show a smooth trend for the number of price arrivals and are useful for understanding the overall direction of price movements.
The duration of the moving average (how many data points it is calculated based on) can be set by the user. This allows for flexible analysis of short or long term price trends. 6.
6. price range tracking and labeling
The script keeps track of which price range the current price is located in. Based on this, information related to the current price range is displayed on the chart as labels.
In particular, labels indicate the beginning and end points of the price range, including which range the price was in at the beginning and which range the price reached at the end. These labels are a useful feature to visually identify price ranges on the chart.
7. labeling of current price range
To confirm which price range the current price is in, when a price reaches a specific price range, a label corresponding to that price range is displayed. This label indicates the position of the price in real-time, allowing traders to visually track where the current price is in the area.
8. calculating the start and end points of the range
The script calculates the start and end points of a range with a non-zero number of price arrivals to find the minimum and maximum of the range. This calculation allows you to see where prices are concentrated within a range.
9. out-of-range price processing
When a price reaches outside the range, the script automatically adds the array element corresponding to that price range and inserts the data in the appropriate location for the count. This allows the script to follow the price as it moves unexpectedly.
Filt ADR๐ Script Name: Filtered Average Daily Range (Filt ADR)
This script calculates a filtered version of the Average Daily Range (ADR) based on the last 14 daily candles. It's designed to reduce the influence of unusually high or low daily ranges (outliers) by applying a filter before calculating the average.
๐ง How It Works โ Step by Step
1. Calculate Daily Ranges (High - Low)
It retrieves the daily price ranges (difference between daily high and low) for the last 14 days using request.security() with the "D" (daily) timeframe.
pinescript
ะะพะฟะธัะพะฒะฐัั
ะ ะตะดะฐะบัะธัะพะฒะฐัั
high - low // today's daily range
high - low // yesterday's daily range
...
These values are stored into individual variables dr0 to dr13.
2. Build an Array of Daily Ranges
An array named ranges is used to store the 14 daily ranges, but only if they are not na (missing data). This avoids errors during processing.
3. Calculate the Initial (Unfiltered) Average Range
The script sums all values in the ranges array and calculates their average:
pinescript
ะะพะฟะธัะพะฒะฐัั
ะ ะตะดะฐะบัะธัะพะฒะฐัั
avg_all = total sum of ranges / number of valid entries
4. Filter Out Outliers
Now it filters the values in ranges:
Only keeps the ranges that are between 0.5รavg_all and 2รavg_all.
This is to remove abnormally small or large daily ranges that could distort the average.
The filtered values are added to a second array called filtered.
5. Calculate the Filtered ADR
Finally, it calculates the average of the filtered daily ranges:
pinescript
ะะพะฟะธัะพะฒะฐัั
ะ ะตะดะฐะบัะธัะพะฒะฐัั
avg_filt = sum of filtered ranges / number of filtered values
This is the Filtered ADR.
6. Plot the Result
The result (avg_filt) is plotted as an orange line on the chart. It updates on each bar (depending on the current timeframe you're viewing) but the underlying data is based on the last 14 daily candles.
pinescript
ะะพะฟะธัะพะฒะฐัั
ะ ะตะดะฐะบัะธัะพะฒะฐัั
plot(avg_filt, title="Filtered ADR", color=color.orange, linewidth=2)
โ
Use Case
This script is useful for traders who use the Average Daily Range (ADR) to:
Estimate expected price movement during a day
Set volatility-based stop-loss or take-profit levels
Identify days with unusually high or low volatility
By filtering out extreme values, it provides a more stable and reliable estimate of daily volatility.
OHLCVRangeXThe OHLCVRange library provides modular range-building utilities for Pine Script v6 based on custom conditions like time, price, volatility, volume, and pattern detection. Each function updates a persistent range (OHLCVRange) passed in from the calling script, based on live streaming candles.
This library is designed to support dynamic windowing over incoming OHLCV bars, with all persistent state handled externally (in the indicator or strategy). The library merely acts as a filter and updater, appending or clearing candles according to custom logic.
๐ฆ
export type OHLCVRange
OHLCV.OHLCV candles // Sliding window of candles
The OHLCVRange is a simple container holding an array of OHLCV.OHLCV structures.
This structure should be declared in the indicator using var to ensure persistence across candles.
๐งฉ Range Updater Functions
Each function follows this pattern:
export updateXxxRange(OHLCVRange r, OHLCV.OHLCV current, ...)
r is the range to update.
current is the latest OHLCV candle (typically from your indicator).
Additional parameters control the behavior of the range filter.
๐ Function List
1. Fixed Lookback Range
export updateFixedRange(OHLCVRange r, OHLCV.OHLCV current, int barsBack)
Keeps only the last barsBack candles.
Sliding window based purely on number of bars.
2. Session Time Range
export updateSessionRange(OHLCVRange r, OHLCV.OHLCV current, int minuteStart, int minuteEnd)
Keeps candles within the [minuteStart, minuteEnd) intraday session.
Clears the range once out of session bounds.
3. Price Zone Range
export updatePriceZoneRange(OHLCVRange r, OHLCV.OHLCV current, float minP, float maxP)
Retains candles within the vertical price zone .
Clears when a candle exits the zone.
4. Consolidation Range
export updateConsolidationRange(OHLCVRange r, OHLCV.OHLCV current, float thresh)
Stores candles as long as the candle range (high - low) is less than or equal to thresh.
Clears on volatility breakout.
5. Volume Spike Range
export updateVolumeSpikeRange(OHLCVRange r, OHLCV.OHLCV current, float avgVol, float mult, int surround)
Triggers a new range when a volume spike โฅ avgVol * mult occurs.
Adds candles around the spike (total surround * 2 + 1).
Can be used to zoom in around anomalies.
6. Engulfing Pattern Range
export updateEngulfingRange(OHLCVRange r, OHLCV.OHLCV current, int windowAround)
Detects bullish or bearish engulfing candles.
Stores 2 * windowAround + 1 candles centered around the pattern.
Clears if no valid engulfing pattern is found.
7. HTF-Aligned Range
export updateHTFAlignedRange(OHLCVRange r, OHLCV.OHLCV current, OHLCV.OHLCV prevHtf)
Used when aligning lower timeframe candles to higher timeframe bars.
Clears and restarts the range on HTF bar transition (compare prevHtf.bar_index with current).
Requires external management of HTF candle state.
๐ก Usage Notes
All OHLCVRange instances should be declared as var in the indicator to preserve state:
var OHLCVRange sessionRange = OHLCVRange.new()
sessionRange := OHLCVRange.updateSessionRange(sessionRange, current, 540, 900)
All OHLCV data should come from the OHLCVData library (v15 or later):
import userId/OHLCVData/15 as OHLCV
OHLCV.OHLCV current = OHLCV.getCurrentChartOHLCV()
This library does not use var internally to enforce clean separation of logic and persistence.
๐
Planned Enhancements
Fib zone ranges: capture candles within custom Fibonacci levels.
Custom event ranges: combine multiple filters (e.g., pattern + volume spike).
Trend-based ranges: windowing based on moving average or trend breaks.
Consolidation indicatorโโ Overview
The "Consolidation Indicator" is a custom indicator for TradingView designed to identify consolidation periods in the price chart. Consolidation typically occurs when the price of an asset moves within a narrow range, and this indicator helps traders recognize such conditions. It can be a useful tool for traders looking to identify potential breakouts or periods of reduced volatility.
โโ Indicator Settings
1 โ Timeframe: This setting allows you to select the timeframe for which you want to analyze consolidation. You can choose from various timeframes available in TradingView.
2 โ Price Smoothing Length: This parameter controls the smoothing of price data. You can adjust the value, with a minimum of 1, to control the level of smoothing applied to the price data.
3 โ Average Range Length (range_len): This setting defines the length of the average range used in the calculation of the indicator. By default, it is set to 14.
4 โ Threshold for Narrow Range (NR_threshold): The indicator will consider a price range as narrow if it falls below this threshold as a percentage of the average range. It is set to 80% by default.
5 โ Consecutive Narrow Ranges for Consolidation: This parameter allows you to specify how many consecutive narrow price ranges are required to confirm a consolidation period. The default value is 3.
6 โ Candle Color: You can choose the color for the consolidation candles. The default is a bright green color.
โโ Indicator Output
The indicator visually displays consolidation and breakout periods on the price chart using colored candles and breakout icons.
โข Candles: During a consolidation period, the indicator colorizes the candles in a specified color (default is green) with a transparency that decreases as the number of consecutive narrow ranges increases. This allows you to easily spot consolidation periods on the chart.
โข Breakout Icons: The indicator also places a breakout icon (๐ฅ) below the price chart to indicate potential breakout opportunities. When a breakout condition is met, the icon appears with an orange color.
โโ Alerts
The indicator provides two alert conditions:
1 โ Consolidation Begins: This alert triggers when a consolidation period starts. It indicates that the price is moving within a narrow range compared to the average range.
2 โ Breakout: This alert triggers when a potential breakout from the consolidation is detected.
โโ How to Use
1 โ Apply the "Consolidation Indicator" to your TradingView chart by adding it as a custom indicator.
2 โ Customize the indicator settings based on your trading preferences, such as timeframe, smoothing length, and threshold for a narrow range.
3 โ Monitor the chart for colored candles. The indicator will color candles to highlight consolidation periods.
4 โ Look for the breakout icon (๐ฅ) below the chart, which indicates potential breakout opportunities.
5 โ Set up alerts to be notified when a consolidation begins or a breakout is detected, helping you stay on top of potential trading opportunities.
Keep in mind that this indicator is a tool to assist in identifying consolidation periods, and it should be used in conjunction with other analysis methods for comprehensive trading decisions.
ka66: ADR EstimationThis is based on Daryl Guppy's Average Daily Range indicator, the link is difficult to find, but it is an estimation/projection indicator for a daily range.
The thesis is (if I understand correctly):
The range (high - low) of a particular day can be determined, with 85% probability, by taking the ranges of the last 5 days, and getting their average, then multiplying this average value by 0.75. This final value is the estimated range for the next day.
The indicator does not say anything about potential direction, so it may be used as a Take Profit or Stop Loss estimator for the trading strategy in use. Either on the daily timeframe, or an intraday timeframe.
And if we enter the market intraday for a day trade, when the day's range has already exceeded or is close to exceeding the estimated/projected value, perhaps the move is already quite exhausted, and the trade needs to be reconsidered.
A further implication is: if 0.75 multiple occurs with 85% probability, then a lower multiple is even more probable, if one was looking for a more conservative estimate.
The indicator shows three things for a visual inspection of the validity of this concept (and allows basic customisation of parameters):
The day's range, shown in a translucent gray/deep green, as columns. This is the current bar's range. If intraday, it will repaint.
The 5 day average up to the current bar, shown as a step-line plot in orange. If intraday, it will repaint.
The projected range: a thinner blue histogram column, this is offset one bar forward, as it is a future estimate/forward-looking. It too will repaint if the current day is still not complete.
To evaluate the historical results of the chosen settings visually (eye-ball it!), compare the blue histogram bar to the gray bar/column, i.e. the estimate vs. actual range:
When the blue bar is generally within the gray column, and close enough to that column's size/range, then the projected estimation has been reasonable.
if the blue bar tends to be relatively smaller than the gray bar, then we are underestimating often. Increase the projection multiple setting, as a simple fix.
if the blue bar tends to exceed the range of the gray bar a lot, we are overestimating often. Lower the projection multiple setting, as a simple fix.
Guppy's document says that they basically calculate this ADR for multiple markets and focus on markets with the top 5 ranges (in descending order, of course), to maximise the profit potential on intraday trades planned for the next day. Because it is an estimation, this calculation can be run at the end of the day on completed bars.
This indicator also allows displaying the value as percentages, taking the logic of the ATR% (ATR Percent) indicator, which divides the ATR by the close value and multiplies it by 100 to get a normalised percentage value, allowing it to be compared across markets (but in the same timeframe!).
Charan_Trading_IndicatorCharan_Trading_Indicator Overview:
The Charan_Trading_Indicator combines several technical analysis tools, including Bollinger Bands, RSI (Relative Strength Index), VWAP (Volume-Weighted Average Price), and ATR (Average True Range), to provide buy and sell signals. The script incorporates multiple strategies, such as crack snap setups, overbought/oversold levels, and trend continuation indicators, all tailored for precise market entry and exit points.
Key Components:
RSI (Relative Strength Index):
The indicator uses RSI to detect overbought (RSI > 70) and oversold (RSI < 30) market conditions.
Alerts are triggered when prices are within the specified buy/sell range and RSI crosses these thresholds.
Bollinger Bands:
Bollinger Bands are calculated based on a configurable moving average and standard deviation.
The script identifies potential buy signals when the price dips below the lower Bollinger Band and recovers, and sell signals when the price exceeds the upper Bollinger Band and retraces.
Crack Snap Strategies:
The indicator incorporates multiple variations of the crack snap strategy:
Buy Signals: Triggered when price opens below the lower Bollinger Band and closes above it, alongside certain conditions in previous candles.
Sell Signals: Triggered when price opens above the upper Bollinger Band and closes below it, with similar candle patterns.
Variations such as 3-candle (3C) and 4-candle (4C) versions refine the crack snap setups for more robust signals.
Isolated Candle Conditions:
The indicator tracks isolated candles, where the entire candle lies above or below the Bollinger Bands, to identify potential reversal points.
Trend Continuation Signals:
Conditions based on the candle range and previous highs/lows allow the indicator to generate signals for trend continuation:
Buy signals when price breaks above the previous two highs.
Sell signals when price breaks below the previous two lows.
VWAP (Volume-Weighted Average Price):
The indicator integrates VWAP to give additional support and resistance levels, ensuring signals align with volume trends.
ATR-Based Stop Loss:
For both buy and sell conditions, the script plots stop-loss levels based on the ATR (Average True Range), giving dynamic risk management levels.
Buy/Sell Ranges:
The user can set minimum and maximum price ranges for buy and sell signals, ensuring that the indicator only generates alerts within desired price ranges.
How It Works:
Buy Signals: The script generates buy signals based on multiple conditions, including the crack snap strategy, oversold RSI levels, and trend continuation setups. When these conditions are met, green triangles appear below the price bars, and an alert is triggered.
Sell Signals: Sell signals are triggered when the opposite conditions are met (overbought RSI, crack snap sell setups, trend breaks), and red triangles appear above the price bars.
Visual Indicators: The script plots upper and lower Bollinger Bands, stop loss levels, and VWAP on the chart, providing a comprehensive view of market conditions and support/resistance levels.
This indicator is versatile, combining multiple technical tools for robust decision-making in trading. It generates alerts, plots visual markers, and integrates risk management, making it a well-rounded tool for technical analysis.
This indicator is versatile, combining multiple technical tools for robust decision-making in trading. It generates alerts, plots visual markers, and integrates risk management, making it a well-rounded tool for technical analysis.
Adaptive Candlestick Pattern Recognition Systemโ INTRODUCTION
Nearly three years in the making, intermittently worked on in the few spare hours of weekends and time off, this is a passion project I undertook to flesh out my skills as a computer programmer. This script currently recognizes 85 different candlestick patterns ranging from one to five candles in length. It also performs statistical analysis on those patterns to determine prior performance and changes the coloration of those patterns based on that performance. In searching TradingView's script library for scripts similar to this one, I had found a handful. However, when I reviewed the ones which were open source, I did not see many that truly captured the power of PineScrypt or leveraged the way it works to create efficient and reliable code; one of the main driving factors for releasing this 5,000+ line behemoth open sourced.
Please take the time to review this description and source code to utilize this script to its fullest potential.
โ CONCEPTS
This script covers the following topics: Candlestick Theory, Trend Direction, Higher Timeframes, Price Analysis, Statistic Analysis, and Code Design.
Candlestick Theory - This script focuses solely on the concept of Candlestick Theory: arrangements of candlesticks may form certain patterns that can potentially influence the future price action of assets which experience those patterns. A full list of patterns (grouped by pattern length) will be in its own section of this description. This script contains two modes of operation for identifying candlestick patterns, 'CLASSIC' and 'BREAKOUT'.
CLASSIC: In this mode, candlestick patterns will be identified whenever they appear. The user has a wide variety of inputs to manipulate that can change how certain patterns are identified and even enable alerts to notify themselves when these patterns appear. Each pattern selected to appear will have their Profit or Loss (P/L) calculated starting from the first candle open succeeding the pattern to a candle close specified some number of candles ahead. These P/L calculations are then collected for each pattern, and split among partitions of prior price action of the asset the script is currently applied to (more on that in Higher Timeframes ).
BREAKOUT: In this mode, P/L calculations are held off until a breakout direction has been confirmed. The user may specify the number of candles ahead of a pattern's appearance (from one to five) that a pattern has to confirm a breakout in either an upward or downward direction. A breakout is constituted when there is a candle following the appearance of the pattern that closes above/at the highest high of the pattern, or below/at its lowest low. Only then will percent return calculations be performed for the pattern that's been identified, and these percent returns are broken up not only by the partition they had appeared in but also by the breakout direction itself. Patterns which do not breakout in either direction will be ignored, along with having their labels deleted.
In both of these modes, patterns may be overridden. Overrides occur when a smaller pattern has been detected and ends up becoming one (or more) of the candles of a larger pattern. A key example of this would be the Bearish Engulfing and the Three Outside Down patterns. A Three Outside Down necessitates a Bearish Engulfing as the first two candles in it, while the third candle closes lower. When a pattern is overridden, the return for that pattern will no longer be tracked. Overrides will not occur if the tail end of a larger pattern occurs at the beginning of a smaller pattern (Ex: a Bullish Engulfing occurs on the third candle of a Three Outside Down and the candle immediately following that pattern, the Three Outside Down pattern will not be overridden).
Important Functionality Note: These patterns are only searched for at the most recently closed candle, not on the currently closing candle, which creates an offset of one for this script's execution. (SEE LIMITATIONS)
Trend Direction - Many of the patterns require a trend direction prior to their appearance. Noting TradingView's own publication of candlestick patterns, I utilize a similar method for determining trend direction. Moving Averages are used to determine which trend is currently taking place for candlestick patterns to be sought out. The user has access to two Moving Averages which they may individually modify the following for each: Moving Average type (list of 9), their length, width, source values, and all variables associated with two special Moving Averages (Least Squares and Arnaud Legoux).
There are 3 settings for these Moving Averages, the first two switch between the two Moving Averages, and the third uses both. When using individual Moving Averages, the user may select a 'price point' to compare against the Moving Average (default is close). This price point is compared to the Moving Average at the candles prior to the appearance of candle patterns. Meaning: The close compared to the Moving Average two candles behind determines the trend direction used for Candlestick Analysis of one candle patterns; three candles behind for two candle patterns and so on. If the selected price point is above the Moving Average, then the current trend is an 'uptrend', 'downtrend' otherwise.
The third setting using both Moving Averages will compare the lengths of each, and trend direction is determined by the shorter Moving Average compared to the longer one. If the shorter Moving Average is above the longer, then the current trend is an 'uptrend', 'downtrend' otherwise. If the lengths of the Moving Averages are the same, or both Moving Averages are Symmetrical, then MA1 will be used by default. (SEE LIMITATIONS)
Higher Timeframes - This script employs the use of Higher Timeframes with a few request.security calls. The purpose of these calls is strictly for the partitioning of an asset's chart, splitting the returns of patterns into three separate groups. The four inputs in control of this partitioning split the chart based on: A given resolution to grab values from, the length of time in that resolution, and 'Upper' and 'Lower Limits' which split the trading range provided by that length of time in that resolution that forms three separate groups. The default values for these four inputs will partition the current chart by the yearly high-low range where: the 'Upper' partition is the top 20% of that trading range, the 'Middle' partition is 80% to 33% of the trading range, and the 'Lower' partition covers the trading range within 33% of the yearly low.
Patterns which are identified by this script will have their returns grouped together based on which partition they had appeared in. For example, a Bullish Engulfing which occurs within a third of the yearly low will have its return placed separately from a Bullish Engulfing that occurred within 20% of the yearly high. The idea is that certain patterns may perform better or worse depending on when they had occurred during an asset's trading range.
Price Analysis - Price Analysis is a major part of this script's functionality as it can fundamentally change how patterns are shown to the user. The settings related to Price Analysis include setting the number of candles ahead of a pattern's appearance to determine the return of that pattern. In 'BREAKOUT' mode, an additional setting allows the user to specify where the P/L calculation will begin for a pattern that had appeared and confirmed. (SEE LIMITATIONS)
The calculation for percent returns of patterns is illustrated with the following pseudo-code (CLASSIC mode, this is a simplified version of the actual code):
type patternObj
int ID
int partition
type returnsArray
float returns
// No pattern found = na returned
patternObj TEST_VAL = f_FindPattern()
priorTestVal = TEST_VAL
if not na( priorTestVal )
pnlMatrixRow = priorTestVal.ID
pnlMatrixCol = priorTestVal.partition
matrixReturn = matrix.get(PERCENT_RETURNS, pnlMatrixRow, pnlMatrixCol)
percentReturn = ( (close - open ) / open ) * 100%
array.push(matrixReturn.returns, percentReturn)
Statistic Analysis - This script uses Pine's built-in array functions to conduct the Statistic Analysis for patterns. When a pattern is found and its P/L calculation is complete, its return is added to a 'Return Array' User-Defined-Type that contains numerous fields which retain information on a pattern's prior performance. The actual UDT is as follows:
type returnArray
float returns = na
int size = 0
float avg = 0
float median = 0
float stdDev = 0
int polarities = na
All values within this UDT will be updated when a return is added to it (some based on user input). The array.avg , array.median and array.stdev will be ran and saved into their respective fields after a return is placed in the 'returns' array. The 'polarities' integer array is what will be changed based on user input. The user specifies two different percentages that declare 'Positive' and 'Negative' returns for patterns. When a pattern returns above, below, or in between these two values, different indices of this array will be incremented to reflect the kind of return that pattern had just experienced.
These values (plus the full name, partition the pattern occurred in, and a 95% confidence interval of expected returns) will be displayed to the user on the tooltip of the labels that identify patterns. Simply scroll over the pattern label to view each of these values.
Code Design - Overall this script is as much of an art piece as it is functional. Its design features numerous depictions of ASCII Art that illustrate what is being attempted by the functions that identify patterns, and an incalculable amount of time was spent rewriting portions of code to improve its efficiency. Admittedly, this final version is nearly 1,000 lines shorter than a previous version (one which took nearly 30 seconds after compilation to run, and didn't do nearly half of what this version does). The use of UDTs, especially the 'patternObj' one crafted and redesigned from the Hikkake Hunter 2.0 I published last month, played a significant role in making this script run efficiently. There is a slight rigidity in some of this code mainly around pattern IDs which are responsible for displaying the abbreviation for patterns (as well as the full names under the tooltips, and the matrix row position for holding returns), as each is hard-coded to correspond to that pattern.
However, one thing I would like to mention is the extensive use of global variables for pattern detection. Many scripts I had looked over for ideas on how to identify candlestick patterns had the same idea; break the pattern into a set of logical 'true/false' statements derived from historically referencing candle OHLC values. Some scripts which identified upwards of 20 to 30 patterns would reference Pine's built-in OHLC values for each pattern individually, potentially requesting information from TradingView's servers numerous times that could easily be saved into a variable for re-use and only requested once per candle (what this script does).
โ FEATURES
This script features a massive amount of switches, options, floating point values, detection settings, and methods for identifying/tailoring pattern appearances. All modifiable inputs for patterns are grouped together based on the number of candles they contain. Other inputs (like those for statistics settings and coloration) are grouped separately and presented in a way I believe makes the most sense.
Not mentioned above is the coloration settings. One of the aims of this script was to make patterns visually signify their behavior to the user when they are identified. Each pattern has its own collection of returns which are analyzed and compared to the inputs of the user. The user may choose the colors for bullish, neutral, and bearish patterns. They may also choose the minimum number of patterns needed to occur before assigning a color to that pattern based on its behavior; a color for patterns that have not met this minimum number of occurrences yet, and a color for patterns that are still processing in BREAKOUT mode.
There are also an additional three settings which alter the color scheme for patterns: Statistic Point-of-Reference, Adaptive coloring, and Hard Limiting. The Statistic Point-of-Reference decides which value (average or median) will be compared against the 'Negative' and 'Positive Return Tolerance'(s) to guide the coloration of the patterns (or for Adaptive Coloring, the generation of a color gradient).
Adaptive Coloring will have this script produce a gradient that patterns will be colored along. The more bullish or bearish a pattern is, the further along the gradient those patterns will be colored starting from the 'Neutral' color (hard lined at the value of 0%: values above this will be colored bullish, bearish otherwise). When Adaptive Coloring is enabled, this script will request the highest and lowest values (these being the Statistic Point-of-Reference) from the matrix containing all returns and rewrite global variables tied to the negative and positive return tolerances. This means that all patterns identified will be compared with each other to determine bullish/bearishness in Adaptive Coloring.
Hard Limiting will prevent these global variables from being rewritten, so patterns whose Statistic Point-of-Reference exceed the return tolerances will be fully colored the bullish or bearish colors instead of a generated gradient color. (SEE LIMITATIONS)
Apart from the Candle Detection Modes (CLASSIC and BREAKOUT), there's an additional two inputs which modify how this script behaves grouped under a "MASTER DETECTION SETTINGS" tab. These two "Pattern Detection Settings" are 'SWITCHBOARD' and 'TARGET MODE'.
SWITCHBOARD: Every single pattern has a switch that is associated with its detection. When a switch is enabled, the code which searches for that pattern will be run. With the Pattern Detection Setting set to this, all patterns that have their switches enabled will be sought out and shown.
TARGET MODE: There is an additional setting which operates on top of 'SWITCHBOARD' that singles out an individual pattern the user specifies through a drop down list. The names of every pattern recognized by this script will be present along with an identifier that shows the number of candles in that pattern (Ex: " (# candles)"). All patterns enabled in the switchboard will still have their returns measured, but only the pattern selected from the "Target Pattern" list will be shown. (SEE LIMITATIONS)
The vast majority of other features are held in the one, two, and three candle pattern sections.
For one-candle patterns, there are:
3 โ Settings related to defining 'Tall' candles:
The number of candles to sample for previous candle-size averages.
The type of comparison done for 'Tall' Candles: Settings are 'RANGE' and 'BODY'.
The 'Tolerance' for tall candles, specifying what percent of the 'average' size candles must exceed to be considered 'Tall'.
When 'Tall Candle Setting' is set to RANGE, the high-low ranges are what the current candle range will be compared against to determine if a candle is 'Tall'. Otherwise the candle bodies (absolute value of the close - open) will be compared instead. (SEE LIMITATIONS)
Hammer Tolerance - How large a 'discarded wick' may be before it disqualifies a candle from being a 'Hammer'.
Discarded wicks are compared to the size of the Hammer's candle body and are dependent upon the body's center position. Hammer bodies closer to the high of the candle will have the upper wick used as its 'discarded wick', otherwise the lower wick is used.
9 โ Doji Settings, some pulled from an old Doji Hunter I made a while back:
Doji Tolerance - How large the body of a candle may be compared to the range to be considered a 'Doji'.
Ignore N/S Dojis - Turns off Trend Direction for non-special Dojis.
GS/DF Doji Settings - 2 Inputs that enable and specify how large wicks that typically disqualify Dojis from being 'Gravestone' or 'Dragonfly' Dojis may be.
4 Settings related to 'Long Wick Doji' candles detailed below.
A Tolerance for 'Rickshaw Man' Dojis specifying how close the center of the body must be to the range to be valid.
The 4 settings the user may modify for 'Long Legged' Dojis are: A Sample Base for determining the previous average of wicks, a Sample Length specifying how far back to look for these averages, a Behavior Setting to define how 'Long Legged' Dojis are recognized, and a tolerance to specify how large in comparison to the prior wicks a Doji's wicks must be to be considered 'Long Legged'.
The 'Sample Base' list has two settings:
RANGE: The wicks of prior candles are compared to their candle ranges and the 'wick averages' will be what the average percent of ranges were in the sample.
WICKS: The size of the wicks themselves are averaged and returned for comparing against the current wicks of a Doji.
The 'Behavior' list has three settings:
ONE: Only one wick length needs to exceed the average by the tolerance for a Doji to be considered 'Long Legged'.
BOTH: Both wick lengths need to exceed the average of the tolerance of their respective wicks (upper wicks are compared to upper wicks, lower wicks compared to lower) to be considered 'Long Legged'.
AVG: Both wicks and the averages of the previous wicks are added together, divided by two, and compared. If the 'average' of the current wicks exceeds this combined average of prior wicks by the tolerance, then this would constitute a valid 'Long Legged' Doji. (For Dojis in general - SEE LIMITATIONS)
The final input is one related to candle patterns which require a Marubozu candle in them. The two settings for this input are 'INCLUSIVE' and 'EXCLUSIVE'. If INCLUSIVE is selected, any opening/closing variant of Marubozu candles will be allowed in the patterns that require them.
For two-candle patterns, there are:
2 โ Settings which define 'Engulfing' parameters:
Engulfing Setting - Two options, RANGE or BODY which sets up how one candle may 'engulf' the previous.
Inclusive Engulfing - Boolean which enables if 'engulfing' candles can be equal to the values needed to 'engulf' the prior candle.
For the 'Engulfing Setting':
RANGE: If the second candle's high-low range completely covers the high-low range of the prior candle, this is recognized as 'engulfing'.
BODY: If the second candle's open-close completely covers the open-close of the previous candle, this is recognized as 'engulfing'. (SEE LIMITATIONS)
4 โ Booleans specifying different settings for a few patterns:
One which allows for 'opens within body' patterns to let the second candle's open/close values match the prior candles' open/close.
One which forces 'Kicking' patterns to have a gap if the Marubozu setting is set to 'INCLUSIVE'.
And Two which dictate if the individual candles in 'Stomach' patterns need to be 'Tall'.
8 โ Floating point values which affect 11 different patterns:
One which determines the distance the close of the first candle in a 'Hammer Inverted' pattern must be to the low to be considered valid.
One which affects how close the opens/closes need to be for all 'Lines' patterns (Bull/Bear Meeting/Separating Lines).
One that allows some leeway with the 'Matching Low' pattern (gives a small range the second candle close may be within instead of needing to match the previous close).
Three tolerances for On Neck/In Neck patterns (2 and 1 respectively).
A tolerance for the Thrusting pattern which give a range the close the second candle may be between the midpoint and close of the first to be considered 'valid'.
A tolerance for the two Tweezers patterns that specifies how close the highs and lows of the patterns need to be to each other to be 'valid'.
The first On Neck tolerance specifies how large the lower wick of the first candle may be (as a % of that candle's range) before the pattern is invalidated. The second tolerance specifies how far up the lower wick to the close the second candle's close may be for this pattern. The third tolerance for the In Neck pattern determines how far into the body of the first candle the second may close to be 'valid'.
For the remaining patterns (3, 4, and 5 candles), there are:
3 โ Settings for the Deliberation pattern:
A boolean which forces the open of the third candle to gap above the close of the second.
A tolerance which changes the proximity of the third candle's open to the second candle's close in this pattern.
A tolerance that sets the maximum size the third candle may be compared to the average of the first two candles.
One boolean value for the Two Crows patterns (standard and Upside Gapping) that forces the first two candles in the patterns to completely gap if disabled (candle 1's close < candle 2's low).
10 โ Floating point values for the remaining patterns:
One tolerance for defining how much the size of each candle in the Identical Black Crows pattern may deviate from the average of themselves to be considered valid.
One tolerance for setting how close the opens/closes of certain three candle patterns may be to each other's opens/closes.*
Three floating point values that affect the Three Stars in the South pattern.
One tolerance for the Side-by-Side patterns - looks at the second and third candle closes.
One tolerance for the Stick Sandwich pattern - looks at the first and third candle closes.
A floating value that sizes the Concealing Baby Swallow pattern's 3rd candle wick.
Two values for the Ladder Bottom pattern which define a range that the third candle's wick size may be.
* This affects the Three Black Crows (non-identical) and Three White Soldiers patterns, each require the opens and closes of every candle to be near each other.
The first tolerance of the Three Stars in the South pattern affects the first candle body's center position, and defines where it must be above to be considered valid. The second tolerance specifies how close the second candle must be to this same position, as well as the deviation the ratio the candle body to its range may be in comparison to the first candle. The third restricts how large the second candle range may be in comparison to the first (prevents this pattern from being recognized if the second candle is similar to the first but larger).
The last two floating point values define upper and lower limits to the wick size of a Ladder Bottom's fourth candle to be considered valid.
โ HOW TO USE
While there are many moving parts to this script, I attempted to set the default values with what I believed may help identify the most patterns within reasonable definitions. When this script is applied to a chart, the Candle Detection Mode (along with the BREAKOUT settings) and all candle switches must be confirmed before patterns are displayed. All switches are on by default, so this gives the user an opportunity to pick which patterns to identify first before playing around in the settings.
All of the settings/inputs described above are meant for experimentation. I encourage the user to tweak these values at will to find which set ups work best for whichever charts they decide to apply these patterns to.
Refer to the patterns themselves during experimentation. The statistic information provided on the tooltips of the patterns are meant to help guide input decisions. The breadth of candlestick theory is deep, and this was an attempt at capturing what I could in its sea of information.
โ LIMITATIONS
DISCLAIMER: While it may seem a bit paradoxical that this script aims to use past performance to potentially measure future results, past performance is not indicative of future results . Markets are highly adaptive and often unpredictable. This script is meant as an informational tool to show how patterns may behave. There is no guarantee that confidence intervals (or any other metric measured with this script) are accurate to the performance of patterns; caution must be exercised with all patterns identified regardless of how much information regarding prior performance is available.
Candlestick Theory - In the name, Candlestick Theory is a theory , and all theories come with their own limits. Some patterns identified by this script may be completely useless/unprofitable/unpredictable regardless of whatever combination of settings are used to identify them. However, if I truly believed this theory had no merit, this script would not exist. It is important to understand that this is a tool meant to be utilized with an array of others to procure positive (or negative, looking at you, short sellers ) results when navigating the complex world of finance.
To address the functionality note however, this script has an offset of 1 by default. Patterns will not be identified on the currently closing candle, only on the candle which has most recently closed. Attempting to have this script do both (offset by one or identify on close) lead to more trouble than it was worth. I personally just want users to be aware that patterns will not be identified immediately when they appear.
Trend Direction - Moving Averages - There is a small quirk with how MA settings will be adjusted if the user inputs two moving averages of the same length when the "MA Setting" is set to 'BOTH'. If Moving Averages have the same length, this script will default to only using MA 1 regardless of if the types of Moving Averages are different . I will experiment in the future to alleviate/reduce this restriction.
Price Analysis - BREAKOUT mode - With how identifying patterns with a look-ahead confirmation works, the percent returns for patterns that break out in either direction will be calculated on the same candle regardless of if P/L Offset is set to 'FROM CONFIRMATION' or 'FROM APPEARANCE'. This same issue is present in the Hikkake Hunter script mentioned earlier. This does not mean the P/L calculations are incorrect , the offset for the calculation is set by the number of candles required to confirm the pattern if 'FROM APPEARANCE' is selected. It just means that these two different P/L calculations will complete at the same time independent of the setting that's been selected.
Adaptive Coloring/Hard Limiting - Hard Limiting is only used with Adaptive Coloring and has no effect outside of it. If Hard Limiting is used, it is recommended to increase the 'Positive' and 'Negative' return tolerance values as a pattern's bullish/bearishness may be disproportionately represented with the gradient generated under a hard limit.
TARGET MODE - This mode will break rules regarding patterns that are overridden on purpose. If a pattern selected in TARGET mode would have otherwise been absorbed by a larger pattern, it will have that pattern's percent return calculated; potentially leading to duplicate returns being included in the matrix of all returns recognized by this script.
'Tall' Candle Setting - This is a wide-reaching setting, as approximately 30 different patterns or so rely on defining 'Tall' candles. Changing how 'Tall' candles are defined whether by the tolerance value those candles need to exceed or by the values of the candle used for the baseline comparison (RANGE/BODY) can wildly affect how this script functions under certain conditions. Refer to the tooltip of these settings for more information on which specific patterns are affected by this.
Doji Settings - There are roughly 10 or so two to three candle patterns which have Dojis as a part of them. If all Dojis are disabled, it will prevent some of these larger patterns from being recognized. This is a dependency issue that I may address in the future.
'Engulfing' Setting - Functionally, the two 'Engulfing' settings are quite different. Because of this, the 'RANGE' setting may cause certain patterns that would otherwise be valid under textbook and online references/definitions to not be recognized as such (like the Upside Gap Two Crows or Three Outside down).
โ PATTERN LIST
This script recognizes 85 patterns upon initial release. I am open to adding additional patterns to it in the future and any comments/suggestions are appreciated. It recognizes:
15 โ 1 Candle Patterns
4 Hammer type patterns: Regular Hammer, Takuri Line, Shooting Star, and Hanging Man
9 Doji Candles: Regular Dojis, Northern/Southern Dojis, Gravestone/Dragonfly Dojis, Gapping Up/Down Dojis, and Long-Legged/Rickshaw Man Dojis
White/Black Long Days
32 โ 2 Candle Patterns
4 Engulfing type patterns: Bullish/Bearish Engulfing and Last Engulfing Top/Bottom
Dark Cloud Cover
Bullish/Bearish Doji Star patterns
Hammer Inverted
Bullish/Bearish Haramis + Cross variants
Homing Pigeon
Bullish/Bearish Kicking
4 Lines type patterns: Bullish/Bearish Meeting/Separating Lines
Matching Low
On/In Neck patterns
Piercing pattern
Shooting Star (2 Lines)
Above/Below Stomach patterns
Thrusting
Tweezers Top/Bottom patterns
Two Black Gapping
Rising/Falling Window patterns
29 โ 3 Candle Patterns
Bullish/Bearish Abandoned Baby patterns
Advance Block
Collapsing Doji Star
Deliberation
Upside/Downside Gap Three Methods patterns
Three Inside/Outside Up/Down patterns (4 total)
Bullish/Bearish Side-by-Side patterns
Morning/Evening Star patterns + Doji variants
Stick Sandwich
Downside/Upside Tasuki Gap patterns
Three Black Crows + Identical variation
Three White Soldiers
Three Stars in the South
Bullish/Bearish Tri-Star patterns
Two Crows + Upside Gap variant
Unique Three River Bottom
3 โ 4 Candle Patterns
Concealing Baby Swallow
Bullish/Bearish Three Line Strike patterns
6 โ 5 Candle Patterns
Bullish/Bearish Breakaway patterns
Ladder Bottom
Mat Hold
Rising/Falling Three Methods patterns
โ WORKS CITED
Because of the amount of time needed to complete this script, I am unable to provide exact dates for when some of these references were used. I will also not provide every single reference, as citing a reference for each individual pattern and the place it was reviewed would lead to a bibliography larger than this script and its description combined. There were five major resources I used when building this script, one book, two websites (for various different reasons including patterns, moving averages, and various other articles of information), various scripts from TradingView's public library (including TradingView's own source code for *all* candle patterns ), and PineScrypt's reference manual.
Bulkowski, Thomas N. Encyclopedia of Candlestick Patterns . Hoboken, New Jersey: John Wiley & Sons Inc., 2008. E-book (google books).
Various. Numerous webpages. CandleScanner . 2023. online. Accessed 2020 - 2023.
Various. Numerous webpages. Investopedia . 2023. online. Accessed 2020 - 2023.
โ AKNOWLEDGEMENTS
I want to take the time here to thank all of my friends and family, both online and in real life, for the support they've given me over the last few years in this endeavor. My pets who tried their hardest to keep me from completing it. And work for the grit to continue pushing through until this script's completion.
This belongs to me just as much as it does anyone else. Whether you are an institutional trader, gold bug hedging against the dollar, retail ape who got in on a squeeze, or just parents trying to grow their retirement/save for the kids. This belongs to everyone.
Private Beta for new features to be tested can be found here .
Vires In Numeris
X OROverview
Designed to plot hourly opening ranges (ORs) on an intraday chart. It primarily serves as a trading tool for assessing market direction and potential trading opportunities by analyzing price action relative to key OHLC (Open, High, Low, Close) levels within each hourly range.
The code provided is for each hour sessions from 2:00 AM to 3:00 PM for a complete session-based framework. In addition there is the RTH open range
Purpose
The core purpose of this indicator is to:
โ
Define each hourly range (based on the sessionโs opening bar) by recording the high and low of that range.
โ
Extend this range into the following bars for visual reference โ serving as dynamic support and resistance zones.
โ
Monitor price action relative to each hourly OR, helping traders evaluate market direction and structure trades using concepts like:
Breakouts above/below the OR high/low.
Rejections or consolidations within the OR.
Continuation or reversal signals tied to each OR.
Key Features
The script marks the first bar of the session as the OR session start.
During this bar, it initializes:
Opening price
Session high
Session low
These levels form the initial range.
๐น Dynamic Range Tracking
Throughout the one-minute OR session:
The highest and lowest prices are updated in real time, capturing intra-hour volatility.
A visual background box is drawn to highlight the OR range on the chart.
๐น Range Extension
The script defines an extended session period after the initial OR (e.g., 2:00 AM-2:45 AM for the 2:00 AM session).
During this extension period:
The box persists on the chart, providing a contextual zone that traders can use as a dynamic support/resistance area.
๐น Visual Representation
Transparent colored boxes highlight each sessionโs OR visually on the chart.
These boxes help traders easily identify whether price is trading:
Inside the OR
Breaking above the high (potential bullish continuation)
Breaking below the low (potential bearish continuation)
Application in Trading
๐ Trading the Opening Range Breakout
Traders often use the OR high and low as breakout triggers. For example:
A price break above the OR high may signal bullish momentum.
A break below the OR low may signal bearish momentum.
โ๏ธ Support and Resistance
Even if breakouts fail, the OR can act as a pivot zone โ offering areas for:
Stop placements
Target levels
Entry confirmations for fade trades or mean reversion strategies.
๐ Session Awareness
By defining each hourโs OR individually (from 2:00 AM to 3:00 PM), traders can:
Analyze price behavior within each session.
Recognize when liquidity or volatility increases (e.g. around overlapping sessions like London open or New York open).
Summary
This Pine Script indicator provides a powerful framework for visualizing and trading hourly opening ranges. It enhances intraday analysis by:
Structuring price action within hourly boxes.
Highlighting key price levels relative to OHLC concepts.
Helping traders make more informed decisions by assessing price behavior around these critical ranges.
Auto Darvas Boxes## AUTO DARVAS BOXES
---
### OVERVIEW
**Auto Darvas Boxes** is a fully-automated, event-driven implementation of Nicolas Darvasโs 1950s box methodology.
The script tracks consolidation zones in real time, verifies that price truly โrespectsโ those zones for a fixed validation window, then waits for the first decisive range violation to mark a directional breakout.
Every box is plotted end-to-endโfrom the first candle of the sideways range to the exact candle that ruptures itโgiving you an on-chart, visually precise record of accumulation or distribution and the expansion that follows.
---
### HISTORICAL BACKGROUND
* Nicolas Darvas was a professional ballroom dancer who traded U.S. equities by telegram while touring the world.
* Without live news or Level II, he relied exclusively on **price** to infer institutional intent.
* His core insight: true market-moving entities leave footprints in the form of tight ranges; once their buying (or selling) is complete, price erupts out of the โbox.โ
* Darvasโs original procedure was manualโhe kept notebooks, drew rectangles around highs and lows, and entered only when price punched out of the roof of a valid box.
* This indicator distills that logic into a rolling, self-resetting state machine so you never miss a box or breakout on any timeframe.
---
### ALGORITHM DETAIL (FOUR-STATE MACHINE)
**STATE 0 โ RANGE DEFINITION**
โโข Examine the last *N* candles (default 7).
โโข Record `rangeHigh = highest(high, N) + tolerance`.
โโข Record `rangeLow = lowest(low, N) โ tolerance`.
โโข Remember the index of the earliest bar in this window (`startBar`).
โโข Immediately transition to STATE 1.
**STATE 1 โ RANGE VALIDATION**
โโข Observe the next *N* candles (again default 7).
โโข If **any** candle prints `high > rangeHigh` or `low < rangeLow`, the validation fails and the engine resets to STATE 0 **beginning at the violating candle**โno halfway boxes, no overlap.
โโข If all *N* candles remain inside the range, the box becomes **armed** and we transition to STATE 2.
**STATE 2 โ ARMED (LIVE VISUAL FEEDBACK)**
โโข Draw a **green horizontal line** at `rangeHigh`.
โโข Draw a **red horizontal line** at `rangeLow`.
โโข Lines are extended in real time so the user can see the โliveโ Darvas ceiling and floor.
โโข Engine waits indefinitely for a breakout candle:
โโโ **Up-Breakout** if `high > rangeHigh`.
โโโ **Down-Breakout** if `low < rangeLow`.
**STATE 3 โ BREAKOUT & COOLDOWN**
โโข Upon breakout the script:
โโ1. Deletes the live range lines.
โโ2. Draws a **filled rectangle (box)** from `startBar` to the breakout bar.
โโโ โฆ **Green fill** when price exits above the ceiling.
โโโ โฆ **Red fill** when price exits below the floor.
โโ3. Optionally prints two labels at the left edge of the box:
โโโ โฆ Dollar distance = `rangeHigh โ rangeLow`.
โโโ โฆ Percentage distance = `(rangeHigh โ rangeLow) / rangeLow ร 100 %`.
โโข After painting, the script waits a **user-defined cooldown** (default = 7 bars) before reverting to STATE 0. The cooldown guarantees separation between consecutive tests and prevents overlapping rectangles.
---
### INPUT PARAMETERS (ALL ADJUSTABLE FROM THE SETTINGS PANEL)
* **BARS TO DEFINE RANGE** โ Number of candles used for both the definition and validation windows. Classic Darvas logic uses 7 but feel free to raise it on higher timeframes or volatile instruments.
* **OPTIONAL TOLERANCE** โ Absolute price buffer added above the ceiling and below the floor. Use a small tolerance to ignore single-tick spikes or data-feed noise.
* **COOLDOWN BARS AFTER BREAKOUT** โ How long the engine pauses before hunting for the next consolidation. Setting this equal to the range length produces non-overlapping, evenly spaced boxes.
* **SHOW BOX DISTANCE LABELS** โ Toggle on/off. When on, each completed box displays its vertical size in both dollars and percentage, anchored at the boxโs left edge.
---
### REAL-TIME VISUALISATION
* During the **armed** phase you see two extended, colour-coded guide-lines showing the exact high/low that must hold.
* When the breakout finally occurs, those lines vanish and the rectangle instantly appears, coloured to match the breakout direction.
* This immediate visual feedback turns any chart into a live Darvas tapeโno manual drawing, no lag.
---
### PRACTICAL USE-CASES & BEST-PRACTICE WORKFLOWS
* **INTRADAY MOMENTUM** โ Drop the script on 1- to 15-minute charts to catch tight coils before they explode. The coloured box marks the precise origin of the expansion; stops can sit just inside the opposite side of the box.
* **SWING & POSITION TRADING** โ On 4-hour or daily charts, boxes often correspond to accumulation bases or volatility squeezes. Waiting for the box-validated breakout filters many false signals.
* **MEAN-REVERSION OR โFADEโ STRATEGIES** โ If a breakout immediately fails and price re-enters the box, you may have trapped momentum traders; fading that failure can be lucrative.
* **RISK MANAGEMENT** โ Box extremes provide objective, structure-based stop levels rather than arbitrary ATR multiples.
* **BACK-TEST RESEARCH** โ Because each box is plotted from first range candle to breakout candle, you can programmatically measure hold time, range height, and post-breakout expectancy for any asset.
---
### CUSTOMISATION IDEAS FOR POWER USERS
* **VOLATILITY-ADAPTIVE WINDOW** โ Replace the fixed 7-bar length with a dynamic value tied to ATR percentile so the consolidation window stretches or compresses with volatility.
* **MULTI-TIMEFRAME LOGIC** โ Only arm a 5-minute box if the 1-hour trend is aligned.
* **STRATEGY WRAPPER** โ Convert the indicator to a full `strategy{}` script, automate entries on breakouts, and benchmark performance across assets.
* **ALERTS** โ Create TradingView alerts on both up-breakout and down-breakout conditions; route them to webhook for broker automation.
---
### FINAL THOUGHTS
**Auto Darvas Boxes** packages one of the marketโs oldest yet still potent price-action frameworks into a modern, self-resetting indicator. Whether you trade equities, futures, crypto, or forex, the script highlights genuine contraction-expansion sequencesโDarvasโs original โboxesโโwith zero manual effort, letting you focus solely on execution and risk.
Trading IQ - ICT LibraryLibrary "ICTlibrary"
Used to calculate various ICT related price levels and strategies. An ongoing project.
Hello Coders!
This library is meant for sourcing ICT related concepts. While some functions might generate more output than you require, you can specify "Lite Mode" as "true" in applicable functions to slim down necessary inputs.
isLastBar(userTF)
โโIdentifies the last bar on the chart before a timeframe change
โโParameters:
โโโโ userTF (simple int) : the timeframe you wish to calculate the last bar for, must be converted to integer using 'timeframe.in_seconds()'
โโReturns: bool true if bar on chart is last bar of higher TF, dalse if bar on chart is not last bar of higher TF
necessaryData(atrTF)
โโreturns necessaryData UDT for historical data access
โโParameters:
โโโโ atrTF (float) : user-selected timeframe ATR value.
โโReturns: logZ. log return Z score, used for calculating order blocks.
method gradBoxes(gradientBoxes, idColor, timeStart, bottom, top, rightCoordinate)
โโcreates neon like effect for box drawings
โโNamespace types: array
โโParameters:
โโโโ gradientBoxes (array) : an array.new() to store the gradient boxes
โโโโ idColor (color)
โโโโ timeStart (int) : left point of box
โโโโ bottom (float) : bottom of box price point
โโโโ top (float) : top of box price point
โโโโ rightCoordinate (int) : right point of box
โโReturns: void
checkIfTraded(tradeName)
โโchecks if recent trade is of specific name
โโParameters:
โโโโ tradeName (string)
โโReturns: bool true if recent trade id matches target name, false otherwise
checkIfClosed(tradeName)
โโchecks if recent closed trade is of specific name
โโParameters:
โโโโ tradeName (string)
โโReturns: bool true if recent closed trade id matches target name, false otherwise
IQZZ(atrMult, finalTF)
โโcustom ZZ to quickly determine market direction.
โโParameters:
โโโโ atrMult (float) : an atr multiplier used to determine the required price move for a ZZ direction change
โโโโ finalTF (string) : the timeframe used for the atr calcuation
โโReturns: dir market direction. Up => 1, down => -1
method drawBos(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showBOS, isUp)
โโcalculates and draws Break Of Structure
โโNamespace types: array
โโParameters:
โโโโ id (array)
โโโโ startPoint (chart.point)
โโโโ getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
โโโโ getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
โโโโ col (color) : color of the BoS line / label
โโโโ showBOS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
โโโโ isUp (bool) : whether BoS happened during price increase or price decrease.
โโReturns: void
method drawMSS(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showMSS, isUp, upRejections, dnRejections, highArr, lowArr, timeArr, closeArr, openArr, atrTFarr, upRejectionsPrices, dnRejectionsPrices)
โโcalculates and draws Market Structure Shift. This data is also used to calculate Rejection Blocks.
โโNamespace types: array
โโParameters:
โโโโ id (array)
โโโโ startPoint (chart.point)
โโโโ getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
โโโโ getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
โโโโ col (color) : color of the MSS line / label
โโโโ showMSS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
โโโโ isUp (bool) : whether MSS happened during price increase or price decrease.
โโโโ upRejections (array)
โโโโ dnRejections (array)
โโโโ highArr (array) : array containing historical highs, should be taken from the UDT "necessaryData" defined above
โโโโ lowArr (array) : array containing historical lows, should be taken from the UDT "necessaryData" defined above
โโโโ timeArr (array) : array containing historical times, should be taken from the UDT "necessaryData" defined above
โโโโ closeArr (array) : array containing historical closes, should be taken from the UDT "necessaryData" defined above
โโโโ openArr (array) : array containing historical opens, should be taken from the UDT "necessaryData" defined above
โโโโ atrTFarr (array) : array containing historical atr values (of user-selected TF), should be taken from the UDT "necessaryData" defined above
โโโโ upRejectionsPrices (array) : array containing up rejections prices. Is sorted and used to determine selective looping for invalidations.
โโโโ dnRejectionsPrices (array) : array containing down rejections prices. Is sorted and used to determine selective looping for invalidations.
โโReturns: void
method getTime(id, compare, timeArr)
โโgets time of inputted price (compare) in an array of data
this is useful when the user-selected timeframe for ICT concepts is greater than the chart's timeframe
โโNamespace types: array
โโParameters:
โโโโ id (array) : the array of data to search through, to find which index has the same value as "compare"
โโโโ compare (float) : the target data point to find in the array
โโโโ timeArr (array) : array of historical times
โโReturns: the time that the data point in the array was recorded
method OB(id, highArr, signArr, lowArr, timeArr, sign)
โโstore bullish orderblock data
โโNamespace types: array
โโParameters:
โโโโ id (array)
โโโโ highArr (array) : array of historical highs
โโโโ signArr (array) : array of historical price direction "math.sign(close - open)"
โโโโ lowArr (array) : array of historical lows
โโโโ timeArr (array) : array of historical times
โโโโ sign (int) : orderblock direction, -1 => bullish, 1 => bearish
โโReturns: void
OTEstrat(OTEstart, future, closeArr, highArr, lowArr, timeArr, longOTEPT, longOTESL, longOTElevel, shortOTEPT, shortOTESL, shortOTElevel, structureDirection, oteLongs, atrTF, oteShorts)
โโexecutes the OTE strategy
โโParameters:
โโโโ OTEstart (chart.point)
โโโโ future (int) : future time point for drawings
โโโโ closeArr (array) : array of historical closes
โโโโ highArr (array) : array of historical highs
โโโโ lowArr (array) : array of historical lows
โโโโ timeArr (array) : array of historical times
โโโโ longOTEPT (string) : user-selected long OTE profit target, please create an input.string() for this using the example below
โโโโ longOTESL (int) : user-selected long OTE stop loss, please create an input.string() for this using the example below
โโโโ longOTElevel (float) : long entry price of selected retracement ratio for OTE
โโโโ shortOTEPT (string) : user-selected short OTE profit target, please create an input.string() for this using the example below
โโโโ shortOTESL (int) : user-selected short OTE stop loss, please create an input.string() for this using the example below
โโโโ shortOTElevel (float) : short entry price of selected retracement ratio for OTE
โโโโ structureDirection (string) : current market structure direction, this should be "Up" or "Down". This is used to cancel pending orders if market structure changes
โโโโ oteLongs (bool) : input.bool() for whether OTE longs can be executed
โโโโ atrTF (float) : atr of the user-seleceted TF
โโโโ oteShorts (bool) : input.bool() for whether OTE shorts can be executed
@exampleInputs
oteLongs = input.bool(defval = false, title = "OTE Longs", group = "Optimal Trade Entry")
longOTElevel = input.float(defval = 0.79, title = "Long Entry Retracement Level", options = , group = "Optimal Trade Entry")
longOTEPT = input.string(defval = "-0.5", title = "Long TP", options = , group = "Optimal Trade Entry")
longOTESL = input.int(defval = 0, title = "How Many Ticks Below Swing Low For Stop Loss", group = "Optimal Trade Entry")
oteShorts = input.bool(defval = false, title = "OTE Shorts", group = "Optimal Trade Entry")
shortOTElevel = input.float(defval = 0.79, title = "Short Entry Retracement Level", options = , group = "Optimal Trade Entry")
shortOTEPT = input.string(defval = "-0.5", title = "Short TP", options = , group = "Optimal Trade Entry")
shortOTESL = input.int(defval = 0, title = "How Many Ticks Above Swing Low For Stop Loss", group = "Optimal Trade Entry")
โโReturns: void (0)
displacement(logZ, atrTFreg, highArr, timeArr, lowArr, upDispShow, dnDispShow, masterCoords, labelLevels, dispUpcol, rightCoordinate, dispDncol, noBorders)
โโcalculates and draws dispacements
โโParameters:
โโโโ logZ (float) : log return of current price, used to determine a "significant price move" for a displacement
โโโโ atrTFreg (float) : atr of user-seleceted timeframe
โโโโ highArr (array) : array of historical highs
โโโโ timeArr (array) : array of historical times
โโโโ lowArr (array) : array of historical lows
โโโโ upDispShow (int) : amount of historical upside displacements to show
โโโโ dnDispShow (int) : amount of historical downside displacements to show
โโโโ masterCoords (map) : a map to push the most recent displacement prices into, useful for having key levels in one data structure
โโโโ labelLevels (string) : used to determine label placement for the displacement, can be inside box, outside box, or none, example below
โโโโ dispUpcol (color) : upside displacement color
โโโโ rightCoordinate (int) : future time for displacement drawing, best is "last_bar_time"
โโโโ dispDncol (color) : downside displacement color
โโโโ noBorders (bool) : input.bool() to remove box borders, example below
@exampleInputs
labelLevels = input.string(defval = "Inside" , title = "Box Label Placement", options = )
noBorders = input.bool(defval = false, title = "No Borders On Levels")
โโReturns: void
method getStrongLow(id, startIndex, timeArr, lowArr, strongLowPoints)
โโunshift strong low data to array id
โโNamespace types: array
โโParameters:
โโโโ id (array)
โโโโ startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the low before an upside BoS
โโโโ timeArr (array) : array of historical times
โโโโ lowArr (array) : array of historical lows
โโโโ strongLowPoints (array) : array of strong low prices. Used to retrieve highest strong low price and see if need for
removal of invalidated strong lows
โโReturns: void
method getStrongHigh(id, startIndex, timeArr, highArr, strongHighPoints)
โโunshift strong high data to array id
โโNamespace types: array
โโParameters:
โโโโ id (array)
โโโโ startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the high before a downside BoS
โโโโ timeArr (array) : array of historical times
โโโโ highArr (array) : array of historical highs
โโโโ strongHighPoints (array)
โโReturns: void
equalLevels(highArr, lowArr, timeArr, rightCoordinate, equalHighsCol, equalLowsCol, liteMode)
โโused to calculate recent equal highs or equal lows
โโParameters:
โโโโ highArr (array) : array of historical highs
โโโโ lowArr (array) : array of historical lows
โโโโ timeArr (array) : array of historical times
โโโโ rightCoordinate (int) : a future time (right for boxes, x2 for lines)
โโโโ equalHighsCol (color) : user-selected color for equal highs drawings
โโโโ equalLowsCol (color) : user-selected color for equal lows drawings
โโโโ liteMode (bool) : optional for a lite mode version of an ICT strategy. For more control over drawings leave as "True", "False" will apply neon effects
โโReturns: void
quickTime(timeString)
โโused to quickly determine if a user-inputted time range is currently active in NYT time
โโParameters:
โโโโ timeString (string) : a time range
โโReturns: true if session is active, false if session is inactive
macros(showMacros, noBorders)
โโused to calculate and draw session macros
โโParameters:
โโโโ showMacros (bool) : an input.bool() or simple bool to determine whether to activate the function
โโโโ noBorders (bool) : an input.bool() to determine whether the box anchored to the session should have borders
โโReturns: void
po3(tf, left, right, show)
โโuse to calculate HTF po3 candle
@tip only call this function on "barstate.islast"
โโParameters:
โโโโ tf (simple string)
โโโโ left (int) : the left point of the candle, calculated as bar_index + left,
โโโโ right (int) : :the right point of the candle, calculated as bar_index + right,
โโโโ show (bool) : input.bool() whether to show the po3 candle or not
โโReturns: void
silverBullet(silverBulletStratLong, silverBulletStratShort, future, userTF, H, L, H2, L2, noBorders, silverBulletLongTP, historicalPoints, historicalData, silverBulletLongSL, silverBulletShortTP, silverBulletShortSL)
โโused to execute the Silver Bullet Strategy
โโParameters:
โโโโ silverBulletStratLong (simple bool)
โโโโ silverBulletStratShort (simple bool)
โโโโ future (int) : a future time, used for drawings, example "last_bar_time"
โโโโ userTF (simple int)
โโโโ H (float) : the high price of the user-selected TF
โโโโ L (float) : the low price of the user-selected TF
โโโโ H2 (float) : the high price of the user-selected TF
โโโโ L2 (float) : the low price of the user-selected TF
โโโโ noBorders (bool) : an input.bool() used to remove the borders from box drawings
โโโโ silverBulletLongTP (series silverBulletLevels)
โโโโ historicalPoints (array)
โโโโ historicalData (necessaryData)
โโโโ silverBulletLongSL (series silverBulletLevels)
โโโโ silverBulletShortTP (series silverBulletLevels)
โโโโ silverBulletShortSL (series silverBulletLevels)
โโReturns: void
method invalidFVGcheck(FVGarr, upFVGpricesSorted, dnFVGpricesSorted)
โโcheck if existing FVGs are still valid
โโNamespace types: array
โโParameters:
โโโโ FVGarr (array)
โโโโ upFVGpricesSorted (array) : an array of bullish FVG prices, used to selective search through FVG array to remove invalidated levels
โโโโ dnFVGpricesSorted (array) : an array of bearish FVG prices, used to selective search through FVG array to remove invalidated levels
โโReturns: void (0)
method drawFVG(counter, FVGshow, FVGname, FVGcol, data, masterCoords, labelLevels, borderTransp, liteMode, rightCoordinate)
โโdraws FVGs on last bar
โโNamespace types: map
โโParameters:
โโโโ counter (map) : a counter, as map, keeping count of the number of FVGs drawn, makes sure that there aren't more FVGs drawn
than int FVGshow
โโโโ FVGshow (int) : the number of FVGs to show. There should be a bullish FVG show and bearish FVG show. This function "drawFVG" is used separately
for bearish FVG and bullish FVG.
โโโโ FVGname (string) : the name of the FVG, "FVG Up" or "FVG Down"
โโโโ FVGcol (color) : desired FVG color
โโโโ data (FVG)
โโโโ masterCoords (map) : a map containing the names and price points of key levels. Used to define price ranges.
โโโโ labelLevels (string) : an input.string with options "Inside", "Outside", "Remove". Determines whether FVG labels should be inside box, outside,
or na.
โโโโ borderTransp (int)
โโโโ liteMode (bool)
โโโโ rightCoordinate (int) : the right coordinate of any drawings. Must be a time point.
โโReturns: void
invalidBlockCheck(bullishOBbox, bearishOBbox, userTF)
โโcheck if existing order blocks are still valid
โโParameters:
โโโโ bullishOBbox (array) : an array declared using the UDT orderBlock that contains bullish order block related data
โโโโ bearishOBbox (array) : an array declared using the UDT orderBlock that contains bearish order block related data
โโโโ userTF (simple int)
โโReturns: void (0)
method lastBarRejections(id, rejectionColor, idShow, rejectionString, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
โโdraws rejectionBlocks on last bar
โโNamespace types: array
โโParameters:
โโโโ id (array) : the array, an array of rejection block data declared using the UDT rejection block
โโโโ rejectionColor (color) : the desired color of the rejection box
โโโโ idShow (int)
โโโโ rejectionString (string) : the desired name of the rejection blocks
โโโโ labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
โโโโ borderTransp (int)
โโโโ liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
โโโโ rightCoordinate (int) : atime for the right coordinate of the box
โโโโ masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
โโReturns: void
method OBdraw(id, OBshow, BBshow, OBcol, BBcol, bullishString, bearishString, isBullish, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
โโdraws orderblocks and breaker blocks for data stored in UDT array()
โโNamespace types: array
โโParameters:
โโโโ id (array) : the array, an array of order block data declared using the UDT orderblock
โโโโ OBshow (int) : the number of order blocks to show
โโโโ BBshow (int) : the number of breaker blocks to show
โโโโ OBcol (color) : color of order blocks
โโโโ BBcol (color) : color of breaker blocks
โโโโ bullishString (string) : the title of bullish blocks, which is a regular bullish orderblock or a bearish orderblock that's converted to breakerblock
โโโโ bearishString (string) : the title of bearish blocks, which is a regular bearish orderblock or a bullish orderblock that's converted to breakerblock
โโโโ isBullish (bool) : whether the array contains bullish orderblocks or bearish orderblocks. If bullish orderblocks,
the array will naturally contain bearish BB, and if bearish OB, the array will naturally contain bullish BB
โโโโ labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
โโโโ borderTransp (int)
โโโโ liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
โโโโ rightCoordinate (int) : atime for the right coordinate of the box
โโโโ masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
โโReturns: void
FVG
โโUDT for FVG calcualtions
โโFields:
โโโโ H (series float) : high price of user-selected timeframe
โโโโ L (series float) : low price of user-selected timeframe
โโโโ direction (series string) : FVG direction => "Up" or "Down"
โโโโ T (series int) : => time of bar on user-selected timeframe where FVG was created
โโโโ fvgLabel (series label) : optional label for FVG
โโโโ fvgLineTop (series line) : optional line for top of FVG
โโโโ fvgLineBot (series line) : optional line for bottom of FVG
โโโโ fvgBox (series box) : optional box for FVG
labelLine
โโquickly pair a line and label together as UDT
โโFields:
โโโโ lin (series line) : Line you wish to pair with label
โโโโ lab (series label) : Label you wish to pair with line
orderBlock
โโUDT for order block calculations
โโFields:
โโโโ orderBlockData (array) : array containing order block x and y points
โโโโ orderBlockBox (series box) : optional order block box
โโโโ vioCount (series int) : = 0 violation count of the order block. 0 = Order Block, 1 = Breaker Block
โโโโ traded (series bool)
โโโโ status (series string) : = "OB" status == "OB" => Level is order block. status == "BB" => Level is breaker block.
โโโโ orderBlockLab (series label) : options label for the order block / breaker block.
strongPoints
โโUDT for strong highs and strong lows
โโFields:
โโโโ price (series float) : price of the strong high or strong low
โโโโ timeAtprice (series int) : time of the strong high or strong low
โโโโ strongPointLabel (series label) : optional label for strong point
โโโโ strongPointLine (series line) : optional line for strong point
โโโโ overlayLine (series line) : optional lines for strong point to enhance visibility
โโโโ overlayLine2 (series line) : optional lines for strong point to enhance visibility
displacement
โโUDT for dispacements
โโFields:
โโโโ highPrice (series float) : high price of displacement
โโโโ lowPrice (series float) : low price of displacement
โโโโ timeAtPrice (series int) : time of bar where displacement occurred
โโโโ displacementBox (series box) : optional box to draw displacement
โโโโ displacementLab (series label) : optional label for displacement
po3data
โโUDT for po3 calculations
โโFields:
โโโโ dHigh (series float) : higher timeframe high price
โโโโ dLow (series float) : higher timeframe low price
โโโโ dOpen (series float) : higher timeframe open price
โโโโ dClose (series float) : higher timeframe close price
โโโโ po3box (series box) : box to draw po3 candle body
โโโโ po3line (array) : line array to draw po3 wicks
โโโโ po3Labels (array) : label array to label price points of po3 candle
macros
โโUDT for session macros
โโFields:
โโโโ sessions (array) : Array of sessions, you can populate this array using the "quickTime" function located above "export macros".
โโโโ prices (matrix) : Matrix of session data -> open, high, low, close, time
โโโโ sessionTimes (array) : Array of session names. Pairs with array sessions.
โโโโ sessionLines (matrix) : Optional array for sesion drawings.
OTEtimes
โโUDT for data storage and drawings associated with OTE strategy
โโFields:
โโโโ upTimes (array) : time of highest point before trade is taken
โโโโ dnTimes (array) : time of lowest point before trade is taken
โโโโ tpLineLong (series line) : line to mark tp level long
โโโโ tpLabelLong (series label) : label to mark tp level long
โโโโ slLineLong (series line) : line to mark sl level long
โโโโ slLabelLong (series label) : label to mark sl level long
โโโโ tpLineShort (series line) : line to mark tp level short
โโโโ tpLabelShort (series label) : label to mark tp level short
โโโโ slLineShort (series line) : line to mark sl level short
โโโโ slLabelShort (series label) : label to mark sl level short
sweeps
โโUDT for data storage and drawings associated with liquidity sweeps
โโFields:
โโโโ upSweeps (matrix) : matrix containing liquidity sweep price points and time points for up sweeps
โโโโ dnSweeps (matrix) : matrix containing liquidity sweep price points and time points for down sweeps
โโโโ upSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
โโโโ dnSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
raidExitDrawings
โโUDT for drawings associated with the Liquidity Raid Strategy
โโFields:
โโโโ tpLine (series line) : tp line for the liquidity raid entry
โโโโ tpLabel (series label) : tp label for the liquidity raid entry
โโโโ slLine (series line) : sl line for the liquidity raid entry
โโโโ slLabel (series label) : sl label for the liquidity raid entry
m2022
โโUDT for data storage and drawings associated with the Model 2022 Strategy
โโFields:
โโโโ mTime (series int) : time of the FVG where entry limit order is placed
โโโโ mIndex (series int) : array index of FVG where entry limit order is placed. This requires an array of FVG data, which is defined above.
โโโโ mEntryDistance (series float) : the distance of the FVG to the 50% range. M2022 looks for the fvg closest to 50% mark of range.
โโโโ mEntry (series float) : the entry price for the most eligible fvg
โโโโ fvgHigh (series float) : the high point of the eligible fvg
โโโโ fvgLow (series float) : the low point of the eligible fvg
โโโโ longFVGentryBox (series box) : long FVG box, used to draw the eligible FVG
โโโโ shortFVGentryBox (series box) : short FVG box, used to draw the eligible FVG
โโโโ line50P (series line) : line used to mark 50% of the range
โโโโ line100P (series line) : line used to mark 100% (top) of the range
โโโโ line0P (series line) : line used to mark 0% (bottom) of the range
โโโโ label50P (series label) : label used to mark 50% of the range
โโโโ label100P (series label) : label used to mark 100% (top) of the range
โโโโ label0P (series label) : label used to mark 0% (bottom) of the range
โโโโ sweepData (array)
silverBullet
โโUDT for data storage and drawings associated with the Silver Bullet Strategy
โโFields:
โโโโ session (series bool)
โโโโ sessionStr (series string) : name of the session for silver bullet
โโโโ sessionBias (series string)
โโโโ sessionHigh (series float) : = high high of session // use math.max(silverBullet.sessionHigh, high)
โโโโ sessionLow (series float) : = low low of session // use math.min(silverBullet.sessionLow, low)
โโโโ sessionFVG (series float) : if applicable, the FVG created during the session
โโโโ sessionFVGdraw (series box) : if applicable, draw the FVG created during the session
โโโโ traded (series bool)
โโโโ tp (series float) : tp of trade entered at the session FVG
โโโโ sl (series float) : sl of trade entered at the session FVG
โโโโ sessionDraw (series box) : optional draw session with box
โโโโ sessionDrawLabel (series label) : optional label session with label
silverBulletDrawings
โโUDT for trade exit drawings associated with the Silver Bullet Strategy
โโFields:
โโโโ tpLine (series line) : tp line drawing for strategy
โโโโ tpLabel (series label) : tp label drawing for strategy
โโโโ slLine (series line) : sl line drawing for strategy
โโโโ slLabel (series label) : sl label drawing for strategy
unicornModel
โโUDT for data storage and drawings associated with the Unicorn Model Strategy
โโFields:
โโโโ hPoint (chart.point)
โโโโ hPoint2 (chart.point)
โโโโ hPoint3 (chart.point)
โโโโ breakerBlock (series box) : used to draw the breaker block required for the Unicorn Model
โโโโ FVG (series box) : used to draw the FVG required for the Unicorn model
โโโโ topBlock (series float) : price of top of breaker block, can be used to detail trade entry
โโโโ botBlock (series float) : price of bottom of breaker block, can be used to detail trade entry
โโโโ startBlock (series int) : start time of the breaker block, used to set the "left = " param for the box
โโโโ includes (array) : used to store the time of the breaker block, or FVG, or the chart point sequence that setup the Unicorn Model.
โโโโ entry (series float) : // eligible entry price, for longs"math.max(topBlock, FVG.get_top())",
โโโโ tpLine (series line) : optional line to mark PT
โโโโ tpLabel (series label) : optional label to mark PT
โโโโ slLine (series line) : optional line to mark SL
โโโโ slLabel (series label) : optional label to mark SL
rejectionBlocks
โโUDT for data storage and drawings associated with rejection blocks
โโFields:
โโโโ rejectionPoint (chart.point)
โโโโ bodyPrice (series float) : candle body price closest to the rejection point, for "Up" rejections => math.max(open, close),
โโโโ rejectionBox (series box) : optional box drawing of the rejection block
โโโโ rejectionLabel (series label) : optional label for the rejection block
equalLevelsDraw
โโUDT for data storage and drawings associated with equal highs / equal lows
โโFields:
โโโโ connector (series line) : single line placed at the first high or low, y = avgerage of distinguished equal highs/lows
โโโโ connectorLab (series label) : optional label to be placed at the highs or lows
โโโโ levels (array) : array containing the equal highs or lows prices
โโโโ times (array) : array containing the equal highs or lows individual times
โโโโ startTime (series int) : the time of the first high or low that forms a sequence of equal highs or lows
โโโโ radiate (array) : options label to "radiate" the label in connector lab. Can be used for anything
necessaryData
โโUDT for data storage of historical price points.
โโFields:
โโโโ highArr (array) : array containing historical high points
โโโโ lowArr (array) : array containing historical low points
โโโโ timeArr (array) : array containing historical time points
โโโโ logArr (array) : array containing historical log returns
โโโโ signArr (array) : array containing historical price directions
โโโโ closeArr (array) : array containing historical close points
โโโโ binaryTimeArr (array) : array containing historical time points, uses "push" instead of "unshift" to allow for binary search
โโโโ binaryCloseArr (array) : array containing historical close points, uses "push" instead of "unshift" to allow the correct
โโโโ binaryOpenArr (array) : array containing historical optn points, uses "push" instead of "unshift" to allow the correct
โโโโ atrTFarr (array) : array containing historical user-selected TF atr points
โโโโ openArr (array) : array containing historical open points
Timeframe PivotsUse this tool to plot open prices from any timeframe as a pivot level with the option to go advanced and turn on extensions (instructions below), which review the relationship between previous and current open prices to build range extensions up to six levels wide.
Please be aware extensions, nor vwap are not enabled by default! It is up to the user to determine how they wish to setup this indicator. Please read the full description for utilizing this indicator so that it's well known the complete feature set and understanding of how to enable additional plots, complete instruction is provided for all users below.
Default configuration example:
To enable extensions the user must open the indicator configuration by clicking the gear icon for "Timeframe Pivots", depending on screen resolution scrolling with mouse may need to occur in order to find the section labeled "Extensions", use the mouse or equivalent human interface device to check the checkbox to the right of the color plots and line type drop down.
Extensions enabled example:
Timeframe Selection
Timeframes available to the indicator are any timeframe the platform makes available to the user by default, or also if the TradingView user has higher tier plan to create custom timeframes - those should be available as well. To adjust timeframe the user must open the indicator configuration by clicking the gear icon for "Timeframe Pivots", depending on screen resolution scrolling with mouse may need to occur in order to find the input labeled "Timeframe", use the mouse or equivalent human interface device select the drop down and select timeframe suitable to users application.
How the extension width and extensions are calculated:
The exact process takes the new timeframe change open price calculates the difference between prior open, once that has been completed then it's divided in half to build extensions.
Code example:
Extension Width = (Open - Open ) / 2
How the extensions are calculated:
// +1 for positive extension, -1 for negative extension
(Extension Width * (Configured Multiplier * 1)) + Pivot Open Price
+1 Extension:
$5 * (1.0 * 1) + $400 = $405
-1 Extension:
$5 * (1.0 * -1) + $400 = $395
So it should be established how each projected extension, either positive or negative, is created.
Range bound market detection and notes:
One note regarding the ranges, sometimes the open prices of each period can be close in proximity to their predecessor, there's not enough range to build meaningful projections. In these situations this means the market is most likely range bound and prior range data is utilized to continue providing guidance. This addresses an issue with other pivot indicators that will instead blindly follow price and present useless pivot ranges.
It does this through detection of average half range widths, the last 14 ranges to be exact, if the current, (open - open / 2), half range width is smaller than the average, prior half range width will be used.
Code example:
// assume past half range widths are 10, 8, 9, 5, 14, 7, 7, 9, 10, 10, 4, 7, 7, 8
float v_halfRangeWidthToUseForExtensions = na
v_priorHalfRangeWidth = 10
v_avgHalfRangeWidth = 8.2 // past range widths sum = 115 / 14
v_newHalfRangeWidthToUseForExtensions = 2 // new open - open is tiny compared to avg
if v_newHalfRangeWidthToUseForExtensions < v_avgHalfRangeWidth
// replace new half range width with previous one
v_newHalfRangeWidthToUseForExtensions := v_priorHalfRangeWidth
In the code example above if the new half range width was above or equal to the rolling average, no adjustment would be made by the indicator.
VWAP
Additional feature of showing vwap, anchored to the same timeframe as the pivot, provides a trend and volume analysis within the confines of the pivots range.
The user must open the indicator configuration by clicking the gear icon for "Timeframe Pivots", scroll using mouse to the "VWAP" section and click the checkbox next to the "Source" field, past the color plots. They are not enabled by default!
The user can also add the bands for VWAP by clicking the checkbox next to the "Bands" field, past the color plots. They are not enabled by default!
VWAP calculations begin from open price of new timeframe change, then afterwards the "Source" set is utilized, the default is HLC3 which is standard for VWAP indicators.
Multiple Timeframe Analysis (MTFA)
It's simple to create a unique combination of favored timeframes for multiple timeframe analysis, consider daily, weekly and monthly combined analysis for powerful indications of market sentiment and directional bias.
Example MTFA demonstration:
Why was this created?
I created this while investigating the efficacy of open price ranges, it became apparent that these pivot ranges are some of the more price respecting pivots I've ever observed. I also grew tired of lack of price adherence to other pivot indicators widely available.
There exists a relationship between each timeframes open price in comparison to prior open price, if the market is willing to navigate to a prior lower open price from higher open price, it could be perceived as bearish and the extensions (if enabled as instructed above), could be suitable range based projections for future price movements.
Example comparison:
As can be seen, and there are many examples, where Timeframe Pivots provides more discreet levels and potential explanations for price movements.
[KVA]Body Percentage Counter This indicator presents a comprehensive view of the historical candle data within user-defined body percentage ranges. Each column represents a specific body size percentage threshold, starting from as low as 0.01% and extending up to 20%.
The rows categorize candles by their closing and opening price differences, effectively sorting them into green (bullish) and red (bearish) candles based on whether they closed higher or lower than their opening prices.
First Row of the table is the bu
For developers, this table can be immensely useful in determining stop-loss ranges. By analyzing the frequency of candles that fall within certain body percentage ranges, developers can better understand where to set stop-loss orders. For instance, if a developer notices a high frequency of candles with body sizes within a specific percentage range, they may choose to set their stop-loss orders outside of this range to avoid being stopped out by normal market fluctuations.
Moreover, the indicator can be used to:
Volatility Assessment : The indicator can be used to gauge market volatility. Smaller bodies may indicate consolidation periods, while larger bodies might suggest more volatile market conditions.
Optimize Trading Strategies : Adjust entry and exit points based on the prevalence of certain candle sizes.
Risk Management : Determine the commonality of price movements within a certain range to better manage risks.
Backtesting : Use historical data to backtest how different stop-loss ranges would have performed in the past.
Comparative Analysis : Traders can compare the frequency of different body sizes over a selected period, providing insights into how the market is evolving.
Educational Use : For new traders, the indicator can serve as an educational tool to understand the implications of candlestick sizes and their relationship with market dynamics
The data provided in this output can guide developers to make more informed decisions about where to place stop-loss orders, potentially increasing the effectiveness of their trading algorithms or manual trading strategies.
The output of the " Body Percentage Counter" indicator is organized into a table format, which can be broken down as follows:
Header (First Row) : This row lists the body percentage thresholds used to categorize the candles. It starts from 0.01% and increases incrementally to 20%. These thresholds are likely set by the user and represent the range of candle body sizes as a percentage of the total candle size.
Green Candle Count (Second Row) : This row displays the count of green candlesโcandles where the close price is higher than the open priceโthat fall within each body percentage threshold. For example, under the column "0.01", the number 25 indicates there are 25 green candles whose body size is 0.01% of the total candle size.
Red Candle Count (Third Row) : This row shows the count of red candlesโcandles where the close price is lower than the open priceโfor each body percentage threshold. The numbers in this row reflect the number of red candles that match the body percentage criteria in the corresponding column.
Total Candle Count (Fourth Row) : This row sums the counts of both green and red candles for each body percentage threshold, providing a total count of candles that have a body size within the specific range. For instance, if under "0.01" the green count is 25 and the red count is 26, then the total would be 51.
This organized data representation allows users to quickly assess the distribution of candle body sizes over a historical period, which is especially useful for determining the frequency of price movements that are significant enough to consider for stop-loss settings or other trade management decisions.
Sessions [LuxAlgo]This indicator shows when user set sessions are active and returns various tools + metrics using the closing price within active sessions as an input. Users have the option to change up to 4 session times.
The indicator will increasingly lack accuracy when the chart timeframe is higher than 1 hour.
Settings
Sessions
Enable Session: Allows to enable or disable all associated elements with a specific user set session.
Session Time: Opening and closing times of the user set session in the hh:mm format.
Range: Highlights the associated session range on the chart.
Trendline: Returns the associated session trendline on the chart.
Mean: Returns the associated session mean average on the chart.
VWAP: Returns the associated session volume weighted average price on the chart.
Ranges Settings
Range Area Transparency: Transparency of the area highlighting sessions ranges.
Range Outline: Highlights the borders of the session range area.
Range Label: Shows the session label at the mid-point of the session interval.
Dashboard
Show Dashboard: Enables sessions dashboard on the chart.
Advanced Dashboard: Returns more information regarding user set sessions on the dashboard.
Dividers
Show Session Divider: Highlights active sessions using intervals on the bottom of the chart (this can lead to less responsive charts)
Show Daily Divider: Highlights days on the chart.
Usage
This tool is versatile and allows the user to perform a wide variety of tasks all focusing on highlighting and analyzing price movements within a specific user set session in a periodic fashion.
Significant forex trading sessions are used by default, but the users are free to choose the opening and closing time of their choices.
Using ranges can indicate which sessions returned the most volatile price movements.
Trendlines can be useful to estimate the underlying trend of a specific session, but they can also offer a quick way to see which session started a trend reversal.
The session Mean highlights the equilibrium level within a session, extrapolating these levels can provide potential support and resistances levels of interest.
Finally, users can use the sessions VWAP's for real time applications, using them as trailing supports and resistances.
Using The Advanced Dashboard
The advanced dashboard returns useful information regarding the user set sessions. Each dashboard elements are described below:
Status: Highlights whether the user set session is active (open) of inactive (closed).
Trend: Shows correlation coefficient between the session prices and a linear sequence of values. Values above 0 indicates an up-trending session, while values under 0 indicates a down-trending session. Values closer to (1, -1) indicates a more trending session.
Volume: Shows accumulated volume within the session
ฯ (Standard Deviation): Shows standard deviation of the session, while this value is not bounded it can be useful to compare it with the other ones to see which session was the most volatile.
Note that when a session becomes inactive the value on the dashboard will hold until the specific session becomes active again.
ORB Advanced Cloud Indicator & FIB's by TenAMTraderSummary: ORB Advanced Cloud Indicator with Alerts and Fibonacci Retracement Targets by TenAMTrader
This TradingView script is an advanced version of the Opening Range Breakout (ORB) indicator, enhanced with visual clouds and Fibonacci retracement/extension levels. It is designed to help traders identify key price levels and track price movements relative to those levels throughout the trading day. The script includes alert functionalities to notify traders when price crosses key levels and when Fibonacci levels are reached, which can serve as potential entry and exit targets.
Key Features:
Primary and Secondary Range Calculation:
The indicator calculates the primary range (defined by a start and end time) and optionally, a secondary range.
The primary range includes the highest and lowest prices during the designated time period, as well as the midpoint of this range.
The secondary range (if enabled) tracks another price range during a second time period, with its own high, low, and midpoint.
Visual Clouds:
The script draws colored clouds between the high, midpoint, and low of the opening range.
The upper cloud spans between the Opening High and Midpoint, while the lower cloud spans between the Midpoint and Opening Low.
Similarly, a second set of clouds can be drawn for the secondary range (if enabled).
Fibonacci Levels:
The script calculates Fibonacci retracement and extension levels based on the primary range (the difference between the Opening High and Opening Low).
Fibonacci levels can be used as entry and exit targets in a trading strategy, as these levels often act as potential support/resistance zones.
Fibonacci levels include standard values like -0.236, -0.382, -0.618, and positive extensions like 1.236, 1.618, etc.
Customizable Alerts:
Alerts can be set to trigger when:
The price crosses above the Opening High.
The price crosses below the Opening Low.
The price crosses the Opening Midpoint.
These alerts can help traders act quickly on important price movements relative to the opening range.
Customization Options:
The indicator allows users to adjust the time settings for both the primary and secondary ranges.
Custom colors can be set for the lines, clouds, and Fibonacci levels.
The visibility of each line and cloud can be toggled on or off, giving users flexibility in how the chart is displayed.
Fibonacci Levels Overview:
The script includes several Fibonacci retracement and extension levels:
Negative Retracements (e.g., -0.236, -0.382, -0.50, -0.618, etc.) are plotted below the Opening Low, and can act as potential support levels in a downtrend.
Positive Extensions (e.g., 1.236, 1.382, 1.618, 2.0, etc.) are plotted above the Opening High, and can act as potential resistance levels in an uptrend.
Fib levels can be used as entry and exit targets to capitalize on price reversals or breakouts.
Safety Warning:
This script is for educational and informational purposes only and is not intended as financial advice. While it provides valuable technical information about price ranges and Fibonacci levels, trading always involves risk. Users are encouraged to:
Paper trade or use a demo account before applying this indicator with real capital.
Use proper risk management strategies, including stop-loss orders, to protect against unexpected market movements.
Understand that no trading strategy, indicator, or tool can guarantee profits, and losses can occur.
Important: The creator, TenAMTrader, and TradingView are not responsible for any financial losses resulting from the use of this script. Always trade responsibly, and ensure you fully understand the risks involved in any trading strategy.