Forex - Lot size calculatorThis indicator is specifically designed for Forex traders who need a convenient lot size calculator directly on their charts. It allows users to input their account balance, risk percentage, and stop-loss distance in pips to easily determine the appropriate lot size for a given trade, ensuring effective risk management.
Key Features:
Lot Size Calculation: Automatically calculates the lot size based on user-defined inputs: account balance, risk percentage, and stop-loss distance.
Error Handling: The indicator only works with Forex pairs. If applied to non-Forex assets, a clear and prominent red error message will appear in the bottom-right corner of the chart, reminding the user that this script is intended exclusively for Forex trading.
Simple Visualization: The calculated lot size is displayed in an easy-to-read table directly on the chart.
How to Use:
Add the indicator to a Forex chart.
Enter your account balance, risk percentage, and stop-loss pips in the input fields.
The indicator will display the calculated lot size for the chosen Forex pair.
Important Notes:
This script is intended only for Forex assets. If used on other instruments (e.g., stocks, crypto, indices), an error message will be shown.
Always validate lot sizes with your broker, as there can be slight variations depending on broker specifications and leverage settings.
지표 및 전략
SMI Ergodic Indicator/Oscillator of Money Flow Index▮ Introduction
The Stochastic Momentum Index Ergodic (SMII) indicator is a technical analysis tool designed to predict trend reversals in the price of an asset.
It functions as a momentum oscillator, measuring the ratio of the smoothed price change to the smoothed absolute price change over a given number of previous periods.
The Ergodic SMI is based on the True Strength Index (TSI) and integrates a signal line, which is an exponential moving average (EMA) of the SMI indicator itself.
The Ergodic SMI oscillator provides a clearer picture of market trends than the traditional stochastic oscillator by incorporating the concept of 'ergodicity', which helps remove market noise.
On ther other hand, MFI (Money Flow Index) is a technical analysis indicator used to measure the inflow of money into an asset and thus help identify buying and selling pressure in a given financial instrument.
When these two indicators are combined, they can provide a more comprehensive view of price direction and market strength.
▮ Motivation: why another indicator?
By combining SMII with MFI, we can gain even more insights into the market.
One way to do this is to use the MFI as an input to the SMII, rather than just using price.
This means we are measuring momentum based on buying and selling pressure rather than just price.
Furthermore, there is the possibility of making several fine adjustments to both the calculation and visualization parameters that are not present in other indicators.
▮ What to look for
When using the SMII MFI indicator, there are a few things to look out for.
First, look at the SMII signal line.
When the line crosses above -40, it is considered a buy signal, while the crossing below +40 is considered a sell signal.
Also, pay attention to divergences between the SMII and the price.
If price is rising but the SMII is showing negative divergence, it could indicate that momentum is waning and a reversal could be in the offing.
Likewise, if price is falling but the SMII is showing positive divergence, this could indicate that momentum is building and a reversal could also be in the offing.
Divergences can be considered in both indicator and/or histogram.
Examples:
▮ Notes
The indicator presented here offers both the 'SMII' and the 'SMIO', that is, the 'Stochastic Momentum Index Ergodic Indicator' together with the 'Stochastic Momentum Index Ergodic Oscillator' (histogram), as per the documentation described in reference links.
So it is important to highlight the differences in relation to my other indicator, the 'Stochastic Momentum Index (SMI) of Money Flow Index (MFI)':
This last one is purely based on the SMI , which is implemented using SMA smoothing for the relative range and the high/low range.
Although they may seem the same in some situations, the calculation is actually different. The TSI tends to be more responsive at the expense of being noisier, while the SMI tends to be smoother. Which of these two indicators is best depends on the situation, the context, and the analyst's personal preference.
Please refer to reference links to more info.
▮ References
SMI documentation
SMII documentation
SMIO documentation
MFI documentation
Zero-Lag MA Trend Levels [ChartPrime] The Zero-Lag MA Trend Levels indicator combines a Zero-Lag Moving Average (ZLMA) with a standard Exponential Moving Average (EMA) to provide a dynamic view of the market trend. This indicator uses a color-changing cloud to represent shifts in trend momentum and plots key levels when trend reversals are detected. The addition of trend level boxes helps identify significant price zones where market shifts occur, with retest signals aiding in spotting potential continuation or reversal points.
⯁ KEY FEATURES & HOW TO USE
⯌ Zero-Lag Moving Average (ZLMA) with EMA Cloud :
The indicator employs a Zero-Lag Moving Average (ZLMA) alongside a standard EMA.
series float emaValue = ta.ema(close, length) // EMA of the closing price
series float correction = close + (close - emaValue) // Correction factor for zero-lag calculation
series float zlma = ta.ema(correction, length) // Zero-Lag Moving Average (ZLMA)
The cloud between these averages changes color depending on the trend direction. During a downtrend, if the ZLMA begins to increase, the cloud partially turns green, signaling potential strength. Conversely, during an uptrend, if the ZLMA decreases, the cloud partially turns to the downtrend color (blue by default), indicating potential weakness.
Use : Traders can monitor the cloud's color shifts for early signs of changing momentum. A fully colored cloud aligning with the current trend indicates a strong directional move, while mixed colors suggest a potential trend change.
⯌ Trend Shift and Level Boxes :
Each time a crossover between the EMA and the ZLMA occurs, indicating a trend shift, the indicator plots a box around the price level where the shift occurred. This box remains on the chart to mark the price zone of the trend change.
Use : The boxes provide clear visual markers of where market sentiment shifted. These levels can act as support and resistance zones. Traders can use these boxes to identify potential entry or exit points when the market retests these key levels.
⯌ Retest Detection with Labels :
If the price action crosses a previously plotted trend level box, the indicator marks this event with triangle labels. An upward triangle (▲) appears when the price retests the top of a box during a bullish crossover, and a downward triangle (▼) appears when the price retests the bottom of a box during a bearish crossunder.
Use : These labels help traders identify potential continuation or reversal points at critical price levels, offering additional confirmation for trading decisions.
⯌ Dynamic Color-Coding :
The color of the ZLMA and the EMA is adjusted according to their current trend direction, with the ZLMA adopting green for upward trends and blue for downward trends. This visual representation makes it easier to quickly gauge the market's momentum at a glance.
Use : Traders can use the color-coding to quickly assess the strength and direction of the current trend, allowing for more informed decision-making.
⯁ USER INPUTS
Length : Sets the period for both the ZLMA and EMA calculations.
Trend Levels : Toggle to display the trend level boxes on the chart.
Colors (+ / -) : Define the colors for bullish and bearish trends.
⯁ CONCLUSION
The Zero-Lag MA Trend Levels - ChartPrime indicator offers a nuanced approach to trend detection by combining the ZLMA with a traditional EMA. Its dynamic cloud color changes, trend level boxes, and retest labels make it a versatile tool for traders seeking to identify trend shifts and key price zones effectively. By incorporating elements of support and resistance along with trend momentum, this indicator provides a comprehensive view of market dynamics for both trend-following and counter-trend trading strategies.
Bubbles Volume [BigBeluga]The Bubbles Volume indicator is an innovative visualization tool designed to represent trading volume in a more intuitive and visually appealing manner. By displaying volume as bubbles of varying sizes and colors on the price chart, this indicator helps traders quickly identify significant volume levels and potential areas of interest.
Important Note:
For correct visual representation of indicator, layout it to front:
🔵 KEY FEATURES
● Volume Bubbles
Represents trading volume as bubbles on the price chart
Bubble size increases with higher volume levels
Color intensity changes based on volume significance
Provides an intuitive visual representation of volume distribution
● Heatmap Coloring
Optional feature to color bubbles based on volume intensity
Uses a color gradient from cool (low volume) to hot (high volume) colors
Helps quickly identify extremely high volume areas
● Significant Volume Levels
Option to display horizontal lines at significant volume levels
Shows volume amount as labels for highly significant levels
Helps identify potential support/resistance areas based on volume
Volume Levels:
Levels with HeatMap:
Levels without Volume Bubles:
● Normalized Volume Calculation
Uses normalized volume to account for overall market volume trends
Provides a more accurate representation of volume significance
🔵 HOW TO USE
● Volume Analysis
Larger bubbles indicate higher trading volume
Clusters of large bubbles may suggest areas of high interest or potential reversals
Use in conjunction with price action to identify potential breakouts or fakeouts
● Trend Confirmation
Strong trends often show increasing bubble sizes in the trend direction
Diminishing bubble sizes might indicate weakening trends
● Support and Resistance
Significant volume levels (displayed as lines) can act as potential support/resistance
Pay attention to price reactions at these levels for trading opportunities
● Divergences
Look for divergences between price action and bubble sizes
Price making new highs/lows with smaller bubbles might indicate weakening momentum
● Volatility Assessment
Periods with consistently large bubbles indicate high volatility
Can be used to adjust trading strategies or position sizing
🔵 CUSTOMIZATION
The Bubbles Volume indicator offers several customization options:
Toggle bubble display on/off
Adjust volume threshold for filtering low volume bubbles
Enable/disable heatmap coloring for enhanced visual analysis
Show/hide significant volume levels
Adjust the number of significant levels displayed
Customize colors to suit personal preferences
By fine-tuning these settings, traders can adapt the indicator to various market conditions and personal analysis preferences.
The Bubbles Volume indicator provides a unique and intuitive way to visualize trading volume directly on the price chart. This approach allows traders to quickly identify areas of significant trading activity and potential price levels of interest without the need for a separate volume sub-chart.
This tool can be particularly useful for traders focusing on volume analysis, breakout strategies, or those looking to confirm price action with volume. The visual nature of the bubbles makes it easy to spot volume patterns and anomalies at a glance, potentially leading to faster and more informed trading decisions.
As with all technical indicators, it's recommended to use the Bubbles Volume indicator in conjunction with other forms of analysis and within the context of a well-defined trading strategy. While this indicator provides valuable volume insights, it should be considered alongside other factors such as overall market trends, price patterns, and fundamental analysis when making trading decisions.
Boosted Moving AverageOverview:
The Boosted Moving Average (BMA) is designed to enhance the traditional Exponential Moving Average (EMA) by introducing a boositng factor that amplifies its responsiveness to price changes. This means that the BMA will react more quickly to significant market movements, while still maintaining a smooth trajectory.
Key Features:
Boost Factor Sensitivity: Adjust the BMA's reactivity to price movements. A higher boost factor makes it more responsive, ideal for traders who want to catch price shifts early.
Dual EMA Calculation: The BMA combines two EMAs with different lengths to create a divergence that forms the basis for boosted values. This dual approach helps refine entry and exit points.
Smoothing: After boosting, the moving average is smoothed using another EMA, ensuring you get the clearest possible signal without over-complicating things.
Bullish/Bearish Coloring: The plot changes color based on the current trend, making it easy to visualize market direction:
How It Works:
The script calculates two EMAs: one with the given length and one with half that length.
The boost factor amplifies the difference between these two EMAs to provide an enhanced signal.
A final EMA is applied to smooth the resulting boosted moving average, ensuring clarity in market direction.
Color-coded trends make it easy to see if the market is bullish (green) or bearish (red).
Iceberg Trade Revealer [CHE]Unveiling Iceberg Trades: A Deep Dive into Low Volatility Market Phases
Introduction
In the dynamic world of trading, hidden forces often influence market movements in ways that aren't immediately apparent. One such force is the phenomenon of iceberg trades—large orders that are concealed to prevent significant market impact. This presentation explores the concept of iceberg trades, explains why they are typically hidden during periods of low volatility, and introduces an indicator designed to reveal these elusive trades.
Agenda
1. Understanding Iceberg Trades
- Definition and Purpose
- Impact on Market Dynamics
2. The Low Volatility Concealment
- Why Low Volatility Phases?
- Strategies Behind Hiding Large Orders
3. Introducing the Iceberg Trade Revealer Indicator
- How the Indicator Works
- Key Components and Calculations
4. Demonstration and Use Cases
- Interpreting the Indicator Signals
- Practical Trading Applications
5. Conclusion
- Summarizing the Insights
- Q&A Session
1. Understanding Iceberg Trades
Definition and Purpose
- Iceberg Trades are large single orders divided into smaller lots to disguise the total order quantity.
- Traders use iceberg orders to minimize market impact and avoid unfavorable price movements.
Impact on Market Dynamics
- Concealed Volume: Iceberg orders hide true supply and demand levels.
- Price Stability: They prevent sudden spikes or drops by releasing orders gradually.
- Market Sentiment: Their presence can influence perceptions of market strength or weakness.
2. The Low Volatility Concealment
Why Low Volatility Phases?
- Less Market Attention: Low volatility periods attract fewer traders, making it easier to conceal large orders.
- Reduced Slippage: Prices are more stable, reducing the risk of executing orders at unfavorable prices.
- Strategic Advantage: Large players can accumulate or distribute positions without tipping off the market.
Strategies Behind Hiding Large Orders
- Order Splitting: Breaking down large orders into smaller pieces.
- Time Slicing: Executing orders over an extended period.
- Algorithmic Trading: Using sophisticated algorithms to optimize order execution.
3. Introducing the Iceberg Trade Revealer Indicator
How the Indicator Works
- Core Thesis: Iceberg trades can be detected by analyzing periods of unusually low volatility.
- Volatility Analysis: Uses the Average True Range (ATR) and Bollinger Bands to identify low volatility phases.
- Signal Generation: Marks periods where iceberg trades are likely occurring.
Key Components and Calculations
1. Average True Range (ATR)
- Measures market volatility over a specified period.
- Lower ATR values indicate less price movement.
2. Bollinger Bands
- Creates a volatility envelope around the ATR.
- Bands tighten during low volatility and widen during high volatility.
3. Timeframe Adjustments
- Utilizes multiple timeframes to enhance signal accuracy.
- Options for auto, multiplier, or manual timeframe selection.
4. Signal Conditions
- Iceberg Trade Detection: ATR falls below the lower Bollinger Band.
- Revealed Volatility: ATR rises above the upper Bollinger Band, indicating potential market moves after iceberg trades.
4. Demonstration and Use Cases
Interpreting the Indicator Signals
- Iceberg Trade Zones: Highlighted areas where large hidden orders are likely.
- Revealed Volatility Zones: Areas indicating the market's response to the execution of iceberg trades.
Practical Trading Applications
- Entry and Exit Points: Use signals to time trades alongside institutional activity.
- Risk Management: Adjust strategies during detected low volatility phases.
- Market Analysis: Gain insights into underlying market mechanics.
5. Conclusion
Summarizing the Insights
- Iceberg Trades play a significant role in market movements, especially when concealed during low volatility phases.
- The Iceberg Trade Revealer Indicator provides a tool to uncover these hidden activities, offering traders a strategic edge.
- Understanding and utilizing this indicator can enhance trading decisions by aligning them with the actions of major market players.
Best regards Chervolino ( Volker )
Q&A Session
- Questions and Discussions: Open the floor for any queries or further explanations.
Thank You!
By delving into the hidden aspects of market activity, traders can better navigate the complexities of financial markets. The Iceberg Trade Revealer Indicator serves as a bridge between observable market data and the concealed strategies of large institutions.
References
- Average True Range (ATR): A technical analysis indicator that measures market volatility.
- Bollinger Bands: A volatility indicator that creates a band of three lines which are plotted in relation to a security's price.
- Iceberg Orders: Large orders divided into smaller lots to hide the actual order quantity.
Note: Always consider multiple factors when making trading decisions. Indicators provide tools, but they do not guarantee results.
Educational Content Disclaimer:
Disclaimer:
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Hma Swing Points | viResearchHma Swing Points | viResearch
Conceptual Foundation and Innovation
The "Hma Swing Points" script introduces a simple yet effective method for identifying key swing points in the market using Hull Moving Averages (HMA). The Hull Moving Average is a faster and smoother alternative to traditional moving averages, making it ideal for detecting significant price swings. By applying HMA to both high and low prices, the script identifies swing highs and lows, providing traders with visual cues for potential trend reversals or continuations. This approach helps traders recognize turning points in the market with minimal lag, allowing for more precise entries and exits.
Technical Composition and Calculation
This script uses two Hull Moving Averages—one for the high prices and another for the low prices. These HMAs offer smoother trend detection while filtering out market noise. The script identifies the highest and lowest HMA values over a user-defined lookback period to determine the swing high and swing low points. Long signals are generated when the current HMA of the highs matches the highest value within the lookback period, while short signals are generated when the HMA of the lows matches the lowest value. These signals are plotted on the chart, and alerts can be set to notify the trader of possible entry or exit points.
Features and User Inputs
The script offers several customizable inputs to adjust its sensitivity and behavior according to the trader’s preferences. The lookback period defines the number of bars used to calculate the highest and lowest HMA values, allowing traders to control how responsive the script is to price changes. The length of the Hull Moving Average can also be modified, giving traders flexibility in smoothing the indicator. Additionally, optional bar color settings provide visual cues, with bullish and bearish trends highlighted. Alerts are included to notify traders when long or short swing points are detected, ensuring they are informed even when not actively monitoring the chart.
Practical Applications
The "Hma Swing Points" script is useful for traders who aim to identify critical market turning points and potential reversals. It is especially effective in trending markets where price swings present trading opportunities. Traders can use the script to detect reversals by spotting swing points that indicate a possible shift from bullish to bearish trends, or vice versa. The script also helps confirm ongoing trends by showing the strength of swings, allowing traders to make informed decisions about entering or exiting trades. Its ability to mark precise swing points enhances trade timing, helping traders optimize their entries and exits.
Advantages and Strategic Value
The script offers a streamlined approach to detecting swing points with the speed and smoothness of the Hull Moving Average. This makes it easier to filter out false signals and noise, improving the accuracy of trend identification. The customizable inputs allow traders to tailor the script for different assets and market conditions, making it versatile for various trading styles. By highlighting key swing points, the script provides traders with clear visual signals for potential reversals and trend confirmations, enhancing their ability to follow and act on market movements.
Summary and Usage Tips
Incorporating the "Hma Swing Points" script into a trading strategy helps traders identify market reversals and continuation points more effectively. Adjusting the lookback period and HMA length ensures the script adapts to different assets and market conditions. The alert system ensures traders don’t miss key swing points. As always, backtesting is important to evaluate the script’s performance under various market conditions, and past results may not guarantee future outcomes.
Magic Touch Line DetectorSummary of the Magic Touch Line Detector Script:
Purpose:
The Magic Touch Line Detector script is designed to identify significant price points in the market by analyzing candlestick wicks and bodies. It plots lines based on the detected wicks, classifying them as either ascending or descending. The script tracks how frequently price touches these lines and highlights the "most touched" lines for both ascending and descending categories. This script is particularly useful for traders looking to identify key price levels and trends over time.
How It Works:
Wick and Body Detection:
The script starts by analyzing the highs and lows of candlestick wicks relative to their bodies over a user-defined lookback period. A significant wick is identified based on a specified wick-to-body ratio and a deviation threshold measured against the Average True Range (ATR).
Line Creation:
Once a significant upper or lower wick is detected, the script calculates unconventional highs and lows (i.e., points that differ from the absolute highs and lows of the lookback period). Lines are then drawn from these unconventional price points using the slope between the detected wick and the current bar, ensuring a smooth extension.
Line Refinement and Touch Tracking:
As new bars are added, the script tracks how often the price touches the previously drawn lines. The number of touches each line receives is counted and updated in real-time, and the script ensures that only the most touched line is highlighted.
Highlighting and Labeling:
For each category (ascending and descending), the most touched line is identified and given special highlighting with thicker lines and different colors. Labels are also generated to show the number of touches that the most touched line has received. Old labels are cleared to avoid clutter.
Explanation of the Settings:
Lookback Period for Highs and Lows:
This sets the number of bars the script will use to detect the highest highs and lowest lows. A larger lookback period gives the script a broader context to work with, potentially identifying more significant price points.
Minimum Wick-to-Body Ratio:
This ratio determines what qualifies as a "significant" wick. It compares the length of the wick to the body of the candle. A higher ratio means that only wicks that are much longer than the candle body will be considered significant.
Price Deviation Threshold (in ATR multiples):
This setting controls how much price deviation from the ATR is required for a wick to be deemed significant. It acts as a filter to reduce noise by ignoring smaller wicks that are within normal price movements.
Line Touch Tolerance Factor (ATR multiple):
When checking if a price touches a line, the script uses this setting to define how close the price must be to the line to count as a "touch." This tolerance is a multiplier of the ATR, allowing for some flexibility in what is considered a touch.
Price Difference Threshold:
This defines the minimum price difference required to plot a line. If the price difference between the high and low of a detected wick is too small, the script can avoid plotting a line for insignificant moves.
Slope Adjustment Multiplier:
This multiplier adjusts the slope of the lines that are drawn from detected price points. It affects the length and angle of the lines, allowing users to control how far and at what angle the lines should extend across the chart.
Customization Options:
Show Ascending/Descending Lines:
These toggles allow users to decide whether ascending (bullish) or descending (bearish) lines should be shown on the chart.
Line Color, Style, and Width (for Ascending and Descending Lines):
These settings give users control over how the lines appear visually. You can customize the color, style (solid, dashed, dotted), and width of both ascending and descending lines.
Most Touched Line Color:
Users can define a different color for the "most touched" line, which is automatically identified by the script. This setting helps highlight the line that has been interacted with the most by the price.
How to Use the Script:
Setup the Lookback Period and Deviation Filters:
Start by setting the lookback period and the filters for wick-to-body ratio and deviation threshold. These settings help control the script's sensitivity to market movements.
Refine the Tolerance and Slope:
Adjust the line touch tolerance and slope adjustment multiplier to control how closely the script tracks price touches and how the lines are extended on the chart.
Customize Visuals:
Once the lines are being drawn, customize the colors, styles, and widths to ensure the lines are easy to read on your chart. You can also decide if you want to display both ascending and descending lines or focus on just one.
By setting up the script based on these inputs and parameters, you can get a real-time view of significant price levels and how often the price interacts with them, helping you make more informed trading decisions.
Support, Resistance & Liquidity Pool ZonesSupport, Resistance & Liquidity Pool Zones
This indicator automatically detects and plots support and resistance levels based on pivot points and highlights liquidity pool zones, areas where the trading volume exceeds the average over a set number of bars. It is designed to help traders identify key price levels and liquidity traps that can trigger significant market reactions.
Key Features:
Support & Resistance Levels:
The indicator identifies pivot highs and pivot lows as potential resistance and support levels, respectively.
You can customize the number of levels shown on the chart, making it easier to focus on the most recent and relevant price levels.
Liquidity Pool Zones:
The script detects liquidity pool zones, which are areas with above-average trading volume. These zones often act as regions of interest where price accumulation or distribution occurs, potentially leading to significant price moves.
Liquidity zones are shaded to help traders visually identify areas of high interest in the market.
Customizable Settings:
You can adjust the pivot period to fine-tune how the indicator calculates support and resistance.
Control the number of support/resistance levels displayed on the chart and the period used to detect liquidity pools.
Customize the colors for support, resistance, and liquidity zones to match your charting preferences.
Alerts:
The script includes built-in alerts for when the price breaks above resistance or falls below support, helping traders catch key breakout opportunities.
How It Works:
The script calculates support and resistance levels using pivot highs and lows based on the user-defined pivot period.
It monitors liquidity pool zones by comparing the current trading volume with the average volume over a customizable period. When the volume exceeds the set threshold, a liquidity pool zone is highlighted, providing insight into where the market may accumulate or distribute.
Alerts are triggered when the price breaks above the first resistance level or falls below the first support level, giving traders immediate notification of key market events.
How to Use:
Tune the Pivot Period: Adjust the pivot period to your preferred time horizon (default: 10 bars).
Set Liquidity Pool Parameters: Customize the number of bars considered for liquidity pool detection and the volume multiplier to detect high-volume zones.
Monitor Breakouts: Use the built-in alerts to catch potential breakout or breakdown opportunities near support and resistance levels.
This script is ideal for traders looking for an easy-to-use tool to visualize support and resistance levels and liquidity pools, aiding in decision-making and trade management.
WSITEEE Imbalance/FVG (FAIR VALUE GAP)Imbalance/FVG (Fair Value Gap) refers to a price imbalance, representing a range on the chart where little liquidity was provided.
Imbalance implies a strong impulsive movement of a candle, which the price almost always returns to cover.
The best analogy would be to imagine painting a wall with a roller. If you move the roller from top to bottom, what remains on the wall? That’s right, gaps that need to be filled. How do you fill them? Exactly, by moving the roller from bottom to top. The same principle applies to imbalance.
How do you correctly mark an Imbalance?
The first thing we need to find on the chart is three candles, one of which should be impulsive. Next, using the “Fibonacci Retracement” tool, we stretch it from the wick of the first candle to the wick of the last candle.
Imbalance can be used both for determining context and as an entry model. On a higher timeframe, it acts as a point of interest (POI), within which you can look for factors to build a position.
This Pine Script is designed for Smart Money traders who work with Fair Value Gaps (FVG). FVGs are three-candle patterns where the third candle does not fully overlap the first, leaving a gap on the second candle. The script helps to automatically detect these gaps and highlight them on the chart with different colors based on their status and type.
It allows for the visualization of imbalances on the chart, highlighting key zones that can serve as important levels for decision-making. With flexible color and label settings, the script can be tailored to individual needs, enhancing data visualization on the chart.
Fibonacci Swing Trading BotStrategy Overview for "Fibonacci Swing Trading Bot"
Strategy Name: Fibonacci Swing Trading Bot
Version: Pine Script v5
Purpose: This strategy is designed for swing traders who want to leverage Fibonacci retracement levels and candlestick patterns to enter and exit trades on higher time frames.
Key Components:
1. Multiple Timeframe Analysis:
The strategy uses a customizable timeframe for analysis. You can choose between 4hour, daily, weekly, or monthly time frames to fit your preferred trading horizon. The high and low-price data is retrieved from the selected timeframe to identify swing points.
2. Fibonacci Retracement Levels:
The script calculates two key Fibonacci retracement levels:
0.618: A common level where price often retraces before resuming its trend.
0.786: A deeper retracement level, often used to identify stronger support/resistance areas.
These levels are dynamically plotted on the chart based on the highest high and lowest low over the last 50 bars of the selected timeframe.
3. Candlestick Based Entry Signals:
The strategy uses candlestick patterns as the only indicator for trade entries:
Bullish Candle: A green candle (close > open) that forms between the 0.618 retracement level and the swing high.
Bearish Candle: A red candle (close < open) that forms between the 0.786 retracement level and the swing low.
When these candlestick patterns align with the Fibonacci levels, the script triggers buy or sell signals.
4. Risk Management:
Stop Loss: The stop loss is set at 1% below the entry price for long trades and 1% above the entry price for short trades. This tight risk management ensures controlled losses.
Take Profit: The strategy uses a 2:1 risk-to-reward ratio. The take profit is automatically calculated based on this ratio relative to the stop loss.
5. Buy/Sell Logic:
Buy Signal: Triggered when a bullish candle forms above the 0.618 retracement level and below the swing high. The bot then places a long position.
Sell Signal: Triggered when a bearish candle forms below the 0.786 retracement level and above the swing low. The bot then places a short position.
The stop loss and take profit levels are automatically managed once the trade is placed.
Strengths of This Strategy:
Swing Trading Focus: The strategy is ideal for swing traders, targeting longer-term price moves that can take days or weeks to play out.
Simple Yet Effective Indicators: By only relying on Fibonacci retracement levels and basic candlestick patterns, the strategy avoids complexity while capitalizing on well-known support and resistance zones.
Automated Risk Management: The built-in stop loss and take profit mechanism ensures trades are protected, adhering to a strict 2:1 risk/reward ratio.
Multiple Timeframe Analysis: The script adapts to various market conditions by allowing users to switch between different timeframes (4hour, daily, weekly, monthly), giving traders flexibility.
Strategy Use Cases:
Retracement Traders: Traders who focus on entering the market at key retracement levels (0.618 and 0.786) will find this strategy especially useful.
Trend Reversal Traders: The strategy’s reliance on candlestick formations at Fibonacci levels helps traders spot potential reversals in price trends.
Risk Conscious Traders: With its 1% risk per trade and 2:1 risk/reward ratio, the strategy is ideal for traders who prioritize risk management in their trades.
Elder AutoEnvelope with Overbought/Oversold Levels with LabelsThe **"Elder AutoEnvelope with Overbought/Oversold Levels with Labels"** is a technical analysis tool designed to help identify overbought and oversold levels in the market, as well as potential reversal points. It uses moving averages and price volatility to detect possible price extremes.
### Indicator Description:
- **Center EMA (26)**: Acts as the main trend line.
- **Envelope Channels**: These are constructed around the central EMA using the current price volatility. The main channel lines are determined by multiplying the standard deviation of the price by the chosen multiplier.
- **Additional Overbought/Oversold Levels**: Displayed on the chart with different colors and thicknesses to highlight small, moderate, strong, and very strong levels.
- **Labels**: Show specific levels when the price reaches areas of overbought or oversold conditions.
### How to Apply in Practice:
1. **Identifying Extremes**: The indicator shows areas where the price is considered overbought or oversold relative to the current trend. When the price touches or exceeds these levels, it can indicate a potential reversal or correction.
2. **Entry/Exit Signals**:
- **Entry on Oversold**: If the price reaches the lower Envelope lines (especially at strong or very strong oversold levels), it may be a good buying signal.
- **Exit on Overbought**: If the price touches the upper lines (especially at strong or very strong overbought levels), it signals a potential selling opportunity.
3. **Combining with Other Indicators**: It’s recommended to use this indicator alongside oscillators like RSI or MACD for signal confirmation.
4. **Trend Analysis**: The central EMA (26) helps identify the trend direction. If the price is above it, the trend is considered bullish; if below, bearish.
This indicator is particularly useful in volatile markets and helps detect price movements near highs or lows.
(Early Test) Weekly Seasonality with Dynamic Kelly Criterion# Enhancing Trading Strategies with the Weekly Seasonality Dynamic Kelly Criterion Indicator
Amidst this pursuit to chase price, a common pitfall emerges: an overemphasis on price movements without adequate attention to risk management, probabilistic analysis, and strategic position sizing. To address these challenges, I developed the **Weekly Seasonality with Dynamic Kelly Criterion Indicator**. It is designed to refocus traders on essential aspects of trading, such as risk management and probabilistic returns, thereby catering to both short-term swing traders and long-term investors aiming for tax-efficient positions.
## The Motivation Behind the Indicator
### Overemphasis on Price: A Common Trading Pitfall
Many traders concentrate heavily on price charts and technical indicators, often neglecting the underlying principles of risk management and probabilistic analysis. This overemphasis on price can lead to:
- **Overtrading:** Making frequent trades based solely on price movements without considering the associated risks.
- **Poor Risk Management:** Failing to set appropriate stop-loss levels or position sizes, increasing the potential for significant losses.
- **Emotional Trading:** Letting emotions drive trading decisions rather than objective analysis, which can result in impulsive and irrational trades.
### The Need for Balanced Focus
To achieve sustained trading success, it is crucial to balance price analysis with robust risk management and probabilistic strategies. Key areas of focus include:
1. **Risk Management:** Implementing strategies to protect capital, such as setting stop-loss orders and determining appropriate position sizes based on risk tolerance.
2. **Probabilistic Analysis:** Assessing the likelihood of various market outcomes to make informed trading decisions.
3. **Swing Trading Percent Returns:** Capitalizing on short- to medium-term price movements by buying assets below their average return and selling them above.
## Introducing the Weekly Seasonality with Dynamic Kelly Criterion Indicator
The **Weekly Seasonality with Dynamic Kelly Criterion Indicator** is designed to integrate these essential elements into a comprehensive tool that aids traders in making informed, risk-aware decisions. Below, we explore the key components and functionalities of this indicator.
### Key Components of the Indicator
1. **Average Return (%)**
- **Definition:** The mean percentage return for each week across multiple years.
- **Purpose:** Serves as a benchmark to identify weeks with above or below-average performance, guiding buy and sell decisions.
2. **Positive Percentage (%)**
- **Definition:** The proportion of weeks that yielded positive returns.
- **Purpose:** Indicates the consistency of positive returns, helping traders gauge the reliability of certain weeks for trading.
3. **Volatility (%)**
- **Definition:** The standard deviation of weekly returns.
- **Purpose:** Measures the variability of returns, providing insights into the risk associated with trading during specific weeks.
4. **Kelly Ratio**
- **Definition:** A mathematical formula used to determine the optimal size of a series of bets to maximize the logarithmic growth of capital.
- **Purpose:** Balances potential returns against risks, guiding traders on the appropriate position size to take.
5. **Adjusted Kelly Fraction**
- **Definition:** The Kelly Ratio adjusted based on user-defined risk tolerance and external factors like Federal Reserve (Fed) stance.
- **Purpose:** Personalizes the Kelly Criterion to align with individual risk preferences and market conditions, enhancing risk management.
6. **Position Size ($)**
- **Definition:** The calculated amount to invest based on the Adjusted Kelly Fraction.
- **Purpose:** Ensures that position sizes are aligned with risk management strategies, preventing overexposure to any single trade.
7. **Max Drawdown (%)**
- **Definition:** The maximum observed loss from a peak to a trough of a portfolio, before a new peak is attained.
- **Purpose:** Assesses the worst-case scenario for losses, crucial for understanding potential capital erosion.
### Functionality and Benefits
- **Weekly Data Aggregation:** Aggregates weekly returns across multiple years to provide a robust statistical foundation for decision-making.
- **Quarterly Filtering:** Allows users to filter weeks based on quarters, enabling seasonality analysis and tailored strategies aligned with specific timeframes.
- **Dynamic Risk Adjustment:** Incorporates the Dynamic Kelly Criterion to adjust position sizes in real-time based on changing risk profiles and market conditions.
- **User-Friendly Visualization:** Presents all essential metrics in an organized Summary Table, facilitating quick and informed decision-making.
## The Origin of the Kelly Criterion and Addressing Its Limitations
### Understanding the Kelly Criterion
The Kelly Criterion, developed by John L. Kelly Jr. in 1956, is a formula used to determine the optimal size of a series of bets to maximize the long-term growth of capital. The formula considers both the probability of winning and the payout ratio, balancing potential returns against the risk of loss.
**Kelly Formula:**
\
Where:
- \( b \) = the net odds received on the wager ("b to 1")
- \( p \) = probability of winning
- \( q \) = probability of losing ( \( q = 1 - p \) )
### The Risk of Ruin
While the Kelly Criterion is effective in optimizing growth, it carries inherent risks:
- **Overbetting:** If the input probabilities or payout ratios are misestimated, the Kelly Criterion can suggest overly aggressive position sizes, leading to significant losses.
- **Assumption of Constant Probabilities:** The criterion assumes that probabilities remain constant, which is rarely the case in dynamic markets.
- **Ignoring External Factors:** Traditional Kelly implementations do not account for external factors such as Federal Reserve rates, margin requirements, or market volatility, which can impact risk and returns.
### Addressing Traditional Limitations
Recognizing these limitations, the **Weekly Seasonality with Dynamic Kelly Criterion Indicator** introduces enhancements to the traditional Kelly approach:
- **Incorporation of Fed Stance:** Adjusts the Kelly Fraction based on the current stance of the Federal Reserve (neutral, dovish, or hawkish), reflecting broader economic conditions that influence market behavior.
- **Margin and Leverage Considerations:** Accounts for margin rates and leverage, ensuring that position sizes remain within manageable risk parameters.
- **Dynamic Adjustments:** Continuously updates position sizes based on real-time risk assessments and probabilistic analyses, mitigating the risk of ruin associated with static Kelly implementations.
## How the Indicator Aids Traders
### For Short-Term Swing Traders
Short-term swing traders thrive on capitalizing over weekly price movements. The indicator aids them by:
- **Identifying Favorable Weeks:** Highlights weeks with above-average returns and favorable volatility, guiding entry and exit points.
- **Optimal Position Sizing:** Utilizes the Adjusted Kelly Fraction to determine the optimal amount to invest, balancing potential returns with risk exposure.
- **Probabilistic Insights:** Provides metrics like Positive Percentage (%) and Kelly Ratio to assess the likelihood of favorable outcomes, enhancing decision-making.
### For Long-Term Tax-Free Investors
This is effectively a drop-in replacement for DCA which uses fixed position size that doesn't change based on market conditions, as a result, it's like catching multiple falling knifes by the blade and smiling with blood on your hand... I don't know about you, but I'd rather juggle by the hilt and look like an actual professional...
Long-term investors, especially those seeking tax-free positions (e.g., through retirement accounts), benefit from:
- **Consistent Risk Management:** Ensures that position sizes are aligned with long-term capital preservation strategies.
- **Seasonality Analysis:** Allows for strategic positioning based on historical performance trends across different weeks and quarters.
- **Dynamic Adjustments:** Adapts to changing market conditions, maintaining optimal risk profiles over extended investment horizons.
### Developers
Please double check the logic and functionality because I think there are a few issue and I need to crowd source solutions and be responsible about the code I publish. If you have corrections, please DM me or leave a respectful comment.
I want to publish this by the end of the year and include other things like highlighting triple witching weeks, adding columns for volume % stats, VaR and CVaR, alpha, beta (to see the seasonal alpha and beta based off a benchmark ticker and risk free rate ticker and other little goodies.
Trend Following Moron TFM 10% System
Trend Following Moron TFM 10% System
The TFM 10% Market Timing System
The Trend Following Moron TFM 10% System is a powerful trading tool designed using Pine Script™, following the principles outlined by Dave S. Landry. This script helps traders identify optimal entry and exit points based on moving averages and market trends.
What the Script Does:
Visual representation of trend strength.
As long as it is trending in green band, trend is very strong and price is contained within 5% of the high.
As price drops to yellow band, strength is weakening and caution is advised. Price is between 5% to 10% away from52 week high.
As price drops in red band, it is to be avoided as trend is rolling over. Price is more than 10% way from 52 week high.
Moving Averages Calculation:
Users can choose between Simple Moving Average (SMA) and Exponential Moving Average (EMA) for daily, weekly, and monthly periods. The script calculates the moving averages to provide trend direction.
Trend Color Coding:
Moving averages are displayed in different colors based on market conditions: green indicates an uptrend, red for a downtrend, and gray for neutral conditions.
Highs Calculation:
The script calculates the 52-week and 12-month closing highs, which are crucial for identifying potential breakout points.
Level Definition:
Traders can set levels based on either Average True Range (ATR) or percentage changes from these highs, allowing for flexible risk management strategies.
Buy and Sell Conditions:
The script defines specific buy conditions: when the price is within 10% of the highest close and trading above the moving averages, and sell conditions: when the price falls below these thresholds.
Visual Indicators:
Buy and sell signals are visually represented on the chart with arrows, making it easy for traders to see potential trading opportunities at a glance.
Performance Labels:
The script includes performance labels that track the number of bars above or below the moving averages and the percentage change from the moving average, providing users with key metrics to evaluate their trades.
Interactive Table:
A table summarizing the buy and sell rules is displayed on the chart, ensuring that traders have quick access to the system’s trading logic.
Benefits of Using the TFM 10% System:
Streamlined Decision Making:
The script simplifies the trading process by clearly outlining buy and sell signals, making it accessible even for novice traders.
Customizable Parameters:
Users can tailor the script to their preferences by adjusting moving average types and lengths, ATR levels, and percentage thresholds. Bands are interchange able for ATR and Percent below 52 week high for volatility looks. But buy and sell are fixed in 10% threshold.
Risk Management:
By utilizing ATR and percentage levels, traders can effectively manage their risk, making the trading process more systematic.
Comprehensive Market Analysis:
The combination of multiple time frames (daily, weekly, monthly) allows for a well-rounded analysis of market trends, enhancing trading accuracy.
Leonid's Bitcoin Sharpe RatioThe Sharpe ratio is an old formula used to value the risk-adjusted return of an asset. It was developed by Nobel Laureate William F. Sharpe. In this case, I have applied it to Bitcoin with an adjustable look-back date.
The Sharpe Ratio shows you the average return earned after subtracting out the risk-free rate per unit of volatility (I've defaulted this to 0.02 ).
Volatility is a measure of the price fluctuations of an asset or portfolio. Subtracting the risk-free rate from the mean return allows you to understand what the extra returns are for taking the risk.
If the indicator is flashing red, Bitcoin is temporarily overbought (expensive).
If the indicator is flashing green, Bitcoin is temporarily oversold (cheap).
The goal of this indicator is to signal out local tops & bottoms. It can be adjusted as far as the lookback time but I have found 25-26 days to be ideal.
bar_index inspectorThis is a tool for developers who are working with index based plots and find themselves adding the bar_index to their indicators on a regular basis during development and debugging.
What it does:
shows the bar_index in the status line and data window.
plots optional labels (bar index + time) into the chart every 10 bars
Custom 4-Hour Candle Colors with Opening Price LinesDescription:
This indicator enhances the visual clarity of 4-hour candles by allowing users to assign custom colors to each 4-hour time block on their chart. It also provides the option to plot horizontal lines at the opening price of each 4-hour candle, with the lines extending for a customizable duration (up to 36 hours), making it easy to track the opening price levels over time.
Features:
Custom 4-Hour Candle Colors: Define unique colors for each 4-hour candle block on the chart. You can configure the colors for six different 4-hour periods, making it easier to visually differentiate between different parts of the trading day.
Opening Price Lines: The indicator plots horizontal lines at the opening price of each 4-hour candle, with the option to extend the lines for up to 36 hours into the future. The lines can also have different colors, which you can configure separately for each time block.
Flexible Time Configuration: Set custom open times for each 4-hour candle block, allowing you to adjust the indicator to match specific market sessions or time zones.
Fully Customizable: Choose both the candle colors and the opening price line colors independently for each 4-hour period. This allows for a highly personalized chart setup.
Use Cases:
Session Tracking: Easily track different trading sessions by assigning specific colors to different time periods.
Key Price Levels: Keep an eye on important opening price levels throughout the day by extending opening price lines into the future.
Visual Organization: For traders who prefer color-coded charts for improved readability, this indicator helps to organize trading days visually by color-blocking each time segment.
Important Notes:
Due to TradingView’s limitations, the opening price lines can only extend up to 500 bars into the future. The indicator automatically limits the duration of the lines to this maximum.
The script is designed to be flexible and user-friendly, allowing for easy adjustments to suit different trading styles and market conditions.
M & W Checklistindicator to Validate & Grade M & W Patterns.
Indicator Inputs
Table Color Palette
• Position Valid : Positions the Valid Trade table on the chart.
• Position Grade : Positions the Grade table on the chart, hover over the Column 1 Row 1 for a description of the bands.
• Size: Text size for all tables.
• Text Color : Sets text color.
• Border Color : Sets the table border color for all tables.
• Background Color : Sets table backgroud color for all tables.
Valid Trade Table
Checkboxes to indicate if the trade is valid. Fail is displayed if unchecked, Pass if checked.
Grade Table
• S/R Level 1: distance between neckline and 1st resistance area in % of the total distance between neckline and take profit. This is not for road blocks but pivot points etc before the initial run up/down in price. I have this set to 30% , this means that if there is a pivot point between the neckline and 30% of the TP level I weight it negatively.
• S/R Level 2: distance between neckline and 1st resistance area in % of the total distance between neckline and take profit. This is not for road blocks but pivot points etc before the initial run up/down in price. I have this set to 50% , this means that if there is a pivot point between the neckline and 50% of the TP level 2 weight it negatively but less so than level 1.
• S/R Level 3: distance between neckline and 1st resistance area in % of the total distance between neckline and take profit. This is not for road blocks but pivot points etc before the initial run up/down in price. I have this set to 70% , this means that if there is a pivot point between the neckline and 70% of the TP level 3 weight it negatively but less so than level 1 & level 2.
• Checkboxes are self explanatory, they are binary options, all are weighted negatively if checked and are weighted positively if unchecked. Divergence values for weighting are neutral if unckecked & weighted positively if checked.
• The select options are neutral weighting if set to neutral , if set to For its weighted positive and set to Against weighted negatively.
Technical Specification of the Scoring and Band System
Overview
The scoring system is designed to evaluate a set of technical trade conditions, assigning weights to various criteria that influence the quality of the trade. The system calculates a total score based on both positive and negative conditions. Based on the final score, the system assigns a grade or band (A, B, or C) for positive scores, and a "Negative" label for negative scores.
Scoring System
The system calculates the score by evaluating a set of 12 conditions (gradeCondition1 to gradeCondition12). These conditions are manually input by the user via checkboxes or dropdowns in a technical indicator (written in Pine Script for TradingView). The score weights vary according to the relative importance of each condition.
Condition Breakdown and Weighting:
1. Divergences (GradeCondition1 & GradeCondition2):
◦ 1H Divergence: +5 points if condition is true.
◦ 4H Divergence: +10 points if condition is true (stronger weight than 1H).
2. Support/Resistance at Neckline (GradeCondition3):
◦ Negative if present: -15 points if true (carries significant negative weight).
3. RB near Entry (GradeCondition4):
◦ Very Negative: -20 points if true (this is a critical negative condition).
4. RB can Manage (GradeCondition5):
◦ Slightly Negative: -5 points if true.
5. Institutional Value Zones (GradeCondition6 to GradeCondition8):
◦ For the trade: +5 points.
◦ Against the trade: -5 points.
◦ Neutral: 0 points.
6. S/R between Neckline & Targets (GradeCondition9 to GradeCondition11):
◦ Level 1: -10 points if true, +7 points if false.
◦ Level 2: -7 points if true, +7 points if false.
◦ Level 3: -5 points if true, +7 points if false.
◦ Use fib tool or Gann Box to measure any S/R levels setup according to your preferences.
7. News Timing (GradeCondition12):
◦ News within 3 hours: -20 points if true (strong negative factor).
◦ No upcoming news: +10 points if false.
Scoring Calculation Formula:
totalScore = score1 + score2 + score3 + score4 + score5 + score6 + score7 + score8 + score9 + score10 + score11 + score12
Where:
• score1 to score12 represent the points derived from the conditions described above.
Coloring and Visual Feedback:
• Positive Scores: Displayed in green.
• Negative Scores: Displayed in red.
Band System
The Band System classifies the total score into different grades, depending on the final value of totalScore. This classification provides an intuitive ranking for trades, helping users quickly assess trade quality.
Band Classification:
• Band A: If the totalScore is 41 or more.
◦ Represents a highly favorable trade setup.
• Band B: If the totalScore is between 21 and 40.
◦ Represents a favorable trade setup with good potential.
• Band C: If the totalScore is between 1 and 20.
◦ Represents a trade setup that is acceptable but may have risks.
• Negative: If the totalScore is 0 or less.
◦ Represents a poor trade setup with significant risks or unfavorable conditions.
Band Calculation Logic (in Pine Script):
var string grade = ""
if (totalScore >= 41)
grade := "Band A"
else if (totalScore >= 21)
grade := "Band B"
else if (totalScore >= 1)
grade := "Band C"
else
grade := "Negative"
Technical Key Points:
• Highly Negative Conditions:
◦ The system penalizes certain conditions more heavily, especially those that suggest significant risks (e.g., News in less than 3 hours, RB near Entry).
• Positive Trade Conditions:
◦ Divergences, Institutional Value Zones in favor of the trade, and lack of significant nearby resistance all contribute positively to the score.
• Flexible System:
◦ The system can be adapted or fine-tuned by adjusting the weights of individual conditions according to trading preferences.
Use Case Example:
• If a trade has 1H and 4H Divergence, RB near Entry (negative), and no upcoming news:
◦ 1H Divergence: +5 points.
◦ 4H Divergence: +10 points.
◦ RB near Entry: -20 points.
◦ No news: +10 points.
◦ Total Score: 5 + 10 - 20 + 10 = 5 → Band C.
This modular and flexible scoring system allows traders to systematically evaluate trades and quickly gauge the trade's potential based on technical indicators
Summary:
Maximum Score: 61
Minimum Score: -97
These are the bounds of the score range based on the current logic of the script.
Crossover CounterExplanation:
Crossover Detection: We detect the crossover of the 20-period and 50-period moving averages using ta.crossover().
Tracking Price Movement: After the crossover, we start tracking the price to check if it moves up or down by 2%. If an up movement occurs before a down movement, we increment the positive counter. If a down movement occurs first, we increment the negative counter.
Reset Condition: Once either a 2% up or down move is detected, we stop tracking until the next crossover.
Table Display: A table shows the counts of positive and negative events.
Bitcoin Cycle Master [InvestorUnknown]The "Bitcoin Cycle Master" indicator is designed for in-depth, long-term analysis of Bitcoin's price cycles, using several key metrics to track market behavior and forecast potential price tops and bottoms. The indicator integrates multiple moving averages and on-chain metrics, offering a comprehensive view of Bitcoin’s historical and projected performance. Each of its components plays a crucial role in identifying critical cycle points:
Top Cap: This is a multiple of the Average Cap, which is calculated as the cumulative sum of Bitcoin’s price (price has a longer history than Market Cap) divided by its age in days. Top Cap serves as an upper boundary for speculative price peaks, multiplied by a factor of 35.
Time_dif() =>
date = ta.valuewhen(bar_index == 0, time, 0)
sec_r = math.floor(date / 1000)
min_r = math.floor(sec_r / 60)
h_r = math.floor(min_r / 60)
d_r = math.floor(h_r / 24)
// Launch of BTC
start = timestamp(2009, 1, 3, 00, 00)
sec_rb = math.floor(start / 1000)
min_rb = math.floor(sec_rb / 60)
h_rb = math.floor(min_rb / 60)
d_rb = math.floor(h_rb / 24)
difference = d_r - d_rb
AverageCap() =>
ta.cum(btc_price) / (Time_dif() + btc_age)
TopCap() =>
// To calculate Top Cap, it is first necessary to calculate Average Cap, which is the cumulative sum of Market Cap divided by the age of the market in days.
// This creates a constant time-based moving average of market cap.
// Once Average cap is calculated, those values are multiplied by 35. The result is Top Cap.
// For AverageCap the BTC price was used instead of the MC because it has more history
// (the result should have minimal if any deviation since MC would have to be divided by Supply)
AverageCap() * 35
Delta Top: Defined as the difference between the Realized Cap and the Average Cap, this metric is further multiplied by a factor of 7. Delta Top provides a historically reliable signal for Bitcoin market cycle tops.
DeltaTop() =>
// Delta Cap = Realized Cap - Average Cap
// Average Cap is explained in the Top Cap section above.
// Once Delta Cap is calculated, its values over time are then multiplied by 7. The result is Delta Top.
(RealizedPrice() - AverageCap()) * 7
Terminal Price: Derived from Coin Days Destroyed, Terminal Price normalizes Bitcoin’s historical price behavior by its finite supply (21 million bitcoins), offering an adjusted price forecast as all bitcoins approach being mined. The original formula for Terminal Price didn’t produce expected results, hence the calculation was adjusted slightly.
CVDD() =>
// CVDD stands for Cumulative Value Coin Days Destroyed.
// Coin Days Destroyed is a term used for bitcoin to identify a value of sorts to UTXO’s (unspent transaction outputs). They can be thought of as coins moving between wallets.
(MCR - TV) / 21000000
TerminalPrice() =>
// Theory:
// Before Terminal price is calculated, it is first necessary to calculate Transferred Price.
// Transferred price takes the sum of > Coin Days Destroyed and divides it by the existing supply of bitcoin and the time it has been in circulation.
// The value of Transferred Price is then multiplied by 21. Remember that there can only ever be 21 million bitcoin mined.
// This creates a 'terminal' value as the supply is all mined, a kind of reverse supply adjustment.
// Instead of heavily weighting later behavior, it normalizes historical behavior to today. By normalizing by 21, a terminal value is created
// Unfortunately the theoretical calculation didn't produce results it should, in pinescript.
// Therefore the calculation was slightly adjusted/improvised
TransferredPrice = CVDD() / (Supply * math.log(btc_age))
tp = TransferredPrice * 210000000 * 3
Realized Price: Calculated as the Market Cap Realized divided by the current supply of Bitcoin, this metric shows the average value of Bitcoin based on the price at which coins last moved, giving a market consensus price for long-term holders.
CVDD (Cumulative Value Coin Days Destroyed): This on-chain metric analyzes Bitcoin’s UTXOs (unspent transaction outputs) and the velocity of coins moving between wallets. It highlights key market dynamics during prolonged accumulation or distribution phases.
Balanced Price: The Balanced Price is the difference between the Realized Price and the Terminal Price, adjusted by Bitcoin's supply constraints. This metric provides a useful signal for identifying oversold market conditions during bear markets.
BalancedPrice() =>
// It is calculated by subtracting Transferred Price from Realized Price
RealizedPrice() - (TerminalPrice() / (21 * 3))
Each component can be toggled individually, allowing users to focus on specific aspects of Bitcoin’s price cycle and derive meaningful insights from its long-term behavior. The combination of these models provides a well-rounded view of both speculative peaks and long-term value trends.
Important consideration:
Top Cap did historically provide reliable signals for cycle peaks, however it may not be a relevant indication of peaks in the future.
Commitment of Trader %R StrategyThis Pine Script strategy utilizes the Commitment of Traders (COT) data to inform trading decisions based on the Williams %R indicator. The script operates in TradingView and includes various functionalities that allow users to customize their trading parameters.
Here’s a breakdown of its key components:
COT Data Import:
The script imports the COT library from TradingView to access historical COT data related to different trader groups (commercial hedgers, large traders, and small traders).
User Inputs:
COT data selection mode (e.g., Auto, Root, Base currency).
Whether to include futures, options, or both.
The trader group to analyze.
The lookback period for calculating the Williams %R.
Upper and lower thresholds for triggering trades.
An option to enable or disable a Simple Moving Average (SMA) filter.
Williams %R Calculation: The script calculates the Williams %R value, which is a momentum indicator that measures overbought or oversold levels based on the highest and lowest prices over a specified period.
SMA Filter: An optional SMA filter allows users to limit trades to conditions where the price is above or below the SMA, depending on the configuration.
Trade Logic: The strategy enters long positions when the Williams %R value exceeds the upper threshold and exits when the value falls below it. Conversely, it enters short positions when the Williams %R value is below the lower threshold and exits when the value rises above it.
Visual Elements: The script visually indicates the Williams %R values and thresholds on the chart, with the option to plot the SMA if enabled.
Commitment of Traders (COT) Data
The COT report is a weekly publication by the Commodity Futures Trading Commission (CFTC) that provides a breakdown of open interest positions held by different types of traders in the U.S. futures markets. It is widely used by traders and analysts to gauge market sentiment and potential price movements.
Data Collection: The COT data is collected from futures commission merchants and is published every Friday, reflecting positions as of the previous Tuesday. The report categorizes traders into three main groups:
Commercial Traders: These are typically hedgers (like producers and processors) who use futures to mitigate risk.
Non-Commercial Traders: Often referred to as speculators, these traders do not have a commercial interest in the underlying commodity but seek to profit from price changes.
Non-reportable Positions: Small traders who do not meet the reporting threshold set by the CFTC.
Interpretation:
Market Sentiment: By analyzing the positions of different trader groups, market participants can gauge sentiment. For instance, if commercial traders are heavily short, it may suggest they expect prices to decline.
Extreme Positions: Some traders look for extreme positions among non-commercial traders as potential reversal signals. For example, if speculators are overwhelmingly long, it might indicate an overbought condition.
Statistical Insights: COT data is often used in conjunction with technical analysis to inform trading decisions. Studies have shown that analyzing COT data can provide valuable insights into future price movements (Lund, 2018; Hurst et al., 2017).
Scientific References
Lund, J. (2018). Understanding the COT Report: An Analysis of Speculative Trading Strategies.
Journal of Derivatives and Hedge Funds, 24(1), 41-52. DOI:10.1057/s41260-018-00107-3
Hurst, B., O'Neill, R., & Roulston, M. (2017). The Impact of COT Reports on Futures Market Prices: An Empirical Analysis. Journal of Futures Markets, 37(8), 763-785.
DOI:10.1002/fut.21849
Commodity Futures Trading Commission (CFTC). (2024). Commitment of Traders. Retrieved from CFTC Official Website.
Fibonacci Levels with StatsPrimary Usage:
Drawing Fibonacci Retracements
Based on the past highs and lows, Fibonacci retracement levels (23.6%, 38.2%, 50%, 61.8%, 78.6%) are calculated and displayed on the chart. The Fibonacci levels are different for positive and negative lines, respectively.
Statistical Counting Function
Records the number of times each Fibonacci level is exceeded and tracks how often price reaches that level. This data can be useful for future price forecasting.
Cueing Symbols by Pattern Matching
Symbols are added to the queue when each Fibonacci level is exceeded. Depending on whether the price is positive or negative, different symbols (1, 2, 3, etc.) are assigned, which are used to predict the next move.
Change background color
Based on the number of times the price exceeds the Fibonacci level, the background color will change to green or red. The intensity of the color changes according to the number of consecutive times the price has exceeded the Fibonacci level.
Cue Size Limitations
Past symbols are added to the queue, but a size limit is set and old symbols are deleted when the queue exceeds a certain size.
Prediction Logic
Pattern matching is used to predict the next symbol based on patterns of past symbols.
Momentum-Based Buy/Sell SignalsBuy Signal:
Triggered when ROC > threshold and the MACD line crosses above the Signal line.
Sell Signal:
Triggered when ROC < threshold and the MACD line crosses below the Signal line.
Visual Elements:
Green labels with "Buy" are displayed below the bars for buy signals.
Red labels with "Sell" are displayed above the bars for sell signals.
The background turns green during a buy signal and red during a sell signal for better visual clarity.