TrendGuard Scalper: SSL + Hama Candle with Consolidation ZonesThis TradingView script brings a powerful scalping strategy that combines the SSL Channel and Hama Candles indicators with a special twist—consolidation detection. Designed for traders looking for consistency in various markets like crypto, forex, and stocks, this strategy highlights clear trend signals, risk management, and helps filter out risky trades during consolidation periods.
Why Use This Strategy?
Clear Trend Detection:
With the SSL Channel, you’ll know exactly when the market is in an uptrend (green) or downtrend (red), giving you straightforward entry points.
Short-Term Trend Precision with Hama Candles:
By calculating unique EMAs for open, high, low, and close, the Hama Candles show the strength and direction of short-term trends. Combined with the Hama Line, it gives you a solid confirmation on whether the trend is strong or about to reverse, allowing for precise entries and exits.
Avoiding Choppy Markets:
Thanks to ATR-based consolidation detection, this strategy identifies low-volatility periods where the market is “choppy” and less predictable. During these times, a yellow background appears on the chart, warning you to hold off on trades, reducing the likelihood of entering losing trades.
Built-In Risk Management:
With adjustable Take Profit and Stop Loss levels based on price movements, you can set and forget your trades, with a safety net if the market turns against you. The strategy automatically closes positions if the price returns to the Hama Candle, keeping your risk low.
How It Works:
Long Position: When both the SSL and Hama indicators show a green trend, and the price is above the Hama Candles, the strategy opens a long position. Take Profit triggers at your chosen risk-to-reward ratio, while Stop Loss protects you just below the Hama Line.
Short Position: When both indicators align in red and the price is below the Hama Candles, the strategy opens a short. Similar to longs, Stop Loss is set just above the Hama Line, and Take Profit is at your defined level.
Start Trading Confidently
Test this strategy with different settings and discover how it can perform across various assets. Whether you're trading Bitcoin, forex pairs, or stocks, this system has the flexibility and robustness to help you spot profitable trends and avoid risky zones. Try it today on a 30-minute timeframe to see how it aligns with your trading goals, and let the consolidation detection guide you away from false signals.
Happy trading, and may the trends be with you! 📈
Indicators and strategies
Expected Volatility, Range, and Estimated VolatilityOverview
The Expected Volatility, Expected Range, and Estimated Volatility Indicator helps traders quantify and visualize the expected price movement of a financial instrument based on historical price changes. Unlike traditional historical volatility measures that are annualized, this indicator calculates expected volatility using a proprietary transform model directly from historical price data over a specified period. This provides an immediate, timeframe-specific estimate of expected volatility without annualization, making it more directly applicable to the current trading timeframe.
This indicator should be used with the Mean and Standard Deviation Lines to enhance analysis by combining price distribution and volatility insights.
Inputs
Volatility Period (Bars): Determines the number of bars used to calculate the expected volatility. For accurate visualization, it is recommended to set this period to be the same as the one used in the Mean and Standard Deviation Lines indicator. Adjusting this period can make the indicator more responsive to recent price changes or smooth out short-term fluctuations.
Plot Mode: Choose between "Percent" or "Base Currency" to display the indicator's outputs either as a percentage or in the asset's base currency value.
Outputs
Expected Volatility (Orange Line): Displays the expected volatility calculated using the transform model based on historical price changes over the specified period and serves as a reference for typical market movements and aiding in the identification of high-risk periods or potential breakout opportunities.
Expected Range (Red Line): Represents the expected price movement range based on the expected volatility.
Estimated Volatility (Yellow Line): Provides an alternative volatility measure based on the intraday range (high-low) relative to the previous close, offering additional insights into price fluctuations within each bar.
How to Use
Risk Management
You can use either the Expected Volatility or the Expected Range to set stop-loss and take-profit levels based on your preference. Using the Expected Volatility values will generally result in tighter stop-loss levels, potentially exiting trades earlier, while using the Expected Range may allow for more room to accommodate price fluctuations.
Historical Performance Analysis
Monitor when the Estimated Volatility (yellow line) crosses above the Expected Volatility or Expected Range lines (orange and red lines). Such crossings indicate periods where actual market volatility exceeded expected levels, providing insights into the historical effectiveness of your stop-loss or take-profit strategies.
Combined Analysis with Mean and Standard Deviation Lines
Use this indicator alongside the Mean and Standard Deviation Lines to gain a comprehensive view of both price distribution and volatility. Ensure that the Volatility Period is set to the same value in both indicators for accurate visualization and comparison. This combined approach enhances your ability to identify significant price movements and adjust your trading strategy accordingly.
Trend Analysis
Observe changes in the Expected Volatility values to identify periods of increasing or decreasing market volatility, which may signal potential trend developments or reversals.
Identifying Typical and Extreme Conditions
The Expected Volatility serves as a benchmark for typical market movements, aiding in the identification of high-risk periods or potential breakout opportunities when price action moves beyond this range.
Preference-Based Strategy
Choose between using the Expected Volatility or Expected Range based on your risk tolerance and trading strategy. The Expected Volatility provides a more conservative approach, while the Expected Range allows for greater flexibility in accommodating market fluctuations.
Additional Notes
For accurate visualization, set the Volatility Period to the same value used in the Mean and Standard Deviation Lines indicator. This alignment ensures consistency in your analysis and enhances the reliability of the insights gained from both indicators.
Be mindful that higher volatility periods can present both opportunities and increased risk; appropriate risk management practices are essential.
Important: The Expected Volatility calculated by this indicator is not annualized , unlike traditional historical volatility measures. This makes it directly applicable to the timeframe of your analysis, providing a more immediate estimate of expected price movements.
IQ Zones [TradingIQ]Hey Traders!
Introducing "IQ Zones".
"IQ Zones" is an indicator that combines support and resistance identification with volume, the "value area" of a candlestick to be exact. IQ Zones identifies turning points in the market; however, the candlestick high or low that formed the key turning point is not necessarily distinguished as the support/resistance area. Instead, the script looks into the bar at lower timeframes and calculates the value area of the candlestick that formed the support or resistance level. Therefore, any lines protruding from a candlestick reflect the value area of that candlestick. These levels (value area high and value area low) are marked on the candlestick as a support/resistance level. If the level formed on high volume it's marked as an "IQ Zone".
Additionally, IQ Zones presents a heat map to show volume intensity at nearby price areas. The heatmap is a product of the Volume Profile (IQ Profile) located on the right of the chart.
The IQ Profile is a segmented volume profile. Recent price is split into fifths (customizable), and individual volume profiles are calculated for all segmented price areas. Price is split into more than one segment to avoid a situation where volume in a ranging price zone far surpasses all other recent price areas - creating an "unusable" volume profile that doesn't offer helpful insights. If desired, you can set the segmenting option to "1" to calculate one unified volume profile for the entire price range.
The image above shows IQ Zones in action!
Core Features of IQ Zones
Value Area Support and Resistance Levels
Segmented volume profile for the recent trading period
Volume intensity heatmap
Support and resistance levels in high volume intensity may be more significant as price stoppers
The image above explains the labels marked along the y-axis of the IQ Profile.
The "more green" a price area/label is, the higher the volume intensity at the marked support/resistance area.
The image above further explains line lines protruding from the IQ Profile.
For this example, the value area of the candlestick (where most trading action occurred) is quite far from the high price of the candlestick that formed a resistance level! Using the value area of a candlestick that marks a key turning point to draw support/resistance offers insight into where the majority of trading action took place when the support/resistance level was forming!
Additionally, you can hover your mouse over the IQ Zone labels (triangles pointing up or down) to see the prices of the value area for the support/resistance level, including the total buying volume and total selling volume at the price area!
The image above further explains the IQ Profile!
You can segment the recent price area anywhere from 1 - 15 times.
The image above further explains IQ Zones and the IQ Profile!
That will be all for this indicator - a fun project to share with the community.
Thank you!
Monthly EMA Touches CounterKey Features of This Script:
Touch Threshold: The script checks if the price is within a specified percentage of each EMA.
Monthly Touch Counters: Separate counters (touchCountEMA12, touchCountEMA26, touchCountEMA50) are used to count touches for each EMA.
Reset Logic: All counters reset at the start of a new month using if ta.change(time("M")).
Increment Logic: Each counter increments whenever the corresponding EMA is touched during a bar.
Label Management: Labels are created to display each count above the bars at the end of each month.
Alert Conditions: Alerts are set up for when the price touches any of the EMAs.
Usage:
Copy and paste this script into TradingView's Pine Script editor.
Add it to your chart to see how many times the price has touched each of the EMAs (12, 26, and 50) on a monthly basis.
Adjust the Touch Threshold (%) input as needed for sensitivity.
This implementation will allow you to effectively track and visualize how often price touches each of these EMAs on a monthly basis. If you have further modifications or additional features you'd like to explore, feel free to ask
Daily Volatility Limit Channel
Hello, this is the simplest yet most powerful tool I have discovered regarding volatility. Using the ATR17 value based on a 4-hour timeframe, this tool displays the most significant volatility thresholds for the day, clearly showing when strong trends occur as these boundaries are breached. Once a boundary is crossed, the price of Bitcoin (as well as other actively traded asset classes like stocks and futures) tends to continue moving in the direction of the breakout. If the price reaches a boundary but fails to break through, this point often becomes the lowest point of pullback or correction, effectively serving as a pivot point and the optimal entry for buying.
The indicator features color and arrow options, enhancing your trading experience. The arrows appear below the candles when the trend changes to an upward impulse and above the candles when it shifts to a downward impulse. This visual aid allows traders to quickly identify trend reversals and make informed decisions.
In summary, this tool effectively highlights volatility limits and trend reversals, making it a valuable asset for any trader looking to navigate the market efficiently.
This indicator is recommended for use on 2-hour or 4-hour candlestick charts. These timeframes allow for clearer visualization of volatility and help effectively identify strong trends and volatility boundaries.
안녕하세요. 이것은 변동성에 관해 제가 발견한 것 중 가장 심플하고도 강력한 툴입니다. 4시간 기준의 ATR17값을 사용한 이 툴은 당일의 가장 강력한 변동성 한계점을 보여주며, 이 변동성 경계가 돌파될 때 강한 추세가 일어나는 것을 명확히 보여줍니다. 한 번 경계가 돌파되면 비트코인 가격(그리고 주식, 선물 등 다른 대부분의 모든 가격을 가지고 활발하게 거래되는 자산군)은 해당 돌파 쪽의 트렌드로 계속 움직이는 경향이 있습니다. 만약 가격이 경계에 도달한 채로 이 경계를 돌파하지 못할 때는 이 자리가 눌림과 조정의 최저점, 즉 피봇 포인트가 되어 매수의 최적 지점이 되는 것을 보실 수 있습니다.
지표에는 컬러 옵션과 화살표 옵션이 있어 거래 경험을 향상시킵니다. 트렌드가 상승 임펄스로 변경될 때 화살표가 캔들 아래에 나타나고, 하락 임펄스로 변경될 때는 캔들 위에 나타납니다. 이 시각적 도구는 트렌드 반전을 빠르게 식별할 수 있도록 도와주어, 거래자들이 정보에 기반한 결정을 내리는 데 유용합니다.
요약하자면, 이 툴은 변동성 한계와 트렌드 반전을 효과적으로 강조하여, 시장을 효율적으로 탐색하려는 모든 거래자에게 가치 있는 자산이 될 것입니다.
이 지표는 2시간 또는 4시간 캔들 차트에서 사용하는 것이 권장됩니다. 이러한 시간대는 지표의 변동성을 보다 명확하게 시각화하며, 강한 추세와 변동성 한계점을 효과적으로 식별하는 데 도움을 줍니다.
Trend Strength Momentum Indicator (TSMI)Introducing the Trend Strength Momentum Indicator (TSMI)
With over two decades of experience, I've found that no single indicator can consistently predict market movements. The key lies in combining multiple indicators to capture different market dimensions—trend, momentum, and volume. With this in mind, I present the Trend Strength Momentum Indicator (TSMI), a comprehensive tool designed to spot emerging uptrends and downtrends in cryptocurrency and other asset markets.
1. Overview of TSMI
The TSMI amalgamates three critical market aspects:
Trend Direction and Strength: Utilizing Moving Averages (MA) and the Average Directional Index (ADX).
Momentum: Incorporating the Moving Average Convergence Divergence (MACD) and the Relative Strength Index (RSI).
Volume Confirmation: Employing the On-Balance Volume (OBV) indicator.
By combining these elements, TSMI aims to provide a robust signal that not only indicates the direction of the trend but also confirms its strength and sustainability through momentum and volume analysis.
2. Components and Calculations
A. Trend Component
Exponential Moving Averages (EMA):
50-day EMA: Captures the short to medium-term trend.
200-day EMA: Reflects the long-term trend.
Average Directional Index (ADX):
Measures the strength of the trend regardless of its direction.
A value above 25 indicates a strong trend, while below 20 suggests a weak or non-trending market.
B. Momentum Component
Moving Average Convergence Divergence (MACD):
Calculated by subtracting the 26-day EMA from the 12-day EMA.
The MACD line crossing above the signal line (9-day EMA of MACD) indicates bullish momentum; crossing below suggests bearish momentum.
Relative Strength Index (RSI):
Oscillates between 0 and 100.
Readings above 70 indicate overbought conditions; below 30 suggest oversold conditions.
C. Volume Component
On-Balance Volume (OBV):
Cumulatively adds volume on up days and subtracts volume on down days.
A rising OBV alongside rising prices confirms an uptrend; divergence may signal a reversal.
3. TSMI Calculation Steps
Step 1: Trend Analysis
EMA Crossover:
Identify if the 50-day EMA crosses above the 200-day EMA (Golden Cross), indicating a potential uptrend.
Conversely, if the 50-day EMA crosses below the 200-day EMA (Death Cross), it may signal a downtrend.
ADX Confirmation:
Confirm the strength of the trend. An ADX value above 25 supports the EMA crossover signal.
Step 2: Momentum Assessment
MACD Evaluation:
Look for MACD crossing above its signal line for bullish momentum or below for bearish momentum.
RSI Check:
Ensure RSI is not in overbought (>70) or oversold (<30) territory to avoid potential reversals against the trend.
Step 3: Volume Verification
OBV Direction:
Confirm that OBV is moving in the same direction as the price trend.
Rising OBV with rising prices strengthens the bullish signal; falling OBV with falling prices strengthens the bearish signal.
Step 4: Composite Signal Generation
Bullish Signal:
50-day EMA crosses above 200-day EMA (Golden Cross).
ADX above 25, indicating a strong trend.
MACD crosses above its signal line.
RSI is between 30 and 70, avoiding overbought conditions.
OBV is rising.
Bearish Signal:
50-day EMA crosses below 200-day EMA (Death Cross).
ADX above 25.
MACD crosses below its signal line.
RSI is between 30 and 70, avoiding oversold conditions.
OBV is falling.
4. How to Use the TSMI
A. Entry Points
Buying into an Uptrend:
Wait for the bullish signal criteria to align.
Enter the position after the 50-day EMA crosses above the 200-day EMA, supported by positive momentum (MACD and RSI) and volume (OBV).
Selling or Shorting into a Downtrend:
Look for the bearish signal criteria.
Initiate the position after the 50-day EMA crosses below the 200-day EMA, with confirming momentum and volume indicators.
B. Exit Strategies
Protecting Profits:
Monitor RSI for overbought or oversold conditions, which may indicate potential reversals.
Watch for MACD divergences or crossovers against your position.
Use trailing stops based on the ATR (Average True Range) to allow profits to run while protecting against sharp reversals.
C. Risk Management
Position Sizing:
Use the ADX value to adjust position sizes. A stronger trend (higher ADX) may justify a larger position, whereas a weaker trend suggests caution.
Avoiding False Signals:
Be cautious during sideways markets where EMAs may whipsaw.
Confirm signals with multiple indicators before acting.
5. Examples
Example 1: Spotting an Emerging Uptrend in Bitcoin
Date: Let's assume on March 1st.
Observations:
EMA Crossover: The 50-day EMA crosses above the 200-day EMA.
ADX: Reading is 28, indicating a strong trend.
MACD: Crosses above the signal line and moves into positive territory.
RSI: Reading is 55, comfortably away from overbought levels.
OBV: Shows a rising trend, confirming increasing buying pressure.
Action:
Enter a long position in Bitcoin.
Set a stop-loss below recent swing lows.
Outcome:
Over the next few weeks, Bitcoin's price continues to rise, validating the TSMI signal.
Example 2: Identifying a Downtrend in Ethereum
Date: Let's assume on July 15th.
Observations:
EMA Crossover: The 50-day EMA crosses below the 200-day EMA.
ADX: Reading is 30, confirming a strong trend.
MACD: Crosses below the signal line into negative territory.
RSI: Reading is 45, not yet oversold.
OBV: Declining, indicating selling pressure.
Action:
Initiate a short position or exit long positions in Ethereum.
Place a stop-loss above recent resistance levels.
Outcome:
Ethereum's price declines over the following weeks, confirming the downtrend.
6. When to Use the TSMI
Trending Markets: TSMI is most effective in markets exhibiting clear trends, whether bullish or bearish.
Avoiding Sideways Markets: In range-bound markets, EMAs and momentum indicators may provide false signals. ADX readings below 20 suggest it's best to stay on the sidelines.
Volatile Assets: Particularly useful in cryptocurrency markets, which are known for their volatility and extended trends.
7. Limitations and Considerations
Lagging Indicators: Moving averages and ADX are lagging by nature. Rapid reversals may not be immediately captured.
False Signals: No indicator is foolproof. Always confirm signals with multiple components of TSMI.
Market Conditions: External factors like news events can significantly impact prices. Consider combining TSMI with fundamental analysis.
8. Enhancing TSMI
Customization: Adjust EMA periods (e.g., 20-day and 100-day) based on the asset's volatility and your trading timeframe.
Additional Indicators: Incorporate Bollinger Bands to gauge volatility or Fibonacci retracement levels to identify potential support and resistance.
Conclusion
The Trend Strength Momentum Indicator (TSMI) offers a holistic approach to spotting emerging trends by combining trend direction, momentum, and volume. By synthesizing the strengths of various traditional indicators while mitigating their individual limitations, TSMI provides traders with a powerful tool to navigate the complex landscape of cryptocurrency and other asset markets.
Key Benefits of TSMI:
Comprehensive Analysis: Integrates multiple market dimensions for well-rounded insights.
Early Trend Identification: Aims to spot trends early for optimal entry points.
Risk Management: Helps in making informed decisions, thereby reducing exposure to false signals.
By applying TSMI diligently and complementing it with sound risk management practices, traders can enhance their ability to capitalize on market trends and improve their overall trading performance.
APF Indicator with Enhanced Machine LearningKey Components:
Physics-Inspired Features:
Fractal Geometry (High/Low Signal): Utilizes pivot points to identify fractal patterns in price movements, which can signal potential market reversals.
Quantum Mechanics (Probabilistic Monte Carlo Signal): Employs Monte Carlo simulations to capture the probabilistic nature of market behavior, reflecting the randomness and uncertainty inherent in financial markets.
Thermodynamics (Efficiency Ratio Signal): Measures the efficiency of price movements over a period, comparing directional change to total volatility to assess trend strength.
Chaos Theory (Normalized ATR Signal): Analyzes market volatility using the Average True Range (ATR) and normalizes price deviations to identify chaotic market conditions.
Network Theory (Correlation Signal with BTC): Examines the correlation between the asset in question and Bitcoin (BTC) to understand interconnected market dynamics and potential influences.
String Theory (Combined RSI & MACD Signal): Combines the Relative Strength Index (RSI) and Moving Average Convergence Divergence (MACD) indicators to evaluate momentum and trend direction.
Fluid Dynamics (Normalized OBV Signal): Uses On-Balance Volume (OBV) to assess the flow of volume in relation to price changes, indicating buying or selling pressure.
Advanced Machine Learning Engine:
Ensemble Learning: Implements an ensemble of five machine learning models to improve predictive performance and reduce overfitting.
Adaptive Learning Rate (Adam Optimizer): Uses the Adam optimization algorithm to adjust learning rates dynamically, enhancing convergence speed and handling of noisy data.
Training Loop: Models are trained over a specified number of epochs, updating weights based on the error between predicted and actual values.
Feature Vector: Combines the physics-inspired signals into a feature vector that serves as input for the machine learning models.
Prediction and Error Calculation: Each ensemble member generates a prediction, and errors are calculated to refine model weights through gradient descent.
Signal Post-Processing:
Signal Smoothing: Applies an Exponential Moving Average (EMA) to smooth the machine learning signal, reducing noise.
Memory Retention Factor: Incorporates a memory factor to blend the smoothed signal with the raw prediction, balancing recent data with historical trends.
Color Coding: Assigns colors to the signal based on percentile ranks, providing visual cues for signal strength (e.g., green for strong signals, red for weak signals).
Market Condition Analysis:
Volatility Assessment: Compares short-term and long-term volatility to determine if the market is experiencing high volatility.
Trend Identification: Uses moving averages to identify bullish or bearish trends.
Background Coloring: Changes the chart background color based on market conditions, offering an at-a-glance understanding of current trends and volatility levels.
Usage and Customization:
Inputs and Parameters: The indicator allows users to customize various parameters, including learning rate, lookback period, memory factor, number of simulations, error threshold, and training epochs, enabling fine-tuning according to individual trading strategies.
Dynamic Adaptation: With adaptive learning rates and ensemble methods, the indicator adjusts to evolving market conditions, aiming to maintain performance over time.
Benefits:
Comprehensive Analysis: By integrating multiple physics-inspired signals, the indicator captures different facets of market behavior, from momentum to volatility to volume flow.
Enhanced Predictive Accuracy: The advanced machine learning engine, particularly the use of ensemble learning and the Adam optimizer, strives to improve prediction accuracy and model robustness.
User-Friendly Visualization: The use of color-coded signals and background shading makes it easier for traders to interpret the data and make informed decisions quickly.
Versatility: Suitable for various timeframes and assets, especially those with significant correlation to Bitcoin, given the inclusion of the network theory component.
Conclusion:
This indicator represents a fusion of advanced technical analysis and machine learning, leveraging complex algorithms to provide traders with potentially more accurate and responsive signals. By combining traditional indicators with innovative computational techniques, it aims to offer a powerful tool for navigating the complexities of financial markets.
Z-Score RSI StrategyOverview
The Z-Score RSI Indicator is an experimental take on momentum analysis. By applying the Relative Strength Index (RSI) to a Z-score of price data, it measures how far prices deviate from their mean, scaled by standard deviation. This isn’t your traditional use of RSI, which is typically based on price data alone. Nevertheless, this unconventional approach can yield unique insights into market trends and potential reversals.
Theory and Interpretation
The RSI calculates the balance between average gains and losses over a set period, outputting values from 0 to 100. Typically, people look at the overbought or oversold levels to identify momentum extremes that might be likely to lead to a reversal. However, I’ve often found that RSI can be effective for trend-following when observing the crossover of its moving average with the midline or the crossover of the RSI with its own moving average. These crossovers can provide useful trend signals in various market conditions.
By combining RSI with a Z-score of price, this indicator estimates the relative strength of the price’s distance from its mean. Positive Z-score trends may signal a potential for higher-than-average prices in the near future (scaled by the standard deviation), while negative trends suggest the opposite. Essentially, when the Z-Score RSI indicates a trend, it reflects that the Z-score (the distance between the average and current price) is likely to continue moving in the trend’s direction. Generally, this signals a potential price movement, though it’s important to note that this could also occur if there’s a shift in the mean or standard deviation, rather than a meaningful change in price itself.
While the Z-Score RSI could be an insightful addition to a comprehensive trading system, it should be interpreted carefully. Mean shifts may validate the indicator’s predictions without necessarily indicating any notable price change, meaning it’s best used in tandem with other indicators or strategies.
Recommendations
Before putting this indicator to use, conduct thorough backtesting and avoid overfitting. The added parameters allow fine-tuning to fit various assets, but be careful not to optimize purely for the highest historical returns. Doing so may create an overly tailored strategy that performs well in backtests but fails in live markets. Keep it balanced and look for robust performance across multiple scenarios, as overfitting is likely to lead to disappointing real-world results.
Quick scan for cycles🙏🏻
The followup for
As I told before, ML based algorading is all about detecting any kind of non-randomness & exploiting it (cuz allegedly u cant trade randomness), and cycles are legit patterns that can be leveraged
But bro would u really apply Fourier / Wavelets / 'whatever else heavy' on every update of thousands of datasets, esp in real time on HFT / nearly HFT data? That's why this metric. It works much faster & eats hell of a less electicity, will do initial rough filtering of time series that might contain any kind of cyclic behaviour. And then, only on these filtered datasets u gonna put Periodograms / Autocorrelograms and see what's going there for real. Better to do it 10x times less a day on 10x less datasets, right?
I ended up with 2 methods / formulas, I called em 'type 0' and 'type 1':
- type 0: takes sum of abs deviations from drift line, scales it by max abs deviation from the same drift line;
- type 1: takes sum of abs deviations from drift line, scales it by range of non-abs deviations from the same drift line.
Finnaly I've chosen type 0 , both logically (sum of abs dev divided by max abs dev makes more sense) and experimentally. About that actually, here are both formulas put on sine waves with uniform noise:
^^ generated sine wave with uniform noise
^^ both formulas on that wave
^^ both formulas on real data
As you can see type 0 is less affected by noise and shows higher values on synthetic data, but I decided to put type 1 inside as well, in case my analysis was not complete and on real data type 1 can actually be better since it has a lil higher info gain / info content (still not sure). But I can assure u that out of all other ways I've designed & tested for quite a time I tell you, these 2 are really the only ones who got there.
Now about dem thresholds and how to use it.
Both type 0 and type 1 can be modelled with Beta distribution, and based on it and on some obvious & tho non mainstream statistical modelling techniques, I got these thresholds, so these are not optimized overfitted values, but natural ones. Each type has 3 thresholds (from lowest to highest):
- typical value (turned off by default). aka basis ;
- typical deviation from typical value, aka deviation ;
- maximum modelled deviation from typical value (idk whow to call it properly for now, this is my own R&D), aka extension .
So when the metric is above one of these thresholds (which one is up to you, you'll read about it in a sec), it means that there might be a strong enough periodic signal inside the data, and the data got to be put through proper spectral analysis tools to confirm / deny it.
If you look at the pictures above again, you'll see gray signal, that's uniform noise. Take a look at it and see where does it sit comparing to the thresholds. Now you just undertand that picking up a threshold is all about the amount of false positives you care to withstand.
If you take basis as threshold, you'll get tons of false positives (that's why it's even turned off by default), but you'll almost never miss a true positive. If you take deviation as threshold, it's gonna be kinda balanced approach. If you take extension as threshold, you gonna miss some cycles, and gonna get only the strongest ones.
More true positives -> more false positives, less false positives -> less true positives, can't go around that mane
Just to be clear again, I am not completely sure yet, but I def lean towards type 0 as metric, and deviation as threshold.
Live Long and Prosper
P.S.: That was actually the main R&D of the last month, that script I've released earlier came out as derivative.
P.S.: These 2 are the first R&Ds made completely in " art-space", St. Petersburg. Come and see me, say wassup🤘🏻
S&P 100 Option Expiration Week StrategyThe Option Expiration Week Strategy aims to capitalize on increased volatility and trading volume that often occur during the week leading up to the expiration of options on stocks in the S&P 100 index. This period, known as the option expiration week, culminates on the third Friday of each month when stock options typically expire in the U.S. During this week, investors in this strategy take a long position in S&P 100 stocks or an equivalent ETF from the Monday preceding the third Friday, holding until Friday. The strategy capitalizes on potential upward price pressures caused by increased option-related trading activity, rebalancing, and hedging practices.
The phenomenon leveraged by this strategy is well-documented in finance literature. Studies demonstrate that options expiration dates have a significant impact on stock returns, trading volume, and volatility. This effect is driven by various market dynamics, including portfolio rebalancing, delta hedging by option market makers, and the unwinding of positions by institutional investors (Stoll & Whaley, 1987; Ni, Pearson, & Poteshman, 2005). These market activities intensify near option expiration, causing price adjustments that may create short-term profitable opportunities for those aware of these patterns (Roll, Schwartz, & Subrahmanyam, 2009).
The paper by Johnson and So (2013), Returns and Option Activity over the Option-Expiration Week for S&P 100 Stocks, provides empirical evidence supporting this strategy. The study analyzes the impact of option expiration on S&P 100 stocks, showing that these stocks tend to exhibit abnormal returns and increased volume during the expiration week. The authors attribute these patterns to intensified option trading activity, where demand for hedging and arbitrage around options expiration causes temporary price adjustments.
Scientific Explanation
Research has found that option expiration weeks are marked by predictable increases in stock returns and volatility, largely due to the role of options market makers and institutional investors. Option market makers often use delta hedging to manage exposure, which requires frequent buying or selling of the underlying stock to maintain a hedged position. As expiration approaches, their activity can amplify price fluctuations. Additionally, institutional investors often roll over or unwind positions during expiration weeks, creating further demand for underlying stocks (Stoll & Whaley, 1987). This increased demand around expiration week typically leads to temporary stock price increases, offering profitable opportunities for short-term strategies.
Key Research and Bibliography
Johnson, T. C., & So, E. C. (2013). Returns and Option Activity over the Option-Expiration Week for S&P 100 Stocks. Journal of Banking and Finance, 37(11), 4226-4240.
This study specifically examines the S&P 100 stocks and demonstrates that option expiration weeks are associated with abnormal returns and trading volume due to increased activity in the options market.
Stoll, H. R., & Whaley, R. E. (1987). Program Trading and Expiration-Day Effects. Financial Analysts Journal, 43(2), 16-28.
Stoll and Whaley analyze how program trading and portfolio insurance strategies around expiration days impact stock prices, leading to temporary volatility and increased trading volume.
Ni, S. X., Pearson, N. D., & Poteshman, A. M. (2005). Stock Price Clustering on Option Expiration Dates. Journal of Financial Economics, 78(1), 49-87.
This paper investigates how option expiration dates affect stock price clustering and volume, driven by delta hedging and other option-related trading activities.
Roll, R., Schwartz, E., & Subrahmanyam, A. (2009). Options Trading Activity and Firm Valuation. Journal of Financial Markets, 12(3), 519-534.
The authors explore how options trading activity influences firm valuation, finding that higher options volume around expiration dates can lead to temporary price movements in underlying stocks.
Cao, C., & Wei, J. (2010). Option Market Liquidity and Stock Return Volatility. Journal of Financial and Quantitative Analysis, 45(2), 481-507.
This study examines the relationship between options market liquidity and stock return volatility, finding that increased liquidity needs during expiration weeks can heighten volatility, impacting stock returns.
Summary
The Option Expiration Week Strategy utilizes well-researched financial market phenomena related to option expiration. By positioning long in S&P 100 stocks or ETFs during this period, traders can potentially capture abnormal returns driven by option market dynamics. The literature suggests that options-related activities—such as delta hedging, position rollovers, and portfolio adjustments—intensify demand for underlying assets, creating short-term profit opportunities around these key dates.
Payday Anomaly StrategyThe "Payday Effect" refers to a predictable anomaly in financial markets where stock returns exhibit significant fluctuations around specific pay periods. Typically, these are associated with the beginning, middle, or end of the month when many investors receive wages and salaries. This influx of funds, often directed automatically into retirement accounts or investment portfolios (such as 401(k) plans in the United States), temporarily increases the demand for equities. This phenomenon has been linked to a cycle where stock prices rise disproportionately on and around payday periods due to increased buy-side liquidity.
Academic research on the payday effect suggests that this pattern is tied to systematic cash flows into financial markets, primarily driven by employee retirement and savings plans. The regularity of these cash infusions creates a calendar-based pattern that can be exploited in trading strategies. Studies show that returns on days around typical payroll dates tend to be above average, and this pattern remains observable across various time periods and regions.
The rationale behind the payday effect is rooted in the behavioral tendencies of investors, specifically the automatic reinvestment mechanisms used in retirement funds, which align with monthly or semi-monthly salary payments. This regular injection of funds can cause market microstructure effects where stock prices temporarily increase, only to stabilize or reverse after the funds have been invested. Consequently, the payday effect provides traders with a potentially profitable opportunity by predicting these inflows.
Scientific Bibliography on the Payday Effect
Ma, A., & Pratt, W. R. (2017). Payday Anomaly: The Market Impact of Semi-Monthly Pay Periods. Social Science Research Network (SSRN).
This study provides a comprehensive analysis of the payday effect, exploring how returns tend to peak around payroll periods due to semi-monthly cash flows. The paper discusses how systematic inflows impact returns, leading to predictable stock performance patterns on specific days of the month.
Lakonishok, J., & Smidt, S. (1988). Are Seasonal Anomalies Real? A Ninety-Year Perspective. The Review of Financial Studies, 1(4), 403-425.
This foundational study explores calendar anomalies, including the payday effect. By examining data over nearly a century, the authors establish a framework for understanding seasonal and monthly patterns in stock returns, which provides historical support for the payday effect.
Owen, S., & Rabinovitch, R. (1983). On the Predictability of Common Stock Returns: A Step Beyond the Random Walk Hypothesis. Journal of Business Finance & Accounting, 10(3), 379-396.
This paper investigates predictability in stock returns beyond random fluctuations. It considers payday effects among various calendar anomalies, arguing that certain dates yield predictable returns due to regular cash inflows.
Loughran, T., & Schultz, P. (2005). Liquidity: Urban versus Rural Firms. Journal of Financial Economics, 78(2), 341-374.
While primarily focused on liquidity, this study provides insight into how cash flows, such as those from semi-monthly paychecks, influence liquidity levels and consequently impact stock prices around predictable pay dates.
Ariel, R. A. (1990). High Stock Returns Before Holidays: Existence and Evidence on Possible Causes. The Journal of Finance, 45(5), 1611-1626.
Ariel’s work highlights stock return patterns tied to certain dates, including paydays. Although the study focuses on pre-holiday returns, it suggests broader implications of predictable investment timing, reinforcing the calendar-based effects seen with payday anomalies.
Summary
Research on the payday effect highlights a repeating pattern in stock market returns driven by scheduled payroll investments. This cyclical increase in stock demand aligns with behavioral finance insights and market microstructure theories, offering a valuable basis for trading strategies focused on the beginning, middle, and end of each month.
XAUUSD 10-Minute StrategyThis XAUUSD 10-Minute Strategy is designed for trading Gold vs. USD on a 10-minute timeframe. By combining multiple technical indicators (MACD, RSI, Bollinger Bands, and ATR), the strategy effectively captures both trend-following and reversal opportunities, with adaptive risk management for varying market volatility. This approach balances high-probability entries with robust volatility management, making it suitable for traders seeking to optimise entries during significant price movements and reversals.
Key Components and Logic:
MACD (12, 26, 9):
Generates buy signals on MACD Line crossovers above the Signal Line and sell signals on crossovers below the Signal Line, helping to capture momentum shifts.
RSI (14):
Utilizes oversold (below 35) and overbought (above 65) levels as a secondary filter to validate entries and avoid overextended price zones.
Bollinger Bands (20, 2):
Uses upper and lower Bollinger Bands to identify potential overbought and oversold conditions, aiming to enter long trades near the lower band and short trades near the upper band.
ATR-Based Stop Loss and Take Profit:
Stop Loss and Take Profit levels are dynamically set as multiples of ATR (3x for stop loss, 5x for take profit), ensuring flexibility with market volatility to optimise exit points.
Entry & Exit Conditions:
Buy Entry: T riggered when any of the following conditions are met:
MACD Line crosses above the Signal Line
RSI is oversold
Price drops below the lower Bollinger Band
Sell Entry: Triggered when any of the following conditions are met:
MACD Line crosses below the Signal Line
RSI is overbought
Price moves above the upper Bollinger Band
Exit Strategy: Trades are closed based on opposing entry signals, with adaptive spread adjustments for realistic exit points.
Backtesting Configuration & Results:
Backtesting Period: July 21, 2024, to October 30, 2024
Symbol Info: XAUUSD, 10-minute timeframe, OANDA data source
Backtesting Capital: Initial capital of $700, with each trade set to 10 contracts (equivalent to approximately 0.1 lots based on the broker’s contract size for gold).
Users should confirm their broker's contract size for gold, as this may differ. This script uses 10 contracts for backtesting purposes, aligned with 0.1 lots on brokers offering a 100-contract specification.
Key Backtesting Performance Metrics:
Net Profit: $4,733.90 USD (676.27% increase)
Total Closed Trades: 526
Win Rate: 53.99%
Profit Factor: 1.44 (1.96 for Long trades, 1.14 for Short trades)
Max Drawdown: $819.75 USD (56.33% of equity)
Sharpe Ratio: 1.726
Average Trade: $9.00 USD (0.04% of equity per trade)
This backtest reflects realistic conditions, with a spread adjustment of 38 points and no slippage or commission applied. The settings aim to simulate typical retail trading conditions. However, please adjust the initial capital, contract size, and other settings based on your account specifics for best results.
Usage:
This strategy is tuned specifically for XAUUSD on a 10-minute timeframe, ideal for both trend-following and reversal trades. The ATR-based stop loss and take profit levels adapt dynamically to market volatility, optimising entries and exits in varied conditions. To backtest this script accurately, ensure your broker’s contract specifications for gold align with the parameters used in this strategy.
BollingerBands Balance[Giang]The "BollingerBands Balance " indicator is an enhanced version of the traditional Bollinger Bands, designed to analyze price trends on higher timeframes to identify key support and resistance zones. Instead of relying on the Simple Moving Average (SMA) to calculate standard deviation and define upper/lower bands, this indicator uses a Balance Line (CB), calculated by averaging the highest and lowest prices over a specified period and smoothing it with the Hull Moving Average (HMA).
This indicator provides multi-level upper and lower bands (from "min" to "supper max") with customizable multipliers, enabling users to identify potential reversal or continuation zones with ease. Analyzing with multiple support/resistance bands not only aids in recognizing short-term trends but also provides a broad view of long-term trends. The BollingerBands Balance indicator is a valuable tool for adjusting trading strategies and identifying optimal entry and exit points based on price dispersion around the balance line.
Asian Session ShadingDescription
The "Asian Session Shading" indicator is designed to highlight the trading hours of the Asian market session on TradingView charts. This script shades the background of the chart in a pale blue color to visually distinguish the time period of the Asian trading session. By using this indicator, traders can easily identify when the Asian session is active, helping them to analyze and make informed trading decisions based on time-specific market behavior.
Features
Customizable Timing: The session start and end times can be adjusted to fit different Asian market hours.
Visual Clarity: The pale blue shading helps to visually separate the Asian session from other trading sessions.
Easy to Use: Simple implementation with clear visual cues on the chart.
Best Use Cases
Market Analysis: Traders can use this indicator to analyze market movements and trends specific to the Asian trading session.
Trading Strategies: This tool can assist in developing and implementing trading strategies that take into account the unique characteristics of the Asian market.
Time Management: Helps traders to manage their trading schedule by clearly marking the start and end of the Asian session.
How to Use
Apply to Chart: Save and apply the indicator to your chart to see the shaded Asian session.
This indicator is particularly useful for forex traders, stock traders, and anyone looking to incorporate the Asian market's influence into their trading strategy.
Accumulation Map [LuxAlgo]The Accumulation Map is a charting tool that tracks traded volume across all price levels within a specified period.
It highlights the relationship between an asset's price and traders' willingness to buy or sell, helping to identify accumulation zones.
These zones represent areas of significant trading activity and provide insights into potential support and resistance levels. The indicator displays these zones using a heatmap, offering a clear, visual representation of market sentiment and activity based on volume.
🔶 USAGE
The Accumulation Map shows the distribution of traded volume across different price levels over a specific period. The volume nodes are displayed as color gradients, each reflecting the accumulation level (trading activity) at that price range.
The heatmap visually represents accumulation areas on the chart with color gradients. This visualization helps traders easily spot areas of significant interest and potential support or resistance levels within the market.
Metric Display controls how accumulation metrics appear on the chart. Options include Level Value Ratio, Level Value Proportion, Combined View, or None.
Color Theme allows users to switch between different color themes.
🔶 SETTINGS
The script includes user-defined parameters to customize profiles. Each input in the indicator settings is provided with a tooltip explaining its usage.
🔹 Accumulation Map
Accumulation Map | Heatmap: Toggles the visibility of the Accumulation Profile | Heatmap.
Metric Display: Controls how accumulation metrics are displayed on the chart.
Color Theme: Switches between different color themes.
🔹 Style & Settings
High Accumulation Color and Threshold: Customize the color for zones with high accumulation, and set the percentage threshold for high accumulation areas (recommended 50%–99%).
Average Accumulation: Define the color for zones with average accumulation.
Low Accumulation: Customize the color for zones with low accumulation, with a threshold range of 10%–40%.
Number of Rows: Specify the number of rows the accumulation map will display.
Horizontal Offset: Controls the horizontal offset of the map relative to the most recent bar.
Profile Width (bars): Sets the profile width in bars.
Extend Calculation To The Right: Extends the calculation to the most recent bar
Anchor Points: Set the first and second anchor points for the map.
🔶 RELATED SCRIPTS
Money-Flow-Profile
Mean Reversion Entry Signal
Mean Reversion Entry Signal Indicator
The Mean Reversion Entry Signal indicator is a trading tool designed for traders looking to capitalize on market corrections. This script leverages mean reversion principles, utilizing price levels and the Relative Strength Index (RSI) to generate potential entry signals for both long and short positions.
Key Features:
1. **Dynamic Price Levels**:
- The indicator calculates critical price levels over a user-defined lookback period, including:
- High (H)**: The highest price point over the lookback period.
- Low (L)**: The lowest price point over the lookback period.
- Midpoint (M)**: The average of the high and low.
- Midpoint High (Mh)** and **Midpoint Low (Ml)**: Additional reference levels derived from M for more nuanced trading signals.
2. User-Configurable Inputs:
- Lookback Period: Traders can specify the number of hours to look back for the calculations, allowing for tailored analysis that fits various trading strategies. By default the lookback is set for 24 hours, as i consider it the most adequate for day trading.
- Aggression Level: This input lets users choose their trading strategy's intensity, affecting the sensitivity of entry signals based on the percentage difference from the midpoint.
3. Entry Signal Generation:
The script evaluates market conditions to signal potential trades:
- Long Entries: Indicated when the price is below the Ml level and the price demonstrates a significant distance from the midpoint (M), coupled with RSI being near the oversold territory.
- Short Entries: Triggered when the price exceeds the Mh level, also indicating a significant distance from M, while the RSI indicates near overbought conditions.
4. Visual Indicators:
Clear visual signals are plotted directly on the chart:
- Long Signals are represented as upward triangles in green.
- Short Signals appear as downward triangles in red.
- Important price levels (M, H, L, Mh, and Ml) are displayed to provide traders with immediate context for potential trades.
5. No Entry Zone:
The area between Mh and Ml is shaded to indicate a "No Entry Zone," helping traders identify regions where conditions may not be favorable for taking new positions.
This can also be used as potencial profit taking area.
Conclusion
1. This indicator was built mainly for day trading, using timeframes between 1 minute and 1 hour. If you want to use it in 1D time frame, for instance, you should adjust the lookback period to 120 hours or so.
2. To use this as a strategy, you should not be afraid to "add to your losers" as the trade goes against you and the signals continue to appear.
Enjoy
Equilibrium Candles + Pattern [Honestcowboy]The Equilibrium Candles is a very simple trend continuation or reversal strategy depending on your settings.
How an Equilibrium Candle is created:
We calculate the equilibrium by measuring the mid point between highest and lowest point over X amount of bars back.
This now is the opening price for each bar and will be considered a green bar if price closes above equilibrium.
Bars get shaded by checking if regular candle close is higher than open etc. So you still see what the normal candles are doing.
Why are they useful?
The equilibrium is calculated the same as Baseline in Ichimoku Cloud. Which provides a point where price is very likely to retrace to. This script visualises the distance between close and equilibrium using candles. To provide a clear visual of how price relates to this equilibrium point.
This also makes it more straightforward to develop strategies based on this simple concept and makes the trader purely focus on this relationship and not think of any Ichimoku Cloud theories.
Script uses a very simple pattern to enter trades:
It will count how many candles have been one directional (above or below equilibrium)
Based on user input after X candles (7 by default) script shows we are in a trend (bg colors)
On the first pullback (candle closes on other side of equilibrium) it will look to enter a trade.
Places a stop order at the high of the candle if bullish trend or reverse if bearish trend.
If based on user input after X opposite candles (2 by default) order is not filled will cancel it and look for a new trend.
Use Reverse Logic:
There is a use reverse logic in the settings which on default is turned on. It will turn long orders into short orders making the stop orders become limit orders. It will use the normal long SL as target for the short. And TP as stop for the short. This to provide a means to reverse equity curve in case your pair is mean reverting by nature instead of trending.
ATR Calculation:
Averaged ATR, which is using ta.percentile_nearest_rank of 60% of a normal ATR (14 period) over the last 200 bars. This in simple words finds a value slightly above the mean ATR value over that period.
Big Candle Exit Logic:
Using Averaged ATR the script will check if a candle closes X times that ATR from the equilibrium point. This is then considered an overextension and all trades are closed.
This is also based on user input.
Simple trade management logic:
Checks if the user has selected to use TP and SL, or/and big candle exit.
Places a TP and SL based on averaged ATR at a multiplier based on user Input.
Closes trade if there is a Big Candle Exit or an opposite direction signal from indicator.
Script can be fully automated to MT5
There are risk settings in % and symbol settings provided at the bottom of the indicator. The script will send alert to MT5 broker trying to mimic the execution that happens on tradingview. There are always delays when using a bridge to MT5 broker and there could be errors so be mindful of that. This script sends alerts in format so they can be read by tradingview.to which is a bridge between the platforms.
Use the all alert function calls feature when setting up alerts and make sure you provide the right webhook if you want to use this approach.
There is also a simple buy and sell alert feature if you don't want to fully automate but still get alerts. These are available in the dropdown when creating an alert.
Almost every setting in this indicator has a tooltip added to it. So if any setting is not clear hover over the (?) icon on the right of the setting.
The backtest uses a 4% exposure per trade and a 10 point slippage. I did not include a commission cause I'm not personaly aware what the commissions are on most forex brokers. I'm only aware of minimal slippage to use in a backtest. Trading conditions vary per broker you use so always pay close attention to trading costs on your own broker. Use a full automation at your own risk and discretion and do proper backtesting.
Economic Profit (YavuzAkbay)The Economic Profit Indicator is a Pine Script™ tool for assessing a company’s economic profit based on key financial metrics like Return on Invested Capital (ROIC) and Weighted Average Cost of Capital (WACC). This indicator is designed to give traders a more accurate understanding of risk-adjusted returns.
Features
Customizable inputs for Risk-Free Rate and Corporate Tax Rate assets for people who are trading in other countries.
Calculates Economic Profit based on ROIC and WACC, with values shown as both plots and in an on-screen table.
Provides detailed breakdowns of all key calculations, enabling deeper insights into financial performance.
How to Use
Open the stock to be analyzed. In the settings, enter the risk-free asset (usually a 10-year bond) of the country where the company to be analyzed is located. Then enter the corporate tax of the country (USCTR for the USA, DECTR for Germany). Then enter the average return of the index the stock is in. I prefer 10% (0.10) for the SP500, different rates can be entered for different indices. Finally, the beta of the stock is entered. In future versions I will automatically pull beta and index returns, but in order to publish the indicator a bit earlier, I have left it entirely up to the investor.
How to Interpret
We see 3 pieces of data on the indicator. The dark blue one is ROIC, the dark orange one is WACC and the light blue line represents the difference between WACC and ROIC.
In a scenario where both ROIC and WACC are negative, if ROIC is lower than WACC, the share is at a complete economic loss.
In a scenario where both ROIC and WACC are negative, if ROIC has started to rise above WACC and is moving towards positive, the share is still in an economic loss but tending towards profit.
A scenario where ROIC is positive and WACC is negative is the most natural scenario for a company. In this scenario, we know that the company is doing well by a gradually increasing ROIC and a stable WACC.
In addition, if the ROIC and WACC difference line goes above 0, the company is now economically in net profit. This is the best scenario for a company.
My own investment strategy as a developer of the code is to look for the moment when ROIC is greater than WACC when ROIC and WACC are negative. At that point the stock is the best time to invest.
Trading is risky, and most traders lose money. The indicators Yavuz Akbay offers are for informational and educational purposes only. All content should be considered hypothetical, selected after the facts to demonstrate my product, and not constructed as financial advice. Decisions to buy, sell, hold, or trade in securities, commodities, and other investments involve risk and are best made based on the advice of qualified financial professionals. Past performance does not guarantee future results.
This indicator is experimental and will always remain experimental. The indicator will be updated by Yavuz Akbay according to market conditions.
MFI Strategy with Oversold Zone Exit and AveragingThis strategy is based on the Money Flow Index (MFI) and aims to enter a long position when the MFI exits an oversold zone, with specific rules for limit orders, stop-loss, and take-profit settings. Here's a detailed breakdown:
Key Components
1. **Money Flow Index (MFI)**: The strategy uses the MFI, a volume-weighted indicator, to gauge whether the market is in an oversold condition (default threshold of MFI < 20). Once the MFI rises above the oversold threshold, it signals a potential buying opportunity.
2. **Limit Order for Long Entry**: Instead of entering immediately after the oversold condition is cleared, the strategy places a limit order at a price slightly below the current price (by a user-defined percentage). This helps achieve a better entry price.
3. **Stop-Loss and Take-Profit**:
- **Stop-Loss**: A stop-loss is set to protect against significant losses, calculated as a percentage below the entry price.
- **Take-Profit**: A take-profit target is set as a percentage above the entry price to lock in gains.
4. **Order Cancellation**: If the limit order isn’t filled within a specific number of bars (default is 5 bars), it’s automatically canceled to avoid being filled at a potentially suboptimal price as market conditions change.
Strategy Workflow
1. **Identify Oversold Zone**: The strategy checks if the MFI falls below a defined oversold level (default is 20). Once this condition is met, the flag `inOversoldZone` is set to `true`.
2. **Wait for Exit from Oversold Zone**: When the MFI rises back above the oversold level, it’s considered a signal that the market is potentially recovering, and the strategy prepares to enter a position.
3. **Place Limit Order**: Upon exiting the oversold zone, the strategy places a limit order for a long position at a price below the current price, defined by the `Long Entry Percentage` parameter.
4. **Monitor Limit Order**: A counter (`barsSinceEntryOrder`) starts counting the bars since the limit order was placed. If the order isn’t filled within the specified number of bars, it’s canceled automatically.
5. **Set Stop-Loss and Take-Profit**: Once the order is filled, a stop-loss and take-profit are set based on user-defined percentages relative to the entry price.
6. **Exit Strategy**: The trade will close automatically when either the stop-loss or take-profit level is hit.
Advantages
- **Risk Management**: With configurable stop-loss and take-profit, the strategy ensures losses are limited while capturing profits at pre-defined levels.
- **Controlled Entry**: The use of a limit order below the current price helps secure a better entry point, enhancing risk-reward.
- **Oversold Exit Trigger**: Using the exit from an oversold zone as an entry condition can help catch reversals.
Disadvantages
- **Missed Entries**: If the limit order isn’t filled due to insufficient downward movement after the oversold signal, potential opportunities may be missed.
- **Dependency on MFI Sensitivity**: As the MFI is sensitive to both price and volume, its fluctuations might not always accurately represent oversold conditions.
Overall Purpose
The strategy is suited for traders who want to capture potential reversals after oversold conditions in the market, with a focus on precise entries, risk management, and an automated exit plan.
Trendfilter ChartIntroduction:
The "Trend Filter Chart" indicator is a comprehensive analytical tool designed to identify market trends through a combination of various technical analysis methods. This indicator utilizes multiple moving averages, power bars, and swing volatility to determine market direction and potential entry points. By combining these elements, the indicator aids in making informed trading decisions and interpreting market movements with greater precision.
The Trend Filter Chart uses several moving averages, including the 18-period and 52-period SMAs, as well as the 8-period SMA for lows and the 10-period SMA for highs. These moving averages are crucial for identifying trends and assisting in the definition of entry points.
A central feature of the indicator is the identification of power bars and ultra bars. These color-coded bars help visualize strong market movements characterized by significant changes in the weighted price range (high-low spread) and percentage price changes. Power bars and ultra bars indicate notable market activities that suggest the involvement of large market participants.
The variable Average Volatility and GSV middle line combines various volatility measures to create a comprehensive moving average. It is formed from the average of the short-term highs and lows, along with the average volatility calculated from the highest and lowest volatility values over the past days.
This calculation allows for capturing and visualizing the current trend in market volatility. This method provides an average trend line used to assess market direction.
Another important feature is the 5-over/Below-Channel signals, which indicate when five consecutive bars trade above or below the moving averages. These signals suggest potential trend continuations or reversals, providing valuable insights for trading decisions.
The integrated color signals support traders in identifying entry opportunities and evaluating market strength.
This indicator also identifies 10 different price patterns, including MA, correction patterns, and Inside/Outside Bar patterns and some others. These patterns are filtered through trend filters to provide potential entry setups. The underlying patterns are based on concepts by Larry Williams.
Depending on the pattern, they work differently in each market. Entry points, stop loss, and profit targets should be backtested in each market, as every market has its own characteristics.
For more information on how to use the patterns, please send me a message.
Disclaimer
The use of this indicator and the generated signals is at your own risk. The author assumes no responsibility for trading decisions made based on these signals. Please be aware that trading financial instruments involves risks.
COT Trendfilter + SignalsCOT Trendfilter + Signals Indicator
Data Processing and Usage: The COT indicator processes Commitments of Traders (COT) data provided by the CFTC. Users can select from various participant groups, including Commercials, Large Speculators, and Small Speculators. However, it is important to note that the signal logic of the indicator is exclusively applicable to the net positions of Commercials. This is because Commercials tend to trade contrarily, meaning their trading decisions often run against the prevailing market trend.
Functionality of the Indicators
1. Cycle COT
The cCOT is an enhanced version of the classic RSI. It incorporates additional smoothing based on market vibrations, along with adaptive upper and lower bands based on cyclical memory. The cCOT uses the current dominant cycle length as input and highlights trading signals when the signal line crosses above or below the adaptive bands. Compared to the standard RSI, the cCOT responds more quickly to market movements.
For detailed information on the cCOT, please refer to Chapter 4 "Fine tuning technical indicators" in the book "Decoding the Hidden Market Rhythm, Part 1" by Lars von Thienen.
2. Adaptive Ultra-Smooth Momentum Indicator
The Adaptive Ultra-Smooth Momentum Indicator (CSI) provides an optimized momentum oscillator based on the current dominant cycle. It addresses three common issues with standard indicators: excessive false signals, signal delay, and the need for length adjustments. The CSI offers adaptive smoothing, zero delay, and accurate detection of turning points.
For further information about the CSI, please refer to Chapter 10 "Cycle Swing Indicator: Trading the swing of the dominant cycle" in the book "Decoding the Hidden Market Rhythm, Part 1" by Lars von Thienen.
Signals and Validation
The indicator generates various trading signals:
cCOT:
A buy signal is indicated by an airplane emoji (🛫), while a sell signal is marked by another airplane emoji (🛬).
COT Momentum:
A buy signal is shown by the symbol “∿” in green, while a sell signal is represented by the same symbol in red.
Standard COT Index (Willco):
A buy signal is depicted by a “B” (in green), while a sell signal is shown by an “S” (in red).
Additionally, the validity of the signals is checked. If a previous signal becomes invalid in the following week, it is marked with a gray “x,” indicating that these signals may not be reliable. Users can also switch between net positions, long, and short to analyze the most relevant data for them.
Background Color
The color in the channel can indicate the strength of the Commercials' long-term trend. A channel background color signals an active long-, short-term trend, while no color suggests that there is no clear long-term trend present.
Strange behavior
When only a sharp spike is displayed and the rest is flat, the length settings of the Cycle Length Index should be increased. This can occur when the length is too short, resulting in an unusual spike to properly generate the channel.
Disclaimer
The use of this indicator and the generated signals is at your own risk. The author assumes no responsibility for trading decisions made based on these signals. Please be aware that trading financial instruments involves risks.
Pine Execution MapPine Script Execution Map
Overview:
This is an educational script for Pine Script developers. The script includes data structure, functions/methods, and process to capture and print Pine Script execution map of functions called while pine script execution.
Map of execution is produced for last/latest candle execution.
The script also has example code to call execution map methods and generate Pine Execution map.
Use cases:
Pine script developers can get view of how the functions are called
This can also be used while debugging the code and know which functions are called vs what developer expect code to do
One can use this while using any of the open source published script and understand how public script is organized and how functions of the script are called.
Code components:
User defined type
type EMAP
string group
string sub_group
int level
array emap = array.new()
method called internally by other methods to generate level of function being executed
method id(string tag) =>
if(str.startswith(tag, "MAIN"))
exe_level.set(0, 0)
else if(str.startswith(tag, "END"))
exe_level.set(0, exe_level.get(0) - 1)
else
exe_level.set(0, exe_level.get(0) + 1)
exe_level.get(0)
Method called from main/global scope to record execution of main scope code. There should be only one call to this method at the start of global scope.
method main(string tag) =>
this = EMAP.new()
this.group := "MAIN"
this.sub_group := tag
this.level := "MAIN".id()
emap.push(this)
Method called from main/global scope to record end of execution of main scope code. There should be only one call to this method at the end of global scope.
method end_main(string tag) =>
this = EMAP.new()
this.group := "END_MAIN"
this.sub_group := tag
this.level := 0
emap.push(this)
Method called from start of each function to record execution of function code
method call(string tag) =>
this = EMAP.new()
this.group := "SUB"
this.sub_group := tag
this.level := "SUB".id()
emap.push(this)
Method called from end of each function to record end of execution of function code
method end_call(string tag) =>
this = EMAP.new()
this.group := "END_SUB"
this.sub_group := tag
this.level := "END_SUB".id()
emap.push(this)
Pine code which generates execution map and show it as a label tooltip.
if(barstate.islast)
for rec in emap
if(not str.startswith(rec.group, "END"))
lvl_tab = str.repeat("", rec.level+1, "\t")
txt = str.format("=> {0} {1}> {2}", lvl_tab, rec.level, rec.sub_group)
debug.log(txt)
debug.lastr()
Snapshot 1:
This is the output of the script and can be viewed by hovering mouse pointer over the blue color diamond shaped label
Snapshot 2:
How to read the Pine execution map
Customizable BTC Seasonality StrategyThis strategy leverages intraday seasonality effects in Bitcoin, specifically targeting hours of statistically significant returns during periods when traditional financial markets are closed. Padysak and Vojtko (2022) demonstrate that Bitcoin exhibits higher-than-average returns from 21:00 UTC to 23:00 UTC, a period in which all major global exchanges, such as the New York Stock Exchange (NYSE), Tokyo Stock Exchange, and London Stock Exchange, are closed. The absence of competing trading activity from traditional markets during these hours appears to contribute to these statistically significant returns.
The strategy proceeds as follows:
Entry Time: A long position in Bitcoin is opened at a user-specified time, which defaults to 21:00 UTC, aligning with the beginning of the identified high-return window.
Holding Period: The position is held for two hours, capturing the positive returns typically observed during this period.
Exit Time: The position is closed at a user-defined time, defaulting to 23:00 UTC, allowing the strategy to exit as the favorable period concludes.
This simple seasonality strategy aims to achieve a 33% annualized return with a notably reduced volatility of 20.93% and maximum drawdown of -22.45%. The results suggest that investing only during these high-return hours is more stable and less risky than a passive holding strategy (Padysak & Vojtko, 2022).
References
Padysak, M., & Vojtko, R. (2022). Seasonality, Trend-following, and Mean reversion in Bitcoin.