Machine Learning SupertrendThe Machine Learning Supertrend is an advanced trend-following indicator that enhances the traditional Supertrend with Gaussian Process Regression (GPR) and kernel-based learning. Unlike conventional methods that rely purely on historical ATR values, this indicator integrates machine learning techniques to dynamically estimate volatility and forecast future price movements, resulting in a more adaptive and robust trend detection system.
At the core of this indicator lies Gaussian Process Regression (GPR), which utilizes a Radial Basis Function (RBF) kernel to model price distributions and anticipate future trends. Instead of simply looking at past price action, it constructs a kernel matrix, enabling a probabilistic approach to price forecasting. This allows the indicator to not only detect current trends but also project potential trend reversals with greater accuracy.
By applying machine learning to ATR estimation, the ML Supertrend dynamically adjusts its thresholds based on predicted values rather than a fixed multiplier. This makes the trend signals more responsive to market conditions, reducing false signals and minimizing whipsaws often seen with traditional Supertrend indicators. The upper and lower bands are no longer static but evolve based on the underlying price structure, improving the reliability of trend shifts.
When the price crosses these adaptive levels, the indicator detects a trend change and plots it accordingly. Green signifies a bullish trend, while red indicates a bearish one. Alerts can also be triggered when the trend shifts, allowing traders to react quickly to potential reversals.
What makes this approach powerful is its ability to adapt to different market conditions. Traditional ATR-based methods use fixed parameters that might not always be optimal, whereas this ML-driven Supertrend continuously refines its estimations based on real-time data. The result is a more intelligent, less lagging, and highly adaptive trend-following tool.
This indicator is particularly useful for traders looking to enhance trend-following strategies with AI-driven insights. It reduces noise, improves signal reliability, and even offers a degree of trend forecasting, making it ideal for those who want a more advanced and dynamic alternative to standard Supertrend indicators.
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, and past performance is not indicative of future results. Trading involves risk, and users should conduct their own research and use proper risk management before making investment decisions.
Forecasting
MACD Indicator with Buy and Sell AlertsIntroduction
The MACD Indicator with Alerts & Manual Thresholds is a powerful and customizable MACD-based trading tool designed for traders who want more control over their buy and sell signals. This script allows users to define their own buy and sell thresholds instead of relying solely on standard MACD crossovers. The built-in alerts help traders stay informed about potential trade opportunities without constantly monitoring charts.
How It Works
This script calculates the Moving Average Convergence Divergence (MACD) using customizable fast and slow moving averages. The MACD histogram is derived from the difference between the MACD line and the signal line:
MACD Line: The difference between a fast-moving average (default 12-period EMA) and a slow-moving average (default 26-period EMA).
Signal Line: A smoothed moving average (default 9-period EMA) of the MACD line.
Histogram: The difference between the MACD line and the signal line.
Instead of using default zero-line crossovers, this script allows traders to set custom buy and sell threshold levels:
A buy signal is generated when the MACD histogram crosses above the user-defined buy threshold.
A sell signal is generated when the MACD histogram crosses below the user-defined sell threshold.
Benefits of This Indicator
Custom Thresholds: Unlike traditional MACD indicators, traders can adjust buy and sell thresholds according to their strategy.
Automated Alerts: Get notified instantly when buy or sell conditions are met.
Flexibility in Calculation: Choose between SMA or EMA for both the MACD and signal line calculations.
Clear Visualization: Histogram bars color-coded for quick analysis.
Risks and Limitations
While the MACD indicator is a widely used tool, traders should be aware of its potential risks:
Lagging Indicator: MACD is a trend-following indicator, meaning it may generate signals with some delay.
False Signals in Ranging Markets: MACD works best in trending markets but can produce misleading signals in sideways conditions.
Threshold Optimization Required: Users need to experiment with different buy/sell thresholds to align with their trading strategy and market conditions.
Improving Accuracy with Additional Indicators
For better accuracy and confirmation, combining this MACD strategy with other indicators is recommended:
1. EMA 200 as a Trend Filter
Use the 200-period EMA to determine the overall trend direction.
Consider buying only when price is above EMA 200 (uptrend) and selling only when price is below EMA 200 (downtrend).
2. RSI (Relative Strength Index) for Overbought/Oversold Conditions
RSI (14) can help filter false MACD signals.
A MACD buy signal is stronger when RSI is below 30 (oversold condition).
A MACD sell signal is more reliable when RSI is above 70 (overbought condition).
3. Support & Resistance Levels
Consider placing trades near major support or resistance zones to avoid chasing breakouts.
MACD signals are more effective when they align with these key price levels.
Conclusion
The MACD Indicator with Alerts & Manual Thresholds offers a flexible and powerful approach to trading by allowing users to define their own thresholds. However, for best results, it should be combined with additional indicators such as EMA 200, RSI, and support/resistance levels. Traders should backtest and optimize settings to suit their market conditions and trading style.
By using this indicator alongside proper risk management techniques, traders can enhance their decision-making process and improve their overall trading performance.
Happy Trading!
b1r1nc1 buy-sell signals (MA + MACD + RSI)Kodun Açıklaması
Hareketli Ortalama (MA):
Kısa ve uzun dönem hareketli ortalamalar hesaplanır.
Alım sinyali: Kısa MA, uzun MA'yı yukarı keser.
Satım sinyali: Kısa MA, uzun MA'yı aşağı keser.
MACD:
MACD çizgisi (macd_line) ve sinyal çizgisi (signal_line) hesaplanır.
Alım sinyali: MACD çizgisi, sinyal çizgisinin üzerinde olmalıdır.
Satım sinyali: MACD çizgisi, sinyal çizgisinin altında olmalıdır.
RSI:
RSI değeri hesaplanır.
Alım sinyali: RSI, aşırı satım seviyesinin (örneğin 30) altında olmalıdır.
Satım sinyali: RSI, aşırı alım seviyesinin (örneğin 70) üzerinde olmalıdır.
Kombine Sinyaller:
Alım sinyali: Kısa MA > Uzun MA ve MACD çizgisi > Sinyal çizgisi ve RSI < 70.
Satım sinyali: Kısa MA < Uzun MA ve MACD çizgisi < Sinyal çizgisi ve RSI > 30.
Grafik Üzerinde Gösterme:
Alım ve satım sinyalleri grafik üzerinde etiketlerle gösterilir.
Hareketli ortalamalar, MACD çizgisi ve RSI değeri grafik üzerinde çizilir.
Örnek Senaryolar
Alım Sinyali:
Kısa dönem MA, uzun dönem MA'yı yukarı keser.
MACD çizgisi, sinyal çizgisinin üzerindedir.
RSI değeri 70'in altındadır (aşırı alım bölgesinde değil).
Satım Sinyali:
Kısa dönem MA, uzun dönem MA'yı aşağı keser.
MACD çizgisi, sinyal çizgisinin altındadır.
RSI değeri 30'un üzerindedir (aşırı satım bölgesinde değil).
Özelleştirme İpuçları
Parametreleri Ayarlama:
Hareketli ortalama, MACD ve RSI parametrelerini kendi stratejinize göre ayarlayabilirsiniz.
Örneğin, MACD için hızlı ve yavaş EMA uzunluklarını değiştirebilirsiniz.
Filtreler Ekleme:
Sinyalleri daha da hassaslaştırmak için ek filtreler ekleyebilirsiniz. Örneğin, hacim veya volatilite göstergeleri kullanabilirsiniz.
Stratejiye Dönüştürme:
Bu kodu bir stratejiye dönüştürerek backtest yapabilirsiniz:
Hanke's Golden Growth Rate for US M2Indicator to check if Inflation will come down or raise in the US. Based on Hanke's Golden Growth Rate.
Romlops MA'sThis is an indicator that lets you have up to 5 EMA's and 5 SMA's, plus 2 extra MA's for price forecasting for BTC.
Simple MA Crossover StrategyKey Features
Simple and Clean:
The script avoids complex conditions and focuses on a straightforward moving average crossover strategy.
Customizable Inputs:
You can adjust the lengths of the moving averages and RSI settings in the inputs.
Error-Free:
The script is designed to compile and run without errors.
How to Use
Copy and paste the script into TradingView's Pine Script editor.
Save the script and add it to your chart.
Adjust the input parameters (e.g., moving average lengths, RSI levels) as needed.
The script will plot buy/sell signals on the chart based on the strategy.
Example Inputs
Ultimate Stochastics Strategy by NHBprod Use to Day Trade BTCHey All!
Here's a new script I worked on that's super simple but at the same time useful. Check out the backtest results. The backtest results include slippage and fees/commission, and is still quite profitable. Obviously the profitability magnitude depends on how much capital you begin with, and how much the user utilizes per order, but in any event it seems to be profitable according to backtests.
This is different because it allows you full functionality over the stochastics calculations which is designed for random datasets. This script allows you to:
Designate ANY period of time to analyze and study
Choose between Long trading, short trading, and Long & Short trading
It allows you to enter trades based on the stochastics calculations
It allows you to EXIT trades using the stochastics calculations or take profit, or stop loss, Or any combination of those, which is nice because then the user can see how one variable effects the overall performance.
As for the actual stochastics formula, you get control, and get to SEE the plot lines for slow K, slow D, and fast K, which is usually not considered.
You also get the chance to modify the smoothing method, which has not been done with regular stochastics indicators. You get to choose the standard simple moving average (SMA) method, but I also allow you to choose other MA's such as the HMA and WMA.
Lastly, the user gets the option of using a custom trade extender, which essentially allows a buy or sell signal to exist for X amount of candles after the initial signal. For example, you can use "max bars since signal" to 1, and this will allow the indicator to produce an extra sequential buy signal when a buy signal is generated. This can be useful because it is possible that you use a small take profit (TP) and quickly exit a profitable trade. With the max bars since signal variable, you're able to reenter on the next candle and allow for another opportunity.
Let me know if you have any questions! Please take a look at the performance report and let me know your thoughts! :)
John Bob-Trading-BotDeveloped by Ayebale John Bob with the help of his bestie, this innovative strategy combines advanced Smart Money Concepts with practical risk management tools to help traders identify and capitalize on key market moves.
Key Features:
Smart Money Concepts & Fair Value Gaps (FVG):
The strategy monitors price action for fair value gaps, which are visualized as extremely faint horizontal lines on the chart. These FVGs signal potential areas where institutional traders might have entered or exited positions.
Dynamic Entry Signals:
Buy signals are triggered when the price crosses above the 50-bar lowest low or when a bullish FVG is detected. Conversely, sell signals are generated when the price falls below the 50-bar highest high or a bearish FVG is identified. Each signal is visually marked on the chart with clear buy (green) and sell (red) labels.
Multi-Level Order Execution:
Once an entry signal occurs, the strategy places five separate orders, each with its own take-profit (TP) level. The TP levels are calculated dynamically using the Average True Range (ATR) and a set of predefined multipliers. This allows traders to scale out of positions as the market moves favorably.
Dynamic Risk Management:
A stop-loss is automatically set at a distance determined by the ATR, ensuring that risk is managed in accordance with current market volatility.
Real-Time Trade Information Table:
In the bottom-right corner of the chart, a trade information table displays essential details about the current trade:
Side: Displays "BUY NOW" (with a dark green background) for long entries or "SELL NOW" (with a dark red background) for short entries.
Entry Price & Stop-Loss: Shows the entry price (highlighted in green) and the corresponding stop-loss level (highlighted in red).
Take-Profit Levels: Lists the five TP levels, each of which turns green once the market price reaches that target.
Timer: A live timer in minutes counts from the moment the current trade trigger started, helping traders track the duration of their active trades.
Visual Progress Bar:
A histogram-style progress bar is plotted on the chart, visually representing the percentage gain (or loss) relative to the entry price.
This strategy was meticulously designed to incorporate both technical analysis and smart risk management, offering a robust trading solution that adapts to changing market conditions. Whether you're a seasoned trader or just starting out, the AyebaleJohnBob Trading Bot equips you with the tools and visual cues needed to make well-informed trading decisions. Enjoy a seamless blend of strategy and style—crafted with passion by Ayebale John Bob and his bestie!
ICT NY Open & CloseHorarios apertura y cierre ICT
Horarios para analisis dependiendo de la tendencia semanal
First 9:15-9:20 Candle Levels (Daily)This indicator captures the closing price of the first 5-minute candle (9:15 - 9:20 AM) every trading day. It then calculates 0.09% above and below this closing price and plots horizontal lines. The indicator resets daily at 9:15 AM, ensuring it always tracks the latest market open. After 9:20 AM, the calculated levels remain visible throughout the day. The upper level is displayed in green, while the lower level is in red. This tool helps traders identify key price levels early in the session, useful for setting stop-losses, take-profit zones, or identifying potential breakout points.
CM_Stochastic_MTF_3TimeframesSame as the original CM_Stochastic_MTF but with 3 timeframes, slightly improved signals.
Multi TimeFrame Stochastic Loaded With Features.
Basics:
Ability to turn On/Off Crosses Only Above or Below High/Low Lines.
User sets Values Of High/Low lines.
Ability to turn On/Off All Crosses, Both BackGround Highlights and “B”, “S” Letters.
Ability to turn On/Off BackGround Highlights if Stoch is Above Or Below High/Low Lines.
Ability to All or Any Combination of these Features.
Multi Timeframe Capabilities:
Stoch defaults to current timeframe. You can change to many other timeframes.
Ability to turn On/Off Plotting 2nd Stoch on same TimeFrame with different settings
Ability to turn On/Off Plotting 2nd Stoch on Different TimeFrame
Much More…All Inputs and Options are Adjustable in Inputs Tab.
Gold Pro StrategyHere’s the strategy description in a chat format:
---
**Gold (XAU/USD) Trend-Following Strategy**
This **trend-following strategy** is designed for trading gold (XAU/USD) by combining moving averages, MACD momentum indicators, and RSI filters to capture sustained trends while managing volatility risks. The strategy uses volatility-adjusted stops to protect gains and prevent overexposure during erratic price movements. The aim is to take advantage of trending markets by confirming momentum and ensuring entries are not made at extreme levels.
---
**Key Components**
1. **Trend Identification**
- **50 vs 200 EMA Crossover**
- **Bullish Trend:** 50 EMA crosses above 200 EMA, and the price closes above the 200 EMA
- **Bearish Trend:** 50 EMA crosses below 200 EMA, and the price closes below the 200 EMA
2. **Momentum Confirmation**
- **MACD (12,26,9)**
- **Buy Signal:** MACD line crosses above the signal line
- **Sell Signal:** MACD line crosses below the signal line
- **RSI (14 Period)**
- **Bullish Zone:** RSI between 50-70 to avoid overbought conditions
- **Bearish Zone:** RSI between 30-50 to avoid oversold conditions
3. **Entry Criteria**
- **Long Entry:** Bullish trend, MACD bullish crossover, and RSI between 50-70
- **Short Entry:** Bearish trend, MACD bearish crossover, and RSI between 30-50
4. **Exit & Risk Management**
- **ATR Trailing Stops (14 Period):**
- Initial Stop: 3x ATR from entry price
- Trailing Stop: Adjusts to lock in profits as price moves favorably
- **Position Sizing:** 100% of equity per trade (high-risk strategy)
---
**Key Logic Flow**
1. **Trend Filter:** Use the 50/200 EMA relationship to define the market's direction
2. **Momentum Confirmation:** Confirm trend momentum with MACD crossovers
3. **RSI Validation:** Ensure RSI is within non-extreme ranges before entering trades
4. **Volatility-Based Risk Management:** Use ATR stops to manage market volatility
---
**Visual Cues**
- **Blue Line:** 50 EMA
- **Red Line:** 200 EMA
- **Green Triangles:** Long entry signals
- **Red Triangles:** Short entry signals
---
**Strengths**
- **Clear Trend Focus:** Avoids counter-trend trades
- **RSI Filter:** Prevents entering overbought or oversold conditions
- **ATR Stops:** Adapts to gold’s inherent volatility
- **Simple Rules:** Easy to follow with minimal inputs
---
**Weaknesses & Risks**
- **Infrequent Signals:** 50/200 EMA crossovers are rare
- **Potential Missed Opportunities:** Strict RSI criteria may miss some valid trends
- **Aggressive Position Sizing:** 100% equity allocation can lead to large drawdowns
- **No Profit Targets:** Relies on trailing stops rather than defined exit targets
---
**Performance Profile**
| Metric | Expected Range |
|----------------------|---------------------|
| Annual Trades | 4-8 |
| Win Rate | 55-65% |
| Max Drawdown | 25-35% |
| Profit Factor | 1.8-2.5 |
---
**Optimization Recommendations**
1. **Increase Trade Frequency**
Adjust the EMAs to shorter periods:
- `emaFastLen = input.int(30, "Fast EMA")`
- `emaSlowLen = input.int(150, "Slow EMA")`
2. **Relax RSI Filters**
Adjust the RSI range to:
- `rsiBullish = rsi > 45 and rsi < 75`
- `rsiBearish = rsi < 55 and rsi > 25`
3. **Add Profit Targets**
Introduce a profit target at 1.5% above entry:
```pine
strategy.exit("Long Exit", "Long",
stop=longStopPrice,
profit=close*1.015, // 1.5% target
trail_offset=trailOffset)
```
4. **Reduce Position Sizing**
Risk a smaller percentage per trade:
- `default_qty_value=25`
---
**Best Use Case**
This strategy excels in **strong trending markets** such as gold rallies during economic or geopolitical crises. However, during sideways or choppy market conditions, the strategy might require manual intervention to avoid false signals. Additionally, integrating fundamental analysis—like monitoring USD weakness or geopolitical risks—can enhance its effectiveness.
---
This strategy offers a balanced approach for trading gold, combining trend-following principles with risk management tailored to the volatility of the market.
THE EDGE FXThis indicator is designed to enhance chart organization for traders by providing essential tools for analysis and time management. Key features include:
1. Notes and Watermarks:
- Allows traders to add customizable notes and watermarks directly on the chart for better information tracking and organization.
2. Unique Day and Week Separation:
- Dynamically separates days and weeks based on the selected UTC timezone. This feature is ideal for global traders managing different time zones and ensures accurate time segmentation on the chart.
3. Fractal Marking:
- Automatically highlights fractal points on the chart, helping traders identify potential reversal or continuation zones based on classic fractal analysis principles.
How It Works:
- The indicator overlays additional visual elements on the chart without altering the underlying data.
- Time segmentation is achieved using an algorithm that adapts to the selected UTC timezone for clear and accurate visualization.
- Fractal detection follows standard technical analysis rules to identify key price levels.
Usage Instructions:
- Add the indicator to your chart and configure the settings for your preferred timezone.
- Use the notes feature to save and display critical information directly on the chart.
- Utilize fractal markings to analyze potential turning points and market trends.
This indicator provides a streamlined way to manage your chart annotations and fractal analysis, making it an essential tool for both intraday and swing traders.
Lorentzian Volatility Filtered SignalsThis indicator uses Lorentzian classification and volume to print accurate buy and sell signals with a stop loss and take profit.
SASDv2rSensitive Altcoin Season Detector V2
This Pine Script™ code, titled "SASDv2r" (Sensitive Altcoin Season Detector version 2 revised), is designed for cryptocurrency trading analysis on the TradingView platform and tailored for those interested in tracking when altcoins might be outperforming Bitcoin, potentially indicating a market shift towards altcoins.
Feel free to use and modify. If you made it better, please let me know. Intention was to help the community with a tool for retail traders have no access to advanced, MV indicators. Solution uses classic TA only.
Use it witl TOTAL3/BTC indicator.
Please check: it gave signal just before last alt season % rose more than 250%.
Market Cap Data Fetching: The script fetches market capitalization data for Bitcoin, Ethereum, and all other altcoins (excluding Bitcoin and Ethereum) using request.security function.
Altcoin to Bitcoin Ratio: It calculates the ratio of total market cap of altcoins to Bitcoin's market cap (altToBtcRatio), which is central to identifying an "altcoin season."
Moving Averages: Several moving averages are computed for different time frames (50-day SMA, 200-day SMA, 20-day SMA, and 10-day EMA) to analyze trends in the altcoin to Bitcoin ratio.
Momentum Indicators: The script uses RSI (Relative Strength Index) and MACD (Moving Average Convergence Divergence) to gauge momentum and potential reversal points in the market.
Custom Indicators: It includes Volume Weighted Moving Average (VWMA) and a custom momentum indicator (altMomentum and altMomentumAvg) to provide additional insights into market movements.
Volatility Measurement: Bollinger Bands are calculated to assess volatility in the altcoin to Bitcoin ratio, which helps identify periods of high or low market activity.
Visual Analysis: Various plots are added to the chart for visual interpretation, including the altcoin to Bitcoin ratio, different moving averages, and Bollinger Bands.
Alt Season Detection: The script defines conditions for detecting when an "altcoin season" might be starting, based on crossovers of moving averages, RSI levels, MACD signals, and other custom criteria.
Performance Tracking: After signaling an alt season, the script evaluates the performance over the next 30 days by checking if there's been an increase in the altcoin to Bitcoin ratio, adding labels for positive or negative trends.(this one is in progress). Logic still gives false signals and aim is to identify failed signals.
Visual Signals: Labels are placed on the chart to visually indicate the beginning of a potential alt season or the performance outcome after a signal, aiding traders in making informed decisions.
RSI & RSI-MA Buy-Sell IndicatorThe RSI & RSI-MA Buy-Sell Indicator is a technical analysis tool designed to identify potential trading opportunities based on the Relative Strength Index (RSI) and its moving average (RSI-MA). The indicator provides clear buy and sell signals when specific conditions are met, helping traders make informed decisions.
How It Works
This indicator is based on two main components:
Relative Strength Index (RSI): Measures the strength and momentum of price movements.
RSI Moving Average (RSI-MA): A simple moving average of RSI values, used to smooth out volatility and confirm trends.
Trading Signals:
A buy signal occurs when the RSI crosses above 70 after previously being below 30, and the RSI-MA is above a predefined threshold.
A sell signal is generated when the RSI crosses below 30 after previously being above 70, and the RSI-MA is below the threshold.
Visual labels for "BUY" and "SELL" appear on the RSI chart rather than the price chart, making it easier to interpret the signals.
Alerts can be set to notify traders when a buy or sell condition is met.
Benefits of the Indicator
Clear Trading Signals: The indicator removes subjectivity by providing distinct buy and sell signals.
Enhanced Trend Confirmation: RSI-MA helps validate RSI movements, reducing false signals.
Customizable Inputs: Traders can adjust the RSI period, RSI-MA period, and reference level based on their strategy.
Efficient for Momentum Trading: Works well in volatile markets where RSI movements are pronounced.
Compatible with Alerts: Can send notifications when trading conditions are met, allowing traders to act swiftly.
Risks & Limitations
False Signals in Sideways Markets: RSI can generate misleading signals when the market lacks a clear trend.
Lagging Nature of Moving Averages: RSI-MA may cause a delay in signal generation compared to RSI alone.
Market Conditions Dependency: Works best in trending markets but may be unreliable during low volatility.
Not a Standalone Strategy: Should be used in conjunction with other indicators, fundamental analysis, and risk management techniques.
Overbought/Oversold Assumptions: Just because RSI reaches extreme levels doesn’t guarantee a reversal—prices can remain overbought/oversold for extended periods.
Conclusion
The RSI & RSI-MA Buy-Sell Indicator is a powerful tool for identifying momentum shifts and potential trade setups. However, like all technical indicators, it has limitations and should be used alongside other analysis techniques. Traders must implement proper risk management and avoid relying solely on RSI signals for trading decisions. With careful usage, this indicator can help enhance decision-making and improve trade timing in dynamic markets.
MABS algo box Time Algothis indicator helps with time zone where market rejects hopefully u can use it
EMA50EMA150#gangesThis strategy is a trading system that uses Exponential Moving Averages (EMA) and Simple Moving Averages (SMA) to determine entry and exit points for trades. Here's a breakdown of the key components and logic:
Key Indicators:
EMA 50 (Exponential Moving Average with a 50-period window): This is a more responsive moving average to recent price movements.
EMA 150 (Exponential Moving Average with a 150-period window): A slower-moving average that helps identify longer-term trends.
SMA 150 (Simple Moving Average with a 150-period window): This acts as a stop-loss indicator for long trades.
User Inputs:
Start Date and End Date: The strategy is applied only within this date range, ensuring that trading only occurs during the specified period.
Trade Conditions:
Buy Signal (Long Position):
A buy is triggered when the 50-period EMA crosses above the 150-period EMA (indicating the price is gaining upward momentum).
Sell Signal (Short Position):
A sell is triggered when the 50-period EMA crosses below the 150-period EMA (indicating the price is losing upward momentum and moving downward).
Stop-Loss for Long Positions:
If the price drops below the 150-period SMA, the strategy closes any long positions as a stop-loss mechanism to limit further losses.
Re-Entry After Stop-Loss:
After a stop-loss is triggered, the strategy monitors for a re-entry signal:
Re-buy: If the price crosses above the 150-period EMA from below, a new long position is triggered.
Re-sell: If the 50-period EMA crosses below the 150-period EMA, a new short position is triggered.
Trade Execution:
Buy or Sell: The strategy enters trades based on the conditions described and exits them if the stop-loss conditions are met.
Re-entry: After a stop-loss, the strategy tries to re-enter the market based on the same buy/sell conditions.
Risk Management:
Commission and Slippage: The strategy includes a 0.1% commission on each trade and allows for 3 pips of slippage to account for real market conditions.
Visuals:
The strategy plots the 50-period EMA (blue), 150-period EMA (red), and 150-period SMA (orange) on the chart, helping users visualize the key levels for decision-making.
Date Range Filter:
The strategy only executes trades during the user-defined date range, which helps limit trades to a specific period and avoid backtesting errors on irrelevant data.
Stop-Loss Logic:
The stop-loss is triggered when the price crosses below the 150-period SMA, closing the long position to protect against significant drawdowns.
Overall Strategy Goal:
The strategy aims to capture long-term trends using the EMAs for entry signals, while protecting profits through the stop-loss mechanism and offering a way to re-enter the market after a stop-loss.
XAU/USD Swing Trading Strategy//@version=5
indicator("XAU/USD Swing Trading Strategy", overlay=true)
// Inputs
ema200_length = input.int(200, title="200 EMA Length")
ema50_length = input.int(50, title="50 EMA Length")
ema100_length = input.int(100, title="100 EMA Length")
rsi_length = input.int(14, title="RSI Length")
rsi_overbought = input.int(70, title="RSI Overbought Level")
rsi_oversold = input.int(30, title="RSI Oversold Level")
fib_levels = input.string("38.2, 50, 61.8", title="Fibonacci Levels")
// EMAs
ema200 = ta.ema(close, ema200_length)
ema50 = ta.ema(close, ema50_length)
ema100 = ta.ema(close, ema100_length)
// RSI
rsi = ta.rsi(close, rsi_length)
// Fibonacci Retracement Levels
fib_382 = 0.382
fib_500 = 0.5
fib_618 = 0.618
// Plot EMAs
plot(ema200, color=color.blue, title="200 EMA", linewidth=2)
plot(ema50, color=color.orange, title="50 EMA", linewidth=1)
plot(ema100, color=color.red, title="100 EMA", linewidth=1)
// Plot RSI
hline(rsi_overbought, "Overbought", color=color.red)
hline(rsi_oversold, "Oversold", color=color.green)
// Candlestick Patterns
bullish_engulfing = ta.crossover(close , open ) and close > open and close < open
bearish_engulfing = ta.crossover(open , close ) and close < open and close > open
pin_bar_bullish = (low < low and close > (high + low) / 2)
pin_bar_bearish = (high > high and close < (high + low) / 2)
// Trend Direction
uptrend = close > ema200
downtrend = close < ema200
// Entry Signals
long_signal = uptrend and bullish_engulfing and rsi > rsi_oversold
short_signal = downtrend and bearish_engulfing and rsi < rsi_overbought
// Plot Signals
plotshape(series=long_signal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(series=short_signal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")
// Fibonacci Levels
fib_high = ta.highest(high, 50)
fib_low = ta.lowest(low, 50)
fib_range = fib_high - fib_low
plot(fib_high - fib_range * fib_382, color=color.purple, title="38.2% Fib")
plot(fib_high - fib_range * fib_500, color=color.blue, title="50% Fib")
plot(fib_high - fib_range * fib_618, color=color.orange, title="61.8% Fib")
// Alerts
alertcondition(long_signal, title="Buy Signal", message="BUY XAU/USD")
alertcondition(short_signal, title="Sell Signal", message="SELL XAU/USD")
Autocorrelation Price Forecasting Backtesting [ScrimpleAI]This script presents an innovative trading backtesting strategy designed to leverage autocorrelation models and linear regression on historical price returns . The goal is to forecast future price movements, identify recurring market cycles, and optimize trading decisions.
Main Functionality
This backtesting script is built to simulate trades by integrating historical autocorrelation with dynamic price forecasting . It incorporates risk management, stop-loss features, and an advanced backtesting date range, providing traders with maximum flexibility for evaluating strategies.
Key Features
1. Customizable Date Range for Backtesting
Allows users to define the exact date period for backtesting their strategies, ensuring they can fine-tune results for specific historical scenarios.
- Inputs: Start and End dates (day, month, year).
2. Autocorrelation Price Forecasting
- Detects cycles in market movements using the `ta.correlation` function.
- Highlights significant cycles when the autocorrelation exceeds a threshold value (default: 0.50).
- Stores projected values based on autocorrelation and linear regression of percentage returns for enhanced forecasting accuracy.
3. Forecast Threshold and Profit Assessment
- Evaluates hypothetical gains by comparing forecasted future prices to the current price.
- Customizable threshold gains to determine minimum profitability requirements for opening trades.
4. Strategy Side
- Long or Short Mode: Users can choose to test either long or short strategies to align with their trading approach.
5. Risk and Trade Management
- Order Sizing: Adjust position size as a percentage of the portfolio.
- Stop-Loss Integration: Dynamically calculates stop-loss based on user-defined percentages.
- Take Profit Target: Automatically sets take-profit levels based on forecasted gains.
6. Visual Alerts
- Provides clear visual signals of long and short entries on the chart, including labels and dynamic coloring.
- Forecasted prices are displayed directly on the chart as a continuous line, enhancing decision-making clarity.
Practical Applications
1. Cycle Detection: Utilize autocorrelation to identify repetitive market behaviors and cycles.
2. Forecasting for Backtesting: Simulate trades and assess the profitability of various strategies based on future price predictions.
3. Risk Management: Test different stop-loss and take-profit configurations.
4. Custom Period Analysis: Evaluate strategy performance in specific historical market conditions using the date range filter.
Core Logic Walkthrough
1. Autocorrelation for Cycle Detection:
- Historical prices are analyzed for recurring patterns using the `ta.correlation` function.
- If a significant cycle is detected (above the `signal_threshold`), the `linreg_values` (linear regression of returns) are stored for price projection.
2. Future Price Estimation: Forecasted price is calculated based on linear regression values and current price movements.
3. Trade Entry Logic
Long Trades
- Triggered if the hypothetical gain exceeds the threshold gain.
- Sets a take-profit level based on the projected future price.
- Includes an optional stop-loss based on user-defined percentages.
Short Trades
- Triggered if the hypothetical gain is less than the negative of the threshold gain.
- Configures take-profit and stop-loss levels for bearish trades.
4. Risk Management
- Position Sizing: Automatically calculates the order size as a percentage of the portfolio.
- Stop-Loss: Dynamically adjusts stop-loss levels to minimize risk.
5. Date Range Filtering: Ensures trades are executed only within the defined backtesting period.
Example Use Case: Backtesting with Autocorrelation
- A trader analyzes a 6-month period using 50 historical bars for autocorrelation.
- Sets a threshold gain of 10% and enables a stop-loss at 5%.
- Evaluates the effectiveness of a long-only strategy in this period to assess its profitability and risk-adjusted performance.
If you find this strategy useful or have ideas for improvements, leave a comment! What new features would you like to see in this strategy?
EMA Cross with Bollinger Bands & SMIIOThis intergrates the 3 indicators to provide a more accurate display of what happening to the market.