Move Up StopsThis script creates a stop loss level and then moves it up in 5% increments as prices increase.
Basically, it checks to see if the lowest low of the last 7 days is above a certain level. If yes, it sets the stop at that level. It then checks for the next highest level and keeps going until the price is not above a level. Those variables are then set to the level below them.
Trailing stops are notorious for skewing backtest results. This script avoids that problem. Also, some exchanges do not offer trailing stops, so this script gives you a signal to let you know its time to manually move your stops up.
I will be using this for swing trades involving both crypto and stocks.
Pesquisar nos scripts por "Trailing stop"
PpSignal Chandelier StopThere are few indicators for MT4 which draw trailing stop line. I prefer to use Chandelier Stops. I believe that with good money management this is one of the best tools to follow a trend.
About ATR trailing stop loss (Chandelier Stops)
When you catch trend you can profit from most of the move. The good thing about ATR is that you have a stop loss level in place. When there is a close on the other side of ATR, it is a signal to close. No second guessing.
Best time frame for ATR trailing stop loss
I strongly recommend time frames such as 30m or larger. On lower time frames like 5m there is too much algo trading. I trade with ATR on 1h or 4h charts.
Parameters for trailing stop
Depends on pair or instrument. In most cases standard parameters will be fine. If I change anything then it is usually a Kv parameter. Standard is 3.5 and I tend to make it bigger like 3.7 or 4.0. In most cases it is around 3.7.
ATR trailing stop loss (Chandelier Exit) – Metatrader download
January 1, 2018 by  simon  in forex indicators
In this section you can download ATR trailing stop loss (Chandelier Exit) for MetaTrader:
– download ATR trailing stop loss (Chandelier Exit) for MetaTrader 4 –
There are few indicators for MT4 which draw trailing stop line. I prefer to use Chandelier Stops. I believe that with good money management this is one of the best tools to follow a trend.
About ATR trailing stop loss (Chandelier Stops)
When you catch trend you can profit from most of the move. The good thing about ATR is that you have a stop loss level in place. When there is a close on the other side of ATR, it is a signal to close. No second guessing.
Over 300 pips in profit thanks to ATR stop
Over 300 pips in profit thanks to ATR stop
Best time frame for ATR trailing stop loss
I strongly recommend time frames such as 30m or larger. On lower time frames like 5m there is too much algo trading. I trade with ATR on 1h or 4h charts.
Parameters for trailing stop
Depends on pair or instrument. In most cases standard parameters will be fine. If I change anything then it is usually a Kv parameter. Standard is 3.5 and I tend to make it bigger like 3.7 or 4.0. In most cases it is around 3.7.
Remember, it depends from pair and current situation in the market. You should experiment with few settings and check it on historical price action if they are ok.
Best pairs to trade with ATR trailing stop loss
Trailing stop loss works best in trending markets. That is why you should check pair if it tends to move strong or to move in range. It is not the secret that yen pairs line to move strongly. If you are looking for solid trends, you can’t go wrong with GBPJPY or EURJPY.
Strategy Chameleon [theUltimator5]Have you ever looked at an indicator and wondered to yourself "Is this indicator actually profitable?"  Well now you can test it out for yourself with the Strategy Chameleon!
Strategy Chameleon is a versatile, signal-agnostic trading strategy designed to adapt to any external indicator or trading system. Like a chameleon changes colors to match its environment, this strategy adapts to match any buy/sell signals you provide, making it the ultimate backtesting and automation tool for traders who want to test multiple strategies without rewriting code.
 🎯 Key Features 
 1) Connects ANY external indicator's buy/sell signals 
 
 Works with RSI, MACD, moving averages, custom indicators, or any Pine Script output
 Simply connect your indicator's signal output to the strategy inputs
 
 2) Multiple Stop Loss Types: 
 
 Percentage-based stops
 ATR (Average True Range) dynamic stops
 Fixed point stops
 
 3) Advanced Trailing Stop System: 
 
 Percentage trailing
 ATR-based trailing
 Fixed point trailing
 
 4) Flexible Take Profit Options: 
 
 Risk:Reward ratio targeting
 Percentage-based profits
 ATR-based profits
 Fixed point profits
 
 5) Trading Direction Control 
 
 Long Only - Bull market strategies
 Short Only - Bear market strategies
 Both - Full market strategies
 
 6) Time-Based Filtering 
 
 Optional trading session restrictions
 Customize active trading hours
 Perfect for day trading strategies
 
 📈 How It Works 
 
 Signal Detection: The strategy monitors your connected buy/sell signals
 Entry Logic: Executes trades when signals trigger during valid time periods
 Risk Management: Automatically applies your chosen stop loss and take profit levels
 Trailing System: Dynamically adjusts stops to lock in profits
 Performance Tracking: Real-time statistics table showing win rate and performance
 
 ⚙️ Setup Instructions 
0) Add indicator you want to test, then add the Strategy to your chart
Connect Your Signals:
 imgur.com 
Go to strategy settings → Signal Sources
1) Set "Buy Signal Source" to your indicator's buy output
2) Set "Sell Signal Source" to your indicator's sell output
3) Choose table position - This simply changes the table location on the screen
4) Set trading direction preference - Buy only? Sell only? Both directions?
 imgur.com 
5) Set your preferred stop loss type and level
You can set the stop loss to be either percentage based or ATR and fully configurable.
6) Enable trailing stops if desired
 imgur.com 
7) Configure take profit settings
8) Toggle time filter to only consider specific time windows or trading sessions.
 🚀 Use Cases 
 
 Test various indicators to determine feasibility and/or profitability.
 Compare different signal sources quickly
 Validate trading ideas with consistent risk management
 
 Portfolio Management 
 
 Apply uniform risk management across different strategies
 Standardize stop loss and take profit rules
 Monitor performance consistently
 
 Automation Ready 
 
 Built-in alert conditions for automated trading
 Compatible with trading bots and webhooks
 Easy integration with external systems
 
 ⚠️ Important Notes 
This strategy requires external signals to function
Default settings use 10% of equity per trade
Pyramiding is disabled (one position at a time)
Strategy calculates on bar close, not every tick
🔗 Integration Examples
Works perfectly with:
RSI strategies (connect RSI > 70 for sells, RSI < 30 for buys)
Moving average crossovers
MACD signal line crosses
Bollinger Band strategies
Custom oscillators and indicators
Multi-timeframe strategies
📋 Default Settings
Position Size: 10% of equity
Stop Loss: 2% percentage-based
Trailing Stop: 1.5% percentage-based (enabled)
Take Profit: Disabled (optional)
Trade Direction: Both long and short
Time Filter: Disabled
HMA Crossover + ATR + Curvature (Long & Short)📏 Hull Moving Averages (Trend Filters)
- fastHMA = ta.hma(close, fastLength)
- slowHMA = ta.hma(close, slowLength)
These two HMAs act as dynamic trend indicators:
- A bullish crossover of fast over slow HMA signals a potential long setup.
- A bearish crossunder triggers short interest.
⚡️ Curvature (Acceleration Filter)
- curv = ta.change(ta.change(fastHMA))
This calculates the second-order change (akin to the second derivative) of the fast HMA — effectively the acceleration of the trend. It serves as a filter:
- For long entries: curv > curvThresh (positive acceleration)
- For short entries: curv < -curvThresh (negative acceleration)
It helps eliminate weak or stagnating moves by requiring momentum behind the crossover.
📈 Volatility-Based Risk Management (ATR)
- atr = ta.atr(atrLength)
- stopLoss = atr * atrMult
- trailStop = atr * trailMult
These define your:
- Initial stop loss: scaled to recent volatility using ATR and atrMult.
- Trailing stop: also ATR-scaled, to lock in gains dynamically as price moves favorably.
💰 Position Sizing via Risk Percent
- capital = strategy.equity
- riskCapital = capital * (riskPercent / 100)
- qty = riskCapital / stopLoss
This dynamically calculates the position size (qty) such that if the stop loss is hit, the loss does not exceed the predefined percentage of account equity. It’s a volatility-adjusted position sizing method, keeping your risk consistent regardless of market conditions.
📌 Execution Logic
- Long Entry: on bullish HMA crossover with rising curvature.
- Short Entry: on bearish crossover with falling curvature.
- Exits: use ATR-based trailing stops.
- Position is closed when trend conditions reverse (e.g., bearish crossover exits the long).
This framework gives you:
- Trend-following logic (via HMAs)
- Momentum confirmation (via curvature)
- Volatility-aware execution and exits (via ATR)
- Risk-controlled dynamic sizing
Want to get surgical and test what happens if we use curvature on the difference between HMAs instead? That might give some cool insights into trend strength transitions.
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
  - Set first partial exit point and percentage of position to close
  - Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
   - Choose your preferred risk management approach
   - Set appropriate stop-loss and take-profit levels
   - Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
   - Select the price source (such as close, open, high, or an indicator)
   - Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
  - Long Source: close
  - Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
  
- **Example 2**: To enter when an indicator reaches a specific value:
  - Long Source: ta.rsi(close, 14)
  - Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
   - Small position sizes
   - Reasonable stop-loss distances
   - Limited trades per day
3. **Monitor and adjust**:
   - Use the performance table to track results
   - Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
   - Use ATR-based stops during volatile periods
   - Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
  "strategy": "LongShortExit",
  "action": "{{strategy.order.action}}",
  "price": "{{strategy.order.price}}",
  "quantity": "{{strategy.position_size}}",
  "time": "{{time}}",
  "ticker": "{{ticker}}",
  "position_size": "{{strategy.position_size}}",
  "position_value": "{{strategy.position_value}}",
  "order_id": "{{strategy.order.id}}",
  "order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}} 
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}}  or {{strategy.position_size}} > {{strategy.position_size}} 
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*
Dskyz Adaptive Futures Elite (DAFE)Dskyz Adaptive Futures Edge (DAFE)
 imgur.com 
A Dynamic Futures Trading Strategy
DAFE adapts to market volatility and price action using technical indicators and advanced risk management. It’s built for high-stakes futures trading (e.g., MNQ, BTCUSDT.P), offering modular logic for scalpers and swing traders alike.
 Key Features 
 Adaptive Moving Averages 
 Dynamic Logic:   Fast and slow SMAs adjust lengths via ATR, reacting to momentum shifts and smoothing in calm markets.
 Signals:  Long entry on fast SMA crossing above slow SMA with price confirmation; short on cross below.
 RSI Filtering  (Optional)
 Momentum Check:  Confirms entries with RSI crossovers (e.g., above oversold for longs). Toggle on/off with custom levels.
 Fine-Tuning:  Adjustable lookback and thresholds (e.g., 60/40) for precision.
 Candlestick Pattern Recognition 
 Eng|Enhanced Detection:  Identifies strong bullish/bearish engulfing patterns, validated by volume and range strength (vs. 10-period SMA).
 Conflict Avoidance:  Skips trades if both patterns appear in the lookback window, reducing whipsaws.
 Multi-Timeframe Trend Filter 
 15-Minute Alignment:  Syncs intrabar trades with 15-minute SMA trends; optional for flexibility.
 Dollar-Cost Averaging (DCA)  New! 
 Scaling:  Adds up to a set number of entries (e.g., 4) on pullbacks/rallies, spaced by ATR multiples.
 Control:  Caps exposure and resets on exit, enhancing trend-following potential.
 Trade Execution & Risk Management 
 Entry Rules:  Prioritizes moving averages or patterns (user choice), with volume, volatility, and time filters.
 Stops & Trails: 
 Initial Stop:  ATR-based (2–3.5x, volatility-adjusted).
 Trailing Stop:  Locks profits with configurable ATR offset and multiplier.
 Discipline 
 Cooldown:  Pauses post-exit (e.g., 0–5 minutes).
 Min Hold:  Ensures trades last a set number of bars (e.g., 2–10).
 Visualization & Tools 
 Charts:  Overlays MAs, stops, and signals; trend shaded in background.
 Dashboard:  Shows position, P&L, win rate, and more in real-time.
 Debugging:  Logs signal details for optimization.
 Input Parameters 
 Parameter	                            Purpose	                              Suggested Use 
 Use RSI Filter -              	    Toggle RSI confirmation	             *Disable 4 price-only 
                                                                                                       trading
 RSI Length -               	    RSI period (e.g., 14)	              *7–14 for sensitivity
 RSI Overbought/Oversold -   Adjust for market type                *Set levels (e.g., 60/40)	
 Use Candlestick Patterns -   Enables engulfing signals	      *Disable for MA focus
 Pattern Lookback -  	           Pattern window (e.g., 19)             *10–20 bars for balance
 Use 15m Trend Filter -  	   Align with 15-min trend	               *Enable for trend trades
 Fast/Slow MA Length - 	   Base MA lengths (e.g., 9/19)	       *10–25 / 30–60 per 
                                                                                                         timeframe
 Volatility Threshold -  	    Filters volatile spikes                     *Max ATR/close (e.g., 1%)	
 Min Volume -                       Entry volume threshold                  *Avoid illiquid periods	                 
                                                                                                         (e.g., 10)	
 ATR Length -  	                    ATR period (e.g., 14)	                 *Standard volatility 
                                                                                                          measure
 Trailing Stop ATR Offset -     Trail distance (e.g., 0.5)	         *0.5–1.5 for tightness
 Trailing Stop ATR Multi -  	    Trail multiplier (e.g., 1.0)	          *1–3 for trend room
 Cooldown Minutes - 	       Post-exit pause (e.g., 0–5)	          *Prevents overtrading
 Min Bars to Hold -  	            Min trade duration (e.g., 2)	          *5–10 for intraday
 Trading Hours - 	               Active window (e.g., 9–16)	          *Focus on key sessions
 Use DCA - 	                       Toggle DCA	                                  *Enable for scaling
 Max DCA Entries -  	            Cap entries (e.g., 4)	                  *Limit risk exposure
 DCA ATR Multiplier               Entry spacing (e.g., 1.0)	           *1–2 for wider gaps
 Compliance 
Realistic Testing:    Fixed quantities, capital, and slippage for accurate backtests.
Transparency:        All logic is user-visible and adjustable.
Risk Controls:        Cooldowns, stops, and hold periods ensure stability.
Flexibility:             Adapts to various futures and timeframes.
 Summary 
DAFE excels in volatile futures markets with adaptive logic, DCA scaling, and robust risk tools. Currently in prop account testing, it’s a powerful framework for precision trading.
 Caution 
DAFE is experimental, not a profit guarantee. Futures trading risks significant losses due to leverage. Backtest, simulate, and monitor actively before live use. All trading decisions are your responsibility.
Multi-Timeframe MACD Strategy ver 1.0Multi-Timeframe MACD Strategy: Enhanced Trend Trading with Customizable Entry and Trailing Stop
This strategy utilizes the Moving Average Convergence Divergence (MACD) indicator across multiple timeframes to identify strong trends, generate precise entry and exit signals, and manage risk with an optional trailing stop loss. By combining the insights of both the current chart's timeframe and a user-defined higher timeframe, this strategy aims to improve trade accuracy, reduce exposure to false signals, and capture larger market moves.
Key Features:
Dual Timeframe Analysis: Calculates and analyzes the MACD on both the current chart's timeframe and a user-selected higher timeframe (e.g., Daily MACD on a 1-hour chart). This provides a broader market context, helping to confirm trends and filter out short-term noise.
Configurable MACD: Fine-tune the MACD calculation with adjustable Fast Length, Slow Length, and Signal Length parameters. Optimize the indicator's sensitivity to match your trading style and the volatility of the asset.
Flexible Entry Options: Choose between three distinct entry types:
Crossover: Enters trades when the MACD line crosses above (long) or below (short) the Signal line.
Zero Cross: Enters trades when the MACD line crosses above (long) or below (short) the zero line.
Both: Combines both Crossover and Zero Cross signals, providing more potential entry opportunities.
Independent Timeframe Control: Display and trade based on the current timeframe MACD, the higher timeframe MACD, or both. This allows you to focus on the information most relevant to your analysis.
Optional Trailing Stop Loss: Implements a configurable trailing stop loss to protect profits and limit potential losses. The trailing stop is adjusted dynamically as the price moves in your favor, based on a user-defined percentage.
No Repainting: Employs lookahead=barmerge.lookahead_off in the request.security() function to prevent data leakage and ensure accurate backtesting and real-time signals.
Clear Visual Signals (Optional): Includes optional plotting of the MACD and Signal lines for both timeframes, with distinct colors for easy visual identification. These plots are for visual confirmation and are not required for the strategy's logic.
Suitable for Various Trading Styles: Adaptable to swing trading, day trading, and trend-following strategies across diverse markets (stocks, forex, cryptocurrencies, etc.).
Fully Customizable: All parameters are adjustable, including timeframes, MACD Settings, Entry signal type and trailing stop settings.
How it Works:
MACD Calculation: The strategy calculates the MACD (using the standard formula) for both the current chart's timeframe and the specified higher timeframe.
Trend Identification: The relationship between the MACD line, Signal line, and zero line is used to determine the current trend for each timeframe.
Entry Signals: Buy/sell signals are generated based on the selected "Entry Type":
Crossover: A long signal is generated when the MACD line crosses above the Signal line, and both timeframes are in agreement (if both are enabled). A short signal is generated when the MACD line crosses below the Signal line, and both timeframes are in agreement.
Zero Cross: A long signal is generated when the MACD line crosses above the zero line, and both timeframes agree. A short signal is generated when the MACD line crosses below the zero line and both timeframes agree.
Both: Combines Crossover and Zero Cross signals.
Trailing Stop Loss (Optional): If enabled, a trailing stop loss is set at a specified percentage below (for long positions) or above (for short positions) the entry price. The stop-loss is automatically adjusted as the price moves favorably.
Exit Signals:
Without Trailing Stop: Positions are closed when the MACD signals reverse according to the selected "Entry Type" (e.g., a long position is closed when the MACD line crosses below the Signal line if using "Crossover" entries).
With Trailing Stop: Positions are closed if the price hits the trailing stop loss.
Backtesting and Optimization: The strategy automatically backtests on the chart's historical data, allowing you to assess its performance and optimize parameters for different assets and timeframes.
Example Use Cases:
Confirming Trend Strength: A trader on a 1-hour chart sees a bullish MACD crossover on the current timeframe. They check the MTF MACD strategy and see that the Daily MACD is also bullish, confirming the strength of the uptrend.
Filtering Noise: A trader using a 15-minute chart wants to avoid false signals from short-term volatility. They use the strategy with a 4-hour higher timeframe to filter out noise and only trade in the direction of the dominant trend.
Dynamic Risk Management: A trader enters a long position and enables the trailing stop loss. As the price rises, the trailing stop is automatically adjusted upwards, protecting profits. The trade is exited either when the MACD reverses or when the price hits the trailing stop.
Disclaimer:
The MACD is a lagging indicator and can produce false signals, especially in ranging markets. This strategy is for educational and informational purposes only and should not be considered financial advice. Backtest and optimize the strategy thoroughly, combine it with other technical analysis tools, and always implement sound risk management practices before using it with real capital. Past performance is not indicative of future results. Conduct your own due diligence and consider your risk tolerance before making any trading decisions.
Awesome Oscillator (AO) with Signals [AIBitcoinTrend]👽  Multi-Scale Awesome Oscillator (AO) with Signals (AIBitcoinTrend) 
The Multi-Scale Awesome Oscillator transforms the traditional Awesome Oscillator (AO) by integrating multi-scale wavelet filtering, enhancing its ability to detect momentum shifts while maintaining responsiveness across different market conditions.
 Unlike conventional AO calculations, this advanced version refines trend structures using high-frequency, medium-frequency, and low-frequency wavelet components, providing traders with superior clarity and adaptability. 
Additionally, it features real-time divergence detection and an ATR-based dynamic trailing stop, making it a powerful tool for momentum analysis, reversals, and breakout strategies.
   
👽  What Makes the Multi-Scale AO – Wavelet-Enhanced Momentum Unique? 
Unlike traditional AO indicators, this enhanced version leverages wavelet-based decomposition and volatility-adjusted normalization, ensuring improved signal consistency across various timeframes and assets.
 ✅  Wavelet Smoothing – Multi-Scale Extraction  – Captures short-term fluctuations while preserving broader trend structures.
✅  Frequency-Based Detail Weights  – Separates high, medium, and low-frequency components to reduce noise and improve trend clarity.
✅  Real-Time Divergence Detection  – Identifies bullish and bearish divergences for early trend reversals.
✅  Crossovers & ATR-Based Trailing Stops  – Implements intelligent trade management with adaptive stop-loss levels. 
   
👽  The Math Behind the Indicator 
👾  Wavelet-Based AO Smoothing 
The indicator applies multi-scale wavelet decomposition to extract high-frequency, medium-frequency, and low-frequency trend components, ensuring an optimal balance between reactivity and smoothness.
 sma1 = ta.sma(signal, waveletPeriod1)
sma2 = ta.sma(signal, waveletPeriod2)
sma3 = ta.sma(signal, waveletPeriod3)
detail1 = signal - sma1      // High-frequency detail
detail2 = sma1 - sma2        // Intermediate detail
detail3 = sma2 - sma3        // Low-frequency detail
advancedAO = weightDetail1 * detail1 + weightDetail2 * detail2 + weightDetail3 * detail3 
 Why It Works: 
 
 Short-Term Smoothing:  Captures rapid fluctuations while minimizing noise.
 Medium-Term Smoothing:  Balances short-term and long-term trends.
 Long-Term Smoothing:  Enhances trend stability and reduces false signals.
 
👾  Z-Score Normalization 
To ensure consistency across different markets, the Awesome Oscillator is normalized using a Z-score transformation, making overbought and oversold levels stable across all assets.
 normFactor = ta.stdev(advancedAO, normPeriod)
normalizedAO = advancedAO / nz(normFactor, 1) 
 Why It Works: 
 
 Standardizes AO values for comparison across assets.
 Enhances signal reliability, preventing misleading spikes.
 
👽  How Traders Can Use This Indicator 
👾  Divergence Trading Strategy 
 Bullish Divergence 
 
 Price makes a lower low, while AO forms a higher low.
 A buy signal is confirmed when AO starts rising.
 
 Bearish Divergence 
 
 Price makes a higher high, while AO forms a lower high.
 A sell signal is confirmed when AO starts declining.
 
   
👾  Buy & Sell Signals with Trailing Stop 
 Bullish Setup: 
 ✅AO crosses above the bullish trigger level → Buy Signal.
✅Trailing stop placed at Low - (ATR × Multiplier).
✅Exit if price crosses below the stop. 
  Bearish Setup: 
 ✅AO crosses below the bearish trigger level → Sell Signal.
✅Trailing stop placed at High + (ATR × Multiplier).
✅Exit if price crosses above the stop. 
  
👽  Why It’s Useful for Traders 
 
 Wavelet-Enhanced Filtering  – Retains essential trend details while eliminating excessive noise.
 Multi-Scale Momentum Analysis  – Separates different trend frequencies for enhanced clarity.
 Real-Time Divergence Alerts  – Identifies early reversal signals for better entries and exits.
 ATR-Based Risk Management  – Ensures stops dynamically adapt to market conditions.
 Works Across Markets & Timeframes  – Suitable for stocks, forex, crypto, and futures trading.
 
👽  Indicator Settings 
 
 AO Short Period  – Defines the short-term moving average for AO calculation.
 AO Long Period  – Defines the long-term moving average for AO smoothing.
 Wavelet Smoothing  – Adjusts multi-scale decomposition for different market conditions.
 Divergence Detection  – Enables or disables real-time divergence analysis. Normalization Period – Sets the lookback period for standard deviation-based AO normalization.
 Cross Signals Sensitivity  – Controls crossover signal strength for buy/sell signals.
 ATR Trailing Stop Multiplier  – Adjusts the sensitivity of the trailing stop.
 
 Disclaimer: This indicator is designed for educational purposes and does not constitute financial advice. Please consult a qualified financial advisor before making investment decisions. 
Enhanced ROC - Savitzky–Golay [AIBitcoinTrend]👽  Adaptive ROC - Savitzky–Golay (AIBitcoinTrend) 
The Adaptive ROC - Savitzky–Golay redefines traditional Rate of Change (ROC) analysis by integrating Savitzky–Golay smoothing with volatility-adaptive normalization, allowing it to dynamically adjust across different market conditions. Unlike the standard ROC, which reacts rigidly to price changes, this advanced version refines trend signals while maintaining responsiveness to volatility.
Additionally, this indicator features real-time divergence detection and an ATR-based trailing stop system, equipping traders with a powerful toolset for momentum analysis, reversals, and trend-following strategies.
  
👽  What Makes the Adaptive ROC - Savitzky–Golay Unique? 
Unlike conventional ROC indicators, this enhanced version leverages volatility-adjusted scaling and Z-score normalization to improve signal consistency across different timeframes and assets.
 ✅  Savitzky–Golay Smoothing  – Reduces noise while preserving trend structure for clearer signals.
✅  Volatility-Adaptive Normalization  – Ensures that overbought and oversold thresholds remain consistent across different markets.
✅  Real-Time Divergence Detection  – Identifies early bullish and bearish divergence signals for potential reversals.
✅  Crossovers & ATR-Based Trailing Stops  – Implements intelligent trade management with dynamic stop levels.  
   
👽  The Math Behind the Indicator 
👾  Savitzky–Golay Smoothing 
The indicator applies a Savitzky–Golay filter to the raw ROC data, creating a smoother curve while preserving key inflection points. This technique prevents excessive lag while maintaining the integrity of price movements.
 sg_roc = (roc_raw + 3*roc_raw  + 5*roc_raw  + 7*roc_raw  + 5*roc_raw  + 3*roc_raw  + roc_raw ) / 25  
👾  Volatility-Adaptive Scaling 
 By dynamically adjusting the smoothed ROC using standard deviation, the indicator ensures that momentum readings remain relative to the market’s current volatility.
 volatility = ta.stdev(close, rocLength)
dynamicFactor = 1 / (1 + volatility / 100)
advanced_sg_roc = sg_roc * dynamicFactor 
👾  Z-Score Normalization 
 To maintain a stable Overbought/Oversold structure across different markets, the ROC is normalized using a Z-score transformation, ensuring its values remain statistically relevant.
 rocMean  = ta.wma(advanced_sg_roc, lenZ)
rocStdev = ta.stdev(advanced_sg_roc, lenZ)
zRoc = (advanced_sg_roc - rocMean) / rocStdev 
👽  How Traders Can Use This Indicator 
👾  Divergence Trading Strategy 
 Bullish Divergence Setup: 
 
 Price makes a lower low, while the ROC forms a higher low.
 A buy signal is confirmed when the ROC starts rising.
 
 Bearish Divergence Setup: 
 
 Price makes a higher high, while the ROC forms a lower high.
 A sell signal is confirmed when the ROC starts declining.
 
  
👾  Buy & Sell Signals with Trailing Stop 
 Bullish Setup: 
  ✅ ROC crosses above the bullish trigger level → Buy Signal.
 ✅ A bullish trailing stop is placed at Low - (ATR × Multiplier).
 ✅ Exit if price crosses below the stop. 
 Bearish Setup: 
  ✅ ROC crosses below the bearish trigger level → Sell Signal.
 ✅ A bearish trailing stop is placed at High + (ATR × Multiplier).
 ✅ Exit if price crosses above the stop. 
   
👽  Why It’s Useful for Traders 
 
 Savitzky–Golay Filtering  – Retains essential trend details while eliminating excessive noise.
 Volatility-Adjusted Normalization  – Makes overbought/oversold levels universally reliable across markets.
 Real-Time Divergence Alerts  – Identifies early reversal signals for optimal entries and exits.
 ATR-Based Risk Management  – Ensures stops dynamically adapt to market conditions.
 Works Across Markets & Timeframes  - Suitable for stocks, forex, crypto, and futures trading.
 
👽  Indicator Settings 
 
 ROC Period  – Defines the number of bars used for ROC calculation.
 Smoothing Strength  – Adjusts the degree of Savitzky–Golay filtering.
 Volatility Scaling  – Enables or disables the adaptive volatility factor.
 Enable Divergence Analysis  – Turns on real-time divergence detection.
 Lookback Period  – Specifies the pivot detection period for divergences.
 Enable Crosses Signals  – Activates trade signals based on ROC crossovers.
 ATR Multiplier  – Controls the sensitivity of the trailing stop.
 
 Disclaimer: This indicator is designed for educational purposes and does not constitute financial advice. Please consult a qualified financial advisor before making investment decisions. 
Volatility-Enhanced Williams %R [AIBitcoinTrend]👽  Volatility-Enhanced Williams %R (AIBitcoinTrend) 
The Volatility-Enhanced Williams %R takes the classic Williams %R oscillator to the next level by incorporating volatility-adaptive smoothing, making it significantly more responsive to market dynamics. Unlike the traditional version, which uses a fixed calculation method, this indicator dynamically adjusts its smoothing factor based on market volatility, helping traders capture trends more effectively while filtering out noise.
Additionally, the indicator includes real-time divergence detection and an ATR-based trailing stop system, providing traders with enhanced risk management tools and early reversal signals.
   
👽  What Makes the Volatility-Enhanced Williams %R Unique? 
Unlike the standard Williams %R, which applies a simple lookback-based formula, this version integrates adaptive smoothing and volatility-based filtering to refine its signals and reduce false breakouts.
 ✅  Volatility-Adaptive Smoothing  – Adjusts dynamically based on standard deviation, enhancing signal accuracy.
 ✅  Real-Time Divergence Detection  – Identifies bullish and bearish divergences for early trend reversal signals.
 ✅  Crossovers & Trailing Stops  – Implements Williams %R crossovers with ATR-based trailing stops for intelligent trade management. 
   
👽  The Math Behind the Indicator 
👾  Volatility-Adaptive Smoothing 
 The indicator smooths the Williams %R calculation by applying an adaptive filtering mechanism, which adjusts its responsiveness based on market conditions. This helps to eliminate whipsaws and makes trend-following strategies more reliable.
 The smoothing function is defined as: 
 clamp(x, lo, hi) => math.min(math.max(x, lo), hi)
adaptive(src, prev, len, divisor, minAlpha, maxAlpha) =>
    vol   = ta.stdev(src, len)
    alpha = clamp(vol / divisor, minAlpha, maxAlpha)
    prev + alpha * (src - prev) 
 Where: 
 
  Volatility Factor (vol) measures price dispersion using standard deviation.
  Adaptive Alpha (alpha) dynamically adjusts smoothing strength.
  Clamped Output ensures that the smoothing factor remains within a stable range.
 
👽  How Traders Can Use This Indicator 
👾  Divergence Trading Strategy 
  Bullish Divergence Setup: 
 
  Price makes a lower low, while Williams %R forms a higher low.
  Buy signal is confirmed when Williams %R reverses upward.
 
 Bearish Divergence Setup: 
 
  Price makes a higher high, while Williams %R forms a lower high.
  Sell signal is confirmed when Williams %R reverses downward.
 
  
👾  Trailing Stop & Signal-Based Trading 
 Bullish Setup: 
  ✅ Williams %R crosses above trigger level → Buy signal.
 ✅ A bullish trailing stop is placed at Low - (ATR × Multiplier).
 ✅ Exit if price crosses below the stop. 
 Bearish Setup: 
  ✅ Williams %R crosses below trigger level → Sell signal.
 ✅ A bearish trailing stop is placed at High + (ATR × Multiplier).
 ✅ Exit if price crosses above the stop. 
   
👽  Why It’s Useful for Traders 
 
 Adaptive Filtering Mechanism  – Avoids excessive noise while maintaining responsiveness.
   Real-Time Divergence Alerts  – Helps traders anticipate market reversals before they occur.
   ATR-Based Risk Management  – Stops dynamically adjust based on market volatility.
   Multi-Market Compatibility  – Works effectively across stocks, forex, crypto, and futures.
 
👽  Indicator Settings 
 
 Smoothing Factor  – Controls how aggressively the indicator adapts to volatility.
   Enable Divergence Analysis  – Activates real-time divergence detection.
   Lookback Period  – Defines the number of bars for detecting pivot points.
   Enable Crosses Signals  – Turns on Williams %R crossover-based trade signals.
   ATR Multiplier  – Adjusts trailing stop sensitivity.
 
 
 Disclaimer: This indicator is designed for educational purposes and does not constitute financial advice. Please consult a qualified financial advisor before making investment decisions. 
CCI with Signals & Divergence [AIBitcoinTrend]👽  CCI with Signals & Divergence (AIBitcoinTrend) 
The Hilbert Adaptive CCI with Signals & Divergence takes the traditional Commodity Channel Index (CCI) to the next level by dynamically adjusting its calculation period based on real-time market cycles using Hilbert Transform Cycle Detection. This makes it far superior to standard CCI, as it adapts to fast-moving trends and slow consolidations, filtering noise and improving signal accuracy.
Additionally, the indicator includes real-time divergence detection and an ATR-based trailing stop system, helping traders identify potential reversals and manage risk effectively.
  
 
👽  What Makes the Hilbert Adaptive CCI Unique? 
Unlike the traditional CCI, which uses a fixed-length lookback period, this version automatically adjusts its lookback period using Hilbert Transform to detect the dominant cycle in the market.
 ✅  Hilbert Transform Adaptive Lookback  – Dynamically detects cycle length to adjust CCI sensitivity.
 ✅  Real-Time Divergence Detection  – Instantly identifies bullish and bearish divergences for early reversal signals.
 ✅ Implement Crossover/Crossunder signals  tied to ATR-based trailing stops for risk management 
   
👽  The Math Behind the Indicator 
👾  Hilbert Transform Cycle Detection 
The Hilbert Transform estimates the dominant market cycle length based on the frequency of price oscillations. It is computed using the in-phase and quadrature components of the price series:
 tp = (high + low + close) / 3
smooth = (tp + 2 * tp  + 2 * tp  + tp ) / 6
detrender = smooth - smooth 
quadrature = detrender - detrender 
inPhase = detrender  + quadrature 
outPhase = quadrature  - inPhase 
instPeriod = 0.0
deltaPhase = math.abs(inPhase - inPhase ) + math.abs(outPhase - outPhase )
instPeriod := nz(3.25 / deltaPhase, instPeriod )
dominantCycle = int(math.min(math.max(instPeriod, cciMinPeriod), 500)) 
 Where: 
 
 In-Phase & Out-Phase Components are derived from a detrended version of the price series.
 Instantaneous Frequency measures the rate of cycle change, allowing the CCI period to adjust dynamically.
 The result is bounded within a user-defined min/max range, ensuring stability.
 
👽  How Traders Can Use This Indicator 
👾  Divergence Trading Strategy 
 Bullish Divergence Setup: 
 
 Price makes a lower low, while CCI forms a higher low.
 Buy signal is confirmed when CCI shows upward momentum.
 
 Bearish Divergence Setup: 
 
 Price makes a higher high, while CCI forms a lower high.
 Sell signal is confirmed when CCI shows downward momentum.
 
   
👾  Trailing Stop & Signal-Based Trading 
 Bullish Setup: 
  ✅ CCI crosses above -100 → Buy signal.
 ✅ A bullish trailing stop is placed at Low - (ATR × Multiplier).
 ✅ Exit if the price crosses below the stop. 
 Bearish Setup: 
  ✅ CCI crosses below 100 → Sell signal.
 ✅ A bearish trailing stop is placed at High + (ATR × Multiplier).
 ✅ Exit if the price crosses above the stop. 
   
👽  Why It’s Useful for Traders 
 
 Hilbert Adaptive Period Calculation  – No more fixed-length periods; the indicator dynamically adapts to market conditions.
   Real-Time Divergence Alerts  – Helps traders anticipate market reversals before they occur.
   ATR-Based Risk Management  – Stops automatically adjust based on volatility.
   Works Across Multiple Markets & Timeframes  – Ideal for stocks, forex, crypto, and futures.
 
👽  Indicator Settings 
 
 Min & Max CCI Period  – Defines the adaptive range for Hilbert-based lookback.
 Smoothing Factor  – Controls the degree of smoothing applied to CCI.
 Enable Divergence Analysis  – Toggles real-time divergence detection.
 Lookback Period  – Defines the number of bars for detecting pivot points.
 Enable Crosses Signals  – Turns on CCI crossover-based trade signals.
 ATR Multiplier  – Adjusts trailing stop sensitivity.
 
 Disclaimer: This indicator is designed for educational purposes and does not constitute financial advice. Please consult a qualified financial advisor before making investment decisions. 
Milvetti_Pineconnector_LibraryLibrary   "Milvetti_Pineconnector_Library" 
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
 buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a buy stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell limit order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
 sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment) 
  Create a sell stop order message
  Parameters:
     licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
     symbol (string) : Symbol. Default is syminfo.ticker
     pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
     risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
     sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
     beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
     beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
     trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
     trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
     trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
     atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
     atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
     atrPeriod (int) : ATR averaging period. Default is 0
     atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
     atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
     accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
     secret (string) 
     comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
Volatility System by W. WilderVolatility System (Volatility Stops) Similarity 
Most traders adjust their stops over time in the direction of the trend in order to lock in profits. Apart from moving averages, one of the most popular techniques is trailing stops using a multiple of Average True Range. There are several variations:
 
 The original Volatility System(Volatility Stops), introduced by Welles Wilder in his 1978 book: New Concepts in Technical Trading Systems
 Chandelier exits introduced by Alexander Elder in Come Into My Trading Room (2002) trail the stops from Highs or Lows rather than Closing Price
 Average True Range Trailing Stops are similar to the above, but include a ratchet mechanism to prevent stops moving down during an up-trend or rising during a down-trend, as ATR increases
 WillTrend intoduced by Larry Williams in 1988
 
 Comparison of systems 
All the systems under consideration have one common ingredient - ATR. ATR was developed by Welles Wilder and described in his book in 1978, also in this book the Volatility System was described, which in the future became known as Volatility Stops.
In fact, Wilder is the father of such systems due to the presence of ATR in the calculation of this type of indicator.
 The main difference of Volatility System 
Followers such as Larry Williams and Alexander Elder made minor changes to the value based on the ATR, mainly focusing on changing the base to which this value is added or subtracted.
Larry Williams uses the square root of 5 as a multiplier and calculates the ATR with a period of 66, and Alexander Elder uses a multiplier of 2.5-3.5 applying it to the ATR with a period of 22. Both authors changed the original value for ATR and multiplier calculations. Alexander Elder is closest to the original Welles Wilder calculation, which used a multiplier of 2.8.-3.1 applying it to an ATR with a period of 7.
As a reference, Elder took the Highest High(22) from which he subtracts ATR*Multiplier in an uptrend or the Lowest Low(22) to which he adds  ATR*Multiplier to obtain the turning point (SAR).
Larry Williams uses the average price of extremes (Highest High(10) + Lowest Low(10)) / 2 as a reference base to which he adds or subtracts the ATR*Multilpyer values.
Both systems differ from the original, because Wilder used Significan Close(SIC) in his calculations. SIC is the maximum closing price during an uptrend and the minimum closing price during a downtrend, which
does not go beyond the current trade, as in other systems. To calculate the base when a trend changes, bars that are outside the current trend will be used when calculating WillTrend and Chandelier Exit, in contrast to the Volatility System, which takes SIC values only within the current trade. This is the main difference from subsequent developments of similar systems.
 Improvements made 
The original Volatility System is present as an indicator on TradingView, but it is an improved version with the addition of a ratchet and works differently from the original Weilder system.
List of improvements:
 
 Added the ability to remove the ratchet. You need to turn off the "Trail one way" checkbox in the setting menu. When this function is turned off, the system will operate in the author-inventor mode. On some instruments, the original system works much better than the improved ratchet system, which cannot be turned off.
 Added the ability to use Highest High and Lowest Low as a base instead of the closing price.
 
 Volatility Stops Formula Description 
Welles Wilder's system uses Closing Price and incorporates a stop-and-reverse feature (as with his Parabolic SAR).
Determine the initial trend direction
Calculate the Significant Close ("SIC"): the highest close reached in an up-trend or the lowest close in a down-trend
Calculate Average True Range ("ATR") for the selected period (7 days in this example)
Multiply ATR by the Multiple (3.0 in this example, best values author describes as 2.8-3.1)
The first stop is calculated in day 7 and plotted for day 8
If an up-trend, the first stop is SIC - 3 * ATR, otherwise SIC + 3 * ATR for a down-trend
Repeat each day until price closes below the stop (or above in a down-trend)
Set SIC equal to the latest Close, reverse the trend and continue.
 Chandelier Exit Description 
Chandelier Exits subtract a multiple of Average True Range ("ATR") from the highest high for the selected period. Using the default settings as an example:
Highest High in last 22 days - 3 * ATR for 22 days
In a down-trend the formula is reversed:
Lowest Low in last 22 days + 3 * ATR for 22 days
The time period must be long enough to capture the highest point of the recent up-trend: too short and the stops move downward; too long and the high may be taken from a previous down-trend.
It is not essential to use the same period for up and down trends; down-trends are notoriously faster than up-trends and may benefit from a shorter time period.
The multiple of 3 may be varied, but most traders settle between 2.5 and 3.5.
 WillTrend Description 
Larry Williams is prefer to used the Square Root from 5 as a multiplayer for ATR. SQRT(5) = 2.236
WillTrend subtract a multiple of Average True Range ("ATR") from the Middle Price (Highest High for the selected period + Lowest Low for the selected period / 2).
(Highest High in last 10 days + Lowest Low in last 10 days) / 2 - 2.236 * ATR for 66 days
In a down-trend the formula is reversed:
(Highest High in last 10 days + Lowest Low in last 10 days) / 2 + 2.236 * ATR for 66 days
Qullamaggie Breakout V2After publishing the Qullamaggie Breakout script and seeing that it had some decent results, I wanted to explore it a bit further. There were a few things I didn't like about that methodology that didn't really jive with the way I like to trade.  So what I did was combined the Breakout Trend Follower strategy I had been using for entries with the Qullamaggie strategy for trailing stops once in profit.  The results seem pretty good to me and an approach that fits my personality and something I can actually trade.  Typically better profit than the Breakout Trend Follower by giving more room for your winners to run, while still protecting your entries by moving up the trailing stop until you are in profit, all while taking less trades, so that's great.  
Everything is done with stop orders.  So you set your buy stop at the recent swing high point and wait for a breakout.  Once in a position you set your sell stop at the recent swing low point.  The most recent swing high and low are shown on the chart for easy reference with the blue and orange horizontal lines.  Once in a trade, trail your sell stop after a new swing low is registered (shown by the thicker orange stop line).  Once you are in profit, leave that hard stop level there (the orange line will stay there helping you).  Now, you wait for price to cross a Moving Average of your choosing (default is Daily 10 MA).  Once the bar crosses that moving average, you move your stop to the low of that candle (shown by the blue stop line) and trail your stop along every crossing of the moving average until the trend changes and takes out your stop.  So managing this trade is pretty easy...just wait for the stop lines to move and move your stop with them.  It's a great way to trade when you can't be at your computer all the time because the stop orders take care of execution on both buy and sell side.  If you use a daily timeframe for your moving averages (the default), you really only need to move stops around about once a day, so is a good part time trader's strategy in my opinion.
The best opportunities will come by scanning for stocks in the longer term timeframe of your moving averages.  Wait for a consolidation on that timeframe so the anticipated breakout has some room to run.  Once you've identified a good candidate, zoom in to your lower timeframe where the swing highs/lows will act as your entry and exit points, all while keeping the moving averages consistent between timeframes.
Hope you guys find it useful.
A few options available:
- Choose any timeframe for your moving averages, while using swing high/low points on intraday charts.
- Choose one of two moving averages shown for your trailing stops (default 10 and 20 MA).
- Choose to use the third moving average as a filter for keeping you out of trades that are below it (trading with the trend).
- Use the charts resolution candle or the moving average resolution candle for the moving average trailing stop.
- Only take trades where your buy level minus stop level is below a % of the Average Daily Range (ADR).  This allows you to potentially have better risk/reward.  I added a little table that shows the ADR of the stock/ticker as well as the range between the recent buy and sell levels (shown by the orange and blue horizontal lines) for easy reference.
Cowabunga System from babypips.comPlease do read the information below as well, especially if you are new to Forex.
The Cowabunga System is a type of Mechanical Trading System that filters trades based on the trend of the 4 hour chart with EMAs and some other familiar indicators (RSI, Stochastics and MACD) while entering trades base on 15 minute chart.
I have coded (quite amateurishly) the basic system onto a 15 minute chart (the 4 hour settings are coded as well). The author says the system is to be traded off the 15 minute chart with the 4 hour chart only as a reference for trend direction. 
 4 Hour Chart Settings 
 
 5 EMA
 10 EMA
  Stochastics (10,3,3)
  RSI (9)
 
Then we move onto the 15 minute chart, where he gives us the trade entry rules.
 15 Minute Chart Settings 
 
 5 EMA
 10 EMA
  Stochastics (10,3,3)
  RSI (9)
  MACD (12,26,9)
 Entry Rules  - long entry rules used, obviously reverse these for shorting.
1. EMA must cross above the 10 EMA.
2. RSI must be greater than 50 and not overbought.
3. Stochastic must be headed up and not be in overbought territory.
4. MACD histogram must go from negative to positive OR be negative and start to increase in value. 
 What I did. 
1. Set the RSI and Stochastic levels to avoid entries when they indicate overbought conditions for long and oversold conditions for short (80 and 20 levels). 
2. Users can input specific times they want to backtest.
3. User's can configure profit targets, trailing stops and stops. Default is set it to was 100 pips profit target with a 40 pip trailing stop. (Note, when you are changing these values, please note that each pip is worth 10, so 100 pips is entered as 1000.)
The Cowabunga System from babypips.com is another popular and active system. The author,  Pip Surfer,  continues to post wins and losses with this system. It shows there is a lot of honesty and integrity with this system if the author keeps up to date even 10 years later and is not afraid of sharing the times the system causes losses.
As an example of this,  here is post he shared just last week . It's almost like a journal, he gives specific times and reasons why he entered, lets the readers know when he was stopped out, etc. I think that what he does is equally important as his system. 
To read more about this system, visit the thread on babypips.com,  click here.
Trend Pullback System```{"variant":"standard","id":"36492","title":"Trend Pullback System Description"}
Trend Pullback System is a price-action trend continuation model that looks to enter on pullbacks, not breakouts. It’s designed to find high-quality long/short entries inside an already established trend, place the stop at meaningful structure, trail that stop as structure evolves, and warn you when the trade thesis is no longer valid.
Developed by: Mohammed Bedaiwi
---------------------------------
HOW IT WORKS
---------------------------------
1. Trend Detection  
   • The strategy defines overall bias using moving averages.  
   • Bullish environment (“uptrend”): price above the slower MA, fast MA above slow MA, and the slow MA is sloping up.  
   • Bearish environment (“downtrend”): price below the slower MA, fast MA below slow MA, and the slow MA is sloping down.  
   This prevents trading against chop and focuses on continuation moves in the dominant direction.
2. Pullback + Re-entry Logic  
   • The script waits for price to pull back into structure (support in an uptrend, resistance in a downtrend), and then push back in the direction of the main trend.  
   • That “push back” is the setup trigger. We don’t chase the first breakout candle — we buy/sell the retest + resume.
3. Structural Levels (“Diamonds”)  
   • Green diamond (below bar): bullish pivot low formed while the trend is bullish. This marks defended support.  
     - Use it as a re-entry zone for longs.  
     - Use it to trail a stop higher when you’re already long.  
     - Shorts can take profit here because buyers stepped in.  
   • Red diamond (above bar): bearish pivot high formed while the trend is bearish. This marks defended resistance.  
     - Use it as a re-entry zone for shorts.  
     - Use it to trail a stop lower when you’re already short.  
     - Longs can take profit here because sellers stepped in.
4. Entry Signals  
   • BUY arrow (green triangle up under the candle, text like “BUY” / “BUY Zone”):  
     - LongSetup is true.  
     - Trend is bullish or turning bullish.  
     - Price just bounced off recent defended support (green diamond) and reclaimed short-term momentum.  
     Meaning: enter long here or cover/exit shorts.  
   • SELL arrow (red triangle down above the candle):  
     - ShortSetup is true.  
     - Trend is bearish or turning bearish.  
     - Price just rolled down from defended resistance (red diamond) and lost short-term momentum.  
     Meaning: enter short here or take profit on longs.  
   These are the primary trade entries. They are meant to be actionable.
5. Weak Setups (“W” in yellow)  
   • Yellow triangle with “W”:  
     - A possible long/short idea is trying to form, BUT the higher-timeframe confirmation is not fully there yet.  
     - Think of it as early pressure / early caution, not a full signal.  
   • You usually watch these areas rather than jumping in immediately.
6. Exit Warning (orange “EXIT” label above a bar)  
   • The strategy will raise an EXIT marker when you’re in a trade and the *opposite* side just produced a confirmed setup.  
     - You’re short and a valid longSetup appears → EXIT.  
     - You’re long and a valid shortSetup appears → EXIT.  
   • This is basically: “Close or reduce — the other side just took control.”  
   • It’s not just a trailing stop hit; it’s a regime flip warning.
7. Stop, Target, and Trailing  
   • On every new setup, the script records:  
     - Initial stop: recent swing beyond the defended level (below support for longs, above resistance for shorts).  
     - Initial target: recent opposing swing.  
   • While you’re in position, if new confirming diamonds print in your favor, the stop can trail toward the new defended level.  
   • This creates structure-based risk management (not just fixed % or ATR).
8. Reference Levels  
   • The strategy also plots prior higher-timeframe closes (last week’s close, last month’s close, last year’s close). These can behave as magnets or stall points.  
   • They’re helpful for take-profit timing and for reading “are we trading above or below last month’s close?”
9. Momentum Panel (hidden by default)  
   • Internally, the script calculates an SMI-style momentum oscillator with overbought/oversold zones.  
   • This is optional visual confirmation and does not drive the core entry/exit logic.
---------------------------------
WHAT A TRADE LOOKS LIKE IN REAL PRICE ACTION
---------------------------------
Early warning  
• Yellow W + red diamonds + red down arrows = “This is getting weak. Short setups are here.”  
• You may also see something like “My Short Entry Id.” That’s where the short side actually engages.
Bearish follow-through, then exhaustion  
• Price bleeds down.  
• Then the orange EXIT appears.  
  → Translation: “If you’re still short, close it. Buyers are stepping in hard. Risk of reversal is now high.”
Regime flip  
• Right after EXIT, multiple green BUY arrows fire together (“BUY”, “BUYZone”).  
• That’s the true long trigger.  
  → This is where you either enter long or flip from short to long.
Expansion leg  
• After that flip, price rips up for multiple candles / days / weeks.  
• While it runs:
  - Green diamonds appear under pullbacks → “dip buy zones / trail stop up here.”  
  - More BUY arrows show on minor pullbacks → continuation long / scale adds.
Distribution / topping  
• Later, you start seeing new yellow W triangles again near local highs. That’s your “careful, this might be topping” warning.  
• You finally get a hard red candle, and green diamonds stop stacking.  
  → That’s where you tighten risk, scale out, or assume the move is mature.
In plain terms, the model is doing the following for you:
• It puts you short during weakness.  
• It tells you when to get OUT of the short.  
• It flips you long right as control changes.  
• It gives you a structure-based trail the whole way up.  
• It warns you again when momentum at the top starts cracking.
That is exactly how the logic was designed.
---------------------------------
QUICK INTERPRETATION CHEAT SHEET
---------------------------------
🔻 Red triangle + “Short Entry” near a red diamond  
   → Short entry zone (or take profit on a long).
🟥 Red diamond above bar  
   → Sellers defended here. Treat it as resistance. Good place to trail short stops just above that level. Avoid chasing longs straight into it.
🟨 Yellow W  
   → Attention only. Early pressure / possible turn. Not fully confirmed.
🟧 EXIT (orange label)  
   → The opposite side just printed a real setup. Close the old idea (cover shorts if you’re short, exit longs if you’re long). Thesis invalid.
🟩 Burst of green BUY triangles after EXIT  
   → Long entry. Also a “cover shorts now” alert. This is the core money entry in bullish reversals.
💎 Green diamond below bar  
   → Bulls defended that level. Good for trailing your long stop up, and good “buy the dip in trend” locations.
📈 Blue / teal MAs stacked and rising  
   → Confirmed bullish structure. You’re in trend continuation mode, so dips are opportunities, not automatic exits.
---------------------------------
COLOR / SHAPE KEY
---------------------------------
• Green triangle up (“BUY”, “BUY Zone”):  
  Long entry / cover shorts / continuation long trigger.  
• Red triangle down:  
  Short entry / take profit on longs / continuation short trigger.  
• Orange “EXIT” label:  
  Opposite side just fired a real setup. The previous trade thesis is now invalid.  
• Green diamond below price:  
  Bullish defended support in an uptrend. Use for dip buys, trailing stops on longs, and objective cover zones for shorts.  
• Red diamond above price:  
  Bearish defended resistance in a downtrend. Use for re-entry shorts, trailing stops on shorts, and objective scale-out zones for longs.  
• Yellow “W”:  
  Weak / early potential setup. Watch it, don’t blindly trust it.  
• Moving average bands (fast MA, slow MA, Hull MA):  
  When stacked and rising, bullish control. When stacked and falling, bearish control.
---------------------------------
INTENT
---------------------------------
This system is built to:
  • Trade with momentum, not against it.  
  • Enter on pullbacks into proven structure, not chase stretched breakouts.  
  • Automate stop/target logic around actual defended swing levels.  
  • Warn you when the other side takes over so you don’t give back gains.
Typical usage:
  1. In an uptrend, wait for price to pull back, print a green diamond (support proved), then take the first BUY arrow that fires.  
  2. In a downtrend, wait for a bounce into resistance, print a red diamond (sellers proved), then take the first SELL arrow that fires.  
  3. Respect EXIT when it appears — that’s the model saying “this trade is done.”
---------------------------------
DISCLAIMER
---------------------------------
This script is for educational and research purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any security, cryptoasset, or derivative. Markets carry risk. Past performance does not guarantee future results. You are fully responsible for your own decisions, position sizing, risk management, and compliance with all applicable laws and regulations.
Pivot Regime Anchored VWAP [CHE]  Pivot Regime Anchored VWAP   — Detects body-based pivot regimes to classify swing highs and lows, anchoring volume-weighted average price lines directly at higher highs and lower lows for adaptive reference levels.
  Summary 
This indicator identifies shifts between top and bottom regimes through breakouts in candle body highs and lows, labeling swing points as higher highs, lower highs, lower lows, or higher lows. It then draws anchored volume-weighted average price lines starting from the most recent higher high and lower low, providing dynamic support and resistance that evolve with volume flow. These anchored lines differ from standard volume-weighted averages by resetting only at confirmed swing extremes, reducing noise in ranging markets while highlighting momentum shifts in trends.
  Motivation: Why this design? 
Traders often struggle with static reference lines that fail to adapt to changing market structures, leading to false breaks in volatile conditions or missed continuations in trends. By anchoring volume-weighted average price calculations to body pivot regimes—specifically at higher highs for resistance and lower lows for support—this design creates reference levels tied directly to price structure extremes. This approach addresses the problem of generic moving averages lagging behind swing confirmations, offering a more context-aware tool for intraday or swing trading.
  What’s different vs. standard approaches? 
- Baseline reference: Traditional volume-weighted average price indicators compute a running total from session start or fixed periods, often ignoring price structure.
- Architecture differences:
  - Regime detection via body breakout logic switches between high and low focus dynamically.
  - Anchoring limited to confirmed higher highs and lower lows, with historical recalculation for accurate line drawing.
  - Polyline rendering rebuilds only on the last bar to manage performance.
- Practical effect: Charts show fewer, more meaningful lines that start at swing points, making it easier to spot confluences with structure breaks rather than cluttered overlays from continuous calculations.
  How it works (technical) 
The indicator first calculates the maximum and minimum of each candle's open and close to define body highs and lows. It then scans a lookback window for the highest body high and lowest body low. A top regime triggers when the body high from the lookback period exceeds the window's highest, and a bottom regime when the body low falls below the window's lowest. These regime shifts confirm pivots only when crossing from one state to the other.
For top pivots, it compares the new body high against the previous swing high: if greater, it marks a higher high and anchors a new line; otherwise, a lower high. The same logic applies inversely for bottom pivots. Anchored lines use cumulative price-volume products and volumes from the anchor bar onward, subtracting prior cumulatives to isolate the segment. On pivot confirmation, it loops backward from the current bar to the anchor, computing and storing points for the line. New points append as bars advance, ensuring the line reflects ongoing volume weighting.
Initialization uses persistent variables to track the last swing values and anchor bars, starting with neutral states. Data flows from regime detection to pivot classification, then to anchoring and point accumulation, with lines rendered globally on the final bar.
  Parameter Guide 
Pivot Length — Controls the lookback window for detecting body breakouts, influencing pivot frequency and sensitivity to recent action. Shorter values catch more pivots in choppy conditions; longer smooths for major swings. Default: 30 (bars). Trade-offs/Tips: Min 1; for intraday, try 10–20 to reduce lag but watch for noise; on daily, 50+ for stability.
Show Pivot Labels — Toggles display of text markers at swing points, aiding quick identification of higher highs, lower highs, lower lows, or higher lows. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to declutter; useful for backtesting structure.
HH Color — Sets the line and label color for higher high anchored lines, distinguishing resistance levels. Default: Red (solid). Trade-offs/Tips: Choose contrasting hues for dark/light themes; pair with opacity for fills if added later.
LL Color — Sets the line and label color for lower low anchored lines, distinguishing support levels. Default: Lime (solid). Trade-offs/Tips: As above; green shades work well for bullish contexts without overpowering candles.
  Reading & Interpretation 
Higher high labels and red lines indicate potential resistance zones where volume weighting begins at a new swing top, suggesting sellers may defend prior highs. Lower low labels and lime lines mark support from a fresh swing bottom, with the line's slope reflecting buyer commitment via volume. Lower highs or higher lows appear as labels without new anchors, signaling possible range-bound action. Line proximity to price shows overextension; crosses may hint at regime shifts, but confirm with volume spikes.
  Practical Workflows & Combinations 
- Trend following: Enter longs above a rising lower low anchored line after higher low confirmation; filter with rising higher highs for uptrends. Use line breaks as trailing stops.
- Exits/Stops: In downtrends, exit shorts below a higher high line; set aggressive stops above it for scalps, conservative below for swings. Pair with momentum oscillators for divergence.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; on crypto 15M, shorten length to 15. Scale colors for dark themes; combine with higher timeframe anchors for confluence.
  Behavior, Constraints & Performance 
Closed-bar logic ensures pivots confirm after the lookback period, with no repainting on historical bars—live bars may adjust until regime shift. No higher timeframe calls, so minimal repaint risk beyond standard delays. Resources include a 2000-bar history limit, label/polyline caps at 200/50, and loops for historical point filling (up to current bar count from anchor, typically under 500 iterations). Known limits: In extreme gaps or low-volume periods, anchors may skew; lines absent until first pivots.
  Sensible Defaults & Quick Tuning 
Start with the 30-bar length for balanced pivot detection across most assets. For too-frequent pivots in ranges, increase to 50 for fewer signals. If lines lag in trends, reduce to 20 and enable labels for visual cues. In low-volatility assets, widen color contrasts; test on 100-bar history to verify stability.
  What this indicator is—and isn’t 
This is a structure-aware visualization layer for anchoring volume-weighted references at swing extremes, enhancing manual analysis of regimes and levels. It is not a standalone signal generator or predictive model—always integrate with broader context like order flow or news. Use alongside risk management and position sizing, not as isolated buy/sell triggers.
Many thanks to LuxAlgo for the original script "McDonald's Pattern  ". The implementation for body pivots instead of wicks uses a = max(open, close), b = min(open, close) and then highest(a, length) / lowest(b, length). This filters noise from the wicks and detects breakouts over/under bodies. Unusual and targeted, super innovative.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino
Keltner Channel Enhanced [DCAUT]█ Keltner Channel Enhanced  
 📊 ORIGINALITY & INNOVATION 
The Keltner Channel Enhanced represents an important advancement over standard Keltner Channel implementations by introducing dual flexibility in moving average selection for both the middle band and ATR calculation. While traditional Keltner Channels typically use EMA for the middle band and RMA (Wilder's smoothing) for ATR, this enhanced version provides access to 25+ moving average algorithms for both components, enabling traders to fine-tune the indicator's behavior to match specific market characteristics and trading approaches.
 Key Advancements: 
 
 Dual MA Algorithm Flexibility: Independent selection of moving average types for middle band (25+ options) and ATR smoothing (25+ options), allowing optimization of both trend identification and volatility measurement separately
 Enhanced Trend Sensitivity: Ability to use faster algorithms (HMA, T3) for middle band while maintaining stable volatility measurement with traditional ATR smoothing, or vice versa for different trading strategies
 Adaptive Volatility Measurement: Choice of ATR smoothing algorithm affects channel responsiveness to volatility changes, from highly reactive (SMA, EMA) to smoothly adaptive (RMA, TEMA)
 Comprehensive Alert System: Five distinct alert conditions covering breakouts, trend changes, and volatility expansion, enabling automated monitoring without constant chart observation
 Multi-Timeframe Compatibility: Works effectively across all timeframes from intraday scalping to long-term position trading, with independent optimization of trend and volatility components
 
This implementation addresses key limitations of standard Keltner Channels: fixed EMA/RMA combination may not suit all market conditions or trading styles. By decoupling the trend component from volatility measurement and allowing independent algorithm selection, traders can create highly customized configurations for specific instruments and market phases.
 📐 MATHEMATICAL FOUNDATION 
Keltner Channel Enhanced uses a three-component calculation system that combines a flexible moving average middle band with ATR-based (Average True Range) upper and lower channels, creating volatility-adjusted trend-following bands.
 Core Calculation Process: 
 1. Middle Band (Basis) Calculation: 
The basis line is calculated using the selected moving average algorithm applied to the price source over the specified period:
 
basis = ma(source, length, maType)
 
Supported algorithms include EMA (standard choice, trend-biased), SMA (balanced and symmetric), HMA (reduced lag), WMA, VWMA, TEMA, T3, KAMA, and 17+ others.
 2. Average True Range (ATR) Calculation: 
ATR measures market volatility by calculating the average of true ranges over the specified period:
 
trueRange = max(high - low, abs(high - close ), abs(low - close ))
atrValue = ma(trueRange, atrLength, atrMaType)
 
ATR smoothing algorithm significantly affects channel behavior, with options including RMA (standard, very smooth), SMA (moderate smoothness), EMA (fast adaptation), TEMA (smooth yet responsive), and others.
 3. Channel Calculation: 
Upper and lower channels are positioned at specified multiples of ATR from the basis:
 
upperChannel = basis + (multiplier × atrValue)
lowerChannel = basis - (multiplier × atrValue)
 
Standard multiplier is 2.0, providing channels that dynamically adjust width based on market volatility.
 Keltner Channel vs. Bollinger Bands - Key Differences: 
While both indicators create volatility-based channels, they use fundamentally different volatility measures:
 Keltner Channel (ATR-based): 
 
 Uses Average True Range to measure actual price movement volatility
 Incorporates gaps and limit moves through true range calculation
 More stable in trending markets, less prone to extreme compression
 Better reflects intraday volatility and trading range
 Typically fewer band touches, making touches more significant
 More suitable for trend-following strategies
 
 Bollinger Bands (Standard Deviation-based): 
 
 Uses statistical standard deviation to measure price dispersion
 Based on closing prices only, doesn't account for intraday range
 Can compress significantly during consolidation (squeeze patterns)
 More touches in ranging markets
 Better suited for mean-reversion strategies
 Provides statistical probability framework (95% within 2 standard deviations)
 
 Algorithm Combination Effects: 
The interaction between middle band MA type and ATR MA type creates different indicator characteristics:
 
 Trend-Focused Configuration (Fast MA + Slow ATR): Middle band uses HMA/EMA/T3, ATR uses RMA/TEMA, quick trend changes with stable channel width, suitable for trend-following
 Volatility-Focused Configuration (Slow MA + Fast ATR): Middle band uses SMA/WMA, ATR uses EMA/SMA, stable trend with dynamic channel width, suitable for volatility trading
 Balanced Configuration (Standard EMA/RMA): Classic Keltner Channel behavior, time-tested combination, suitable for general-purpose trend following
 Adaptive Configuration (KAMA + KAMA): Self-adjusting indicator responding to efficiency ratio, suitable for markets with varying trend strength and volatility regimes
 
 📊 COMPREHENSIVE SIGNAL ANALYSIS 
Keltner Channel Enhanced provides multiple signal categories optimized for trend-following and breakout strategies.
 Channel Position Signals: 
 Upper Channel Interaction: 
 
 Price Touching Upper Channel: Strong bullish momentum, price moving more than typical volatility range suggests, potential continuation signal in established uptrends
 Price Breaking Above Upper Channel: Exceptional strength, price exceeding normal volatility expectations, consider adding to long positions or tightening trailing stops
 Price Riding Upper Channel: Sustained strong uptrend, characteristic of powerful bull moves, stay with trend and avoid premature profit-taking
 Price Rejection at Upper Channel: Momentum exhaustion signal, consider profit-taking on longs or waiting for pullback to middle band for reentry
 
 Lower Channel Interaction: 
 
 Price Touching Lower Channel: Strong bearish momentum, price moving more than typical volatility range suggests, potential continuation signal in established downtrends
 Price Breaking Below Lower Channel: Exceptional weakness, price exceeding normal volatility expectations, consider adding to short positions or protecting against further downside
 Price Riding Lower Channel: Sustained strong downtrend, characteristic of powerful bear moves, stay with trend and avoid premature covering
 Price Rejection at Lower Channel: Momentum exhaustion signal, consider covering shorts or waiting for bounce to middle band for reentry
 
 Middle Band (Basis) Signals: 
 Trend Direction Confirmation: 
 
 Price Above Basis: Bullish trend bias, middle band acts as dynamic support in uptrends, consider long positions or holding existing longs
 Price Below Basis: Bearish trend bias, middle band acts as dynamic resistance in downtrends, consider short positions or avoiding longs
 Price Crossing Above Basis: Potential trend change from bearish to bullish, early signal to establish long positions
 Price Crossing Below Basis: Potential trend change from bullish to bearish, early signal to establish short positions or exit longs
 
 Pullback Trading Strategy: 
 
 Uptrend Pullback: Price pulls back from upper channel to middle band, finds support, and resumes upward, ideal long entry point
 Downtrend Bounce: Price bounces from lower channel to middle band, meets resistance, and resumes downward, ideal short entry point
 Basis Test: Strong trends often show price respecting the middle band as support/resistance on pullbacks
 Failed Test: Price breaking through middle band against trend direction signals potential reversal
 
 Volatility-Based Signals: 
 Narrow Channels (Low Volatility): 
 
 Consolidation Phase: Channels contract during periods of reduced volatility and directionless price action
 Breakout Preparation: Narrow channels often precede significant directional moves as volatility cycles
 Trading Approach: Reduce position sizes, wait for breakout confirmation, avoid range-bound strategies within channels
 Breakout Direction: Monitor for price breaking decisively outside channel range with expanding width
 
 Wide Channels (High Volatility): 
 
 Trending Phase: Channels expand during strong directional moves and increased volatility
 Momentum Confirmation: Wide channels confirm genuine trend with substantial volatility backing
 Trading Approach: Trend-following strategies excel, wider stops necessary, mean-reversion strategies risky
 Exhaustion Signs: Extreme channel width (historical highs) may signal approaching consolidation or reversal
 
 Advanced Pattern Recognition: 
 Channel Walking Pattern: 
 
 Upper Channel Walk: Price consistently touches or exceeds upper channel while staying above basis, very strong uptrend signal, hold longs aggressively
 Lower Channel Walk: Price consistently touches or exceeds lower channel while staying below basis, very strong downtrend signal, hold shorts aggressively
 Basis Support/Resistance: During channel walks, price typically uses middle band as support/resistance on minor pullbacks
 Pattern Break: Price crossing basis during channel walk signals potential trend exhaustion
 
 Squeeze and Release Pattern: 
 
 Squeeze Phase: Channels narrow significantly, price consolidates near middle band, volatility contracts
 Direction Clues: Watch for price positioning relative to basis during squeeze (above = bullish bias, below = bearish bias)
 Release Trigger: Price breaking outside narrow channel range with expanding width confirms breakout
 Follow-Through: Measure squeeze height and project from breakout point for initial profit targets
 
 Channel Expansion Pattern: 
 
 Breakout Confirmation: Rapid channel widening confirms volatility increase and genuine trend establishment
 Entry Timing: Enter positions early in expansion phase before trend becomes overextended
 Risk Management: Use channel width to size stops appropriately, wider channels require wider stops
 
 Basis Bounce Pattern: 
 
 Clean Bounce: Price touches middle band and immediately reverses, confirms trend strength and entry opportunity
 Multiple Bounces: Repeated basis bounces indicate strong, sustainable trend
 Bounce Failure: Price penetrating basis signals weakening trend and potential reversal
 
 Divergence Analysis: 
 
 Price/Channel Divergence: Price makes new high/low while staying within channel (not reaching outer band), suggests momentum weakening
 Width/Price Divergence: Price breaks to new extremes but channel width contracts, suggests move lacks conviction
 Reversal Signal: Divergences often precede trend reversals or significant consolidation periods
 
 Multi-Timeframe Analysis: 
Keltner Channels work particularly well in multi-timeframe trend-following approaches:
 Three-Timeframe Alignment: 
 
 Higher Timeframe (Weekly/Daily): Identify major trend direction, note price position relative to basis and channels
 Intermediate Timeframe (Daily/4H): Identify pullback opportunities within higher timeframe trend
 Lower Timeframe (4H/1H): Time precise entries when price touches middle band or lower channel (in uptrends) with rejection
 
 Optimal Entry Conditions: 
 
 Best Long Entries: Higher timeframe in uptrend (price above basis), intermediate timeframe pulls back to basis, lower timeframe shows rejection at middle band or lower channel
 Best Short Entries: Higher timeframe in downtrend (price below basis), intermediate timeframe bounces to basis, lower timeframe shows rejection at middle band or upper channel
 Risk Management: Use higher timeframe channel width to set position sizing, stops below/above higher timeframe channels
 
 🎯 STRATEGIC APPLICATIONS 
Keltner Channel Enhanced excels in trend-following and breakout strategies across different market conditions.
 Trend Following Strategy: 
 Setup Requirements: 
 
 Identify established trend with price consistently on one side of basis line
 Wait for pullback to middle band (basis) or brief penetration through it
 Confirm trend resumption with price rejection at basis and move back toward outer channel
 Enter in trend direction with stop beyond basis line
 
 Entry Rules: 
 Uptrend Entry: 
 
 Price pulls back from upper channel to middle band, shows support at basis (bullish candlestick, momentum divergence)
 Enter long on rejection/bounce from basis with stop 1-2 ATR below basis
 Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
 
 Downtrend Entry: 
 
 Price bounces from lower channel to middle band, shows resistance at basis (bearish candlestick, momentum divergence)
 Enter short on rejection/reversal from basis with stop 1-2 ATR above basis
 Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
 
 Trend Management: 
 
 Trailing Stop: Use basis line as dynamic trailing stop, exit if price closes beyond basis against position
 Profit Taking: Take partial profits at opposite channel, move stops to basis
 Position Additions: Add to winners on subsequent basis bounces if trend intact
 
 Breakout Strategy: 
 Setup Requirements: 
 
 Identify consolidation period with contracting channel width
 Monitor price action near middle band with reduced volatility
 Wait for decisive breakout beyond channel range with expanding width
 Enter in breakout direction after confirmation
 
 Breakout Confirmation: 
 
 Price breaks clearly outside channel (upper for longs, lower for shorts), channel width begins expanding from contracted state
 Volume increases significantly on breakout (if using volume analysis)
 Price sustains outside channel for multiple bars without immediate reversal
 
 Entry Approaches: 
 
 Aggressive: Enter on initial break with stop at opposite channel or basis, use smaller position size
 Conservative: Wait for pullback to broken channel level, enter on rejection and resumption, tighter stop
 
 Volatility-Based Position Sizing: 
Adjust position sizing based on channel width (ATR-based volatility):
 
 Wide Channels (High ATR): Reduce position size as stops must be wider, calculate position size using ATR-based risk calculation: Risk / (Stop Distance in ATR × ATR Value)
 Narrow Channels (Low ATR): Increase position size as stops can be tighter, be cautious of impending volatility expansion
 ATR-Based Risk Management: Use ATR-based risk calculations, position size = 0.01 × Capital / (2 × ATR), use multiples of ATR (1-2 ATR) for adaptive stops
 
 Algorithm Selection Guidelines: 
Different market conditions benefit from different algorithm combinations:
 
 Strong Trending Markets: Middle band use EMA or HMA, ATR use RMA, capture trends quickly while maintaining stable channel width
 Choppy/Ranging Markets: Middle band use SMA or WMA, ATR use SMA or WMA, avoid false trend signals while identifying genuine reversals
 Volatile Markets: Middle band and ATR both use KAMA or FRAMA, self-adjusting to changing market conditions reduces manual optimization
 Breakout Trading: Middle band use SMA, ATR use EMA or SMA, stable trend with dynamic channels highlights volatility expansion early
 Scalping/Day Trading: Middle band use HMA or T3, ATR use EMA or TEMA, both components respond quickly
 Position Trading: Middle band use EMA/TEMA/T3, ATR use RMA or TEMA, filter out noise for long-term trend-following
 
 📋 DETAILED PARAMETER CONFIGURATION 
Understanding and optimizing parameters is essential for adapting Keltner Channel Enhanced to specific trading approaches.
 Source Parameter: 
 
 Close (Most Common): Uses closing price, reflects daily settlement, best for end-of-day analysis and position trading, standard choice
 HL2 (Median Price): Smooths out closing bias, better represents full daily range in volatile markets, good for swing trading
 HLC3 (Typical Price): Gives more weight to close while including full range, popular for intraday applications, slightly more responsive than HL2
 OHLC4 (Average Price): Most comprehensive price representation, smoothest option, good for gap-prone markets or highly volatile instruments
 
 Length Parameter: 
Controls the lookback period for middle band (basis) calculation:
 
 Short Periods (10-15): Very responsive to price changes, suitable for day trading and scalping, higher false signal rate
 Standard Period (20 - Default): Represents approximately one month of trading, good balance between responsiveness and stability, suitable for swing and position trading
 Medium Periods (30-50): Smoother trend identification, fewer false signals, better for position trading and longer holding periods
 Long Periods (50+): Very smooth, identifies major trends only, minimal false signals but significant lag, suitable for long-term investment
 
 Optimization by Timeframe:  1-15 minute charts use 10-20 period, 30-60 minute charts use 20-30 period, 4-hour to daily charts use 20-40 period, weekly charts use 20-30 weeks.
 ATR Length Parameter: 
Controls the lookback period for Average True Range calculation, affecting channel width:
 
 Short ATR Periods (5-10): Very responsive to recent volatility changes, standard is 10 (Keltner's original specification), may be too reactive in whipsaw conditions
 Standard ATR Period (10 - Default): Chester Keltner's original specification, good balance between responsiveness and stability, most widely used
 Medium ATR Periods (14-20): Smoother channel width, ATR 14 aligns with Wilder's original ATR specification, good for position trading
 Long ATR Periods (20+): Very smooth channel width, suitable for long-term trend-following
 
 Length vs. ATR Length Relationship:  Equal values (20/20) provide balanced responsiveness, longer ATR (20/14) gives more stable channel width, shorter ATR (20/10) is standard configuration, much shorter ATR (20/5) creates very dynamic channels.
 Multiplier Parameter: 
Controls channel width by setting ATR multiples:
 
 Lower Values (1.0-1.5): Tighter channels with frequent price touches, more trading signals, higher false signal rate, better for range-bound and mean-reversion strategies
 Standard Value (2.0 - Default): Chester Keltner's recommended setting, good balance between signal frequency and reliability, suitable for both trending and ranging strategies
 Higher Values (2.5-3.0): Wider channels with less frequent touches, fewer but potentially higher-quality signals, better for strong trending markets
 
 Market-Specific Optimization:  High volatility markets (crypto, small-caps) use 2.5-3.0 multiplier, medium volatility markets (major forex, large-caps) use 2.0 multiplier, low volatility markets (bonds, utilities) use 1.5-2.0 multiplier.
 MA Type Parameter (Middle Band): 
Critical selection that determines trend identification characteristics:
 
 EMA (Exponential Moving Average - Default): Standard Keltner Channel choice, Chester Keltner's original specification, emphasizes recent prices, faster response to trend changes, suitable for all timeframes
 SMA (Simple Moving Average): Equal weighting of all data points, no directional bias, slower than EMA, better for ranging markets and mean-reversion
 HMA (Hull Moving Average): Minimal lag with smooth output, excellent for fast trend identification, best for day trading and scalping
 TEMA (Triple Exponential Moving Average): Advanced smoothing with reduced lag, responsive to trends while filtering noise, suitable for volatile markets
 T3 (Tillson T3): Very smooth with minimal lag, excellent for established trend identification, suitable for position trading
 KAMA (Kaufman Adaptive Moving Average): Automatically adjusts speed based on market efficiency, slow in ranging markets, fast in trends, suitable for markets with varying conditions
 
 ATR MA Type Parameter: 
Determines how Average True Range is smoothed, affecting channel width stability:
 
 RMA (Wilder's Smoothing - Default): J. Welles Wilder's original ATR smoothing method, very smooth, slow to adapt to volatility changes, provides stable channel width
 SMA (Simple Moving Average): Equal weighting, moderate smoothness, faster response to volatility changes than RMA, more dynamic channel width
 EMA (Exponential Moving Average): Emphasizes recent volatility, quick adaptation to new volatility regimes, very responsive channel width changes
 TEMA (Triple Exponential Moving Average): Smooth yet responsive, good balance for varying volatility, suitable for most trading styles
 
 Parameter Combination Strategies: 
 
 Conservative Trend-Following: Length 30/ATR Length 20/Multiplier 2.5, MA Type EMA or TEMA/ATR MA Type RMA, smooth trend with stable wide channels, suitable for position trading
 Standard Balanced Approach: Length 20/ATR Length 10/Multiplier 2.0, MA Type EMA/ATR MA Type RMA, classic Keltner Channel configuration, suitable for general purpose swing trading
 Aggressive Day Trading: Length 10-15/ATR Length 5-7/Multiplier 1.5-2.0, MA Type HMA or EMA/ATR MA Type EMA or SMA, fast trend with dynamic channels, suitable for scalping and day trading
 Breakout Specialist: Length 20-30/ATR Length 5-10/Multiplier 2.0, MA Type SMA or WMA/ATR MA Type EMA or SMA, stable trend with responsive channel width
 Adaptive All-Conditions: Length 20/ATR Length 10/Multiplier 2.0, MA Type KAMA or FRAMA/ATR MA Type KAMA or TEMA, self-adjusting to market conditions
 
 Offset Parameter: 
Controls horizontal positioning of channels on chart. Positive values shift channels to the right (future) for visual projection, negative values shift left (past) for historical analysis, zero (default) aligns with current price bars for real-time signal analysis. Offset affects only visual display, not alert conditions or actual calculations.
 📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES 
Keltner Channel Enhanced provides improvements over standard implementations while maintaining proven effectiveness.
 Response Characteristics: 
 
 Standard EMA/RMA Configuration: Moderate trend lag (approximately 0.4 × length periods), smooth and stable channel width from RMA smoothing, good balance for most market conditions
 Fast HMA/EMA Configuration: Approximately 60% reduction in trend lag compared to EMA, responsive channel width from EMA ATR smoothing, suitable for quick trend changes and breakouts
 Adaptive KAMA/KAMA Configuration: Variable lag based on market efficiency, automatic adjustment to trending vs. ranging conditions, self-optimizing behavior reduces manual intervention
 
 Comparison with Traditional Keltner Channels: 
 Enhanced Version Advantages: 
 
 Dual Algorithm Flexibility: Independent MA selection for trend and volatility vs. fixed EMA/RMA, separate tuning of trend responsiveness and channel stability
 Market Adaptation: Choose configurations optimized for specific instruments and conditions, customize for scalping, swing, or position trading preferences
 Comprehensive Alerts: Enhanced alert system including channel expansion detection
 
 Traditional Version Advantages: 
 
 Simplicity: Fewer parameters, easier to understand and implement
 Standardization: Fixed EMA/RMA combination ensures consistency across users
 Research Base: Decades of backtesting and research on standard configuration
 
 When to Use Enhanced Version:  Trading multiple instruments with different characteristics, switching between trending and ranging markets, employing different strategies, algorithm-based trading systems requiring customization, seeking optimization for specific trading style and timeframe.
 When to Use Standard Version:  Beginning traders learning Keltner Channel concepts, following published research or trading systems, preferring simplicity and standardization, wanting to avoid optimization and curve-fitting risks.
 Performance Across Market Conditions: 
 
 Strong Trending Markets: EMA or HMA basis with RMA or TEMA ATR smoothing provides quicker trend identification, pullbacks to basis offer excellent entry opportunities
 Choppy/Ranging Markets: SMA or WMA basis with RMA ATR smoothing and lower multipliers, channel bounce strategies work well, avoid false breakouts
 Volatile Markets: KAMA or FRAMA with EMA or TEMA, adaptive algorithms excel by automatic adjustment, wider multipliers (2.5-3.0) accommodate large price swings
 Low Volatility/Consolidation: Channels narrow significantly indicating consolidation, algorithm choice less impactful, focus on detecting channel width contraction for breakout preparation
 
 Keltner Channel vs. Bollinger Bands - Usage Comparison: 
 Favor Keltner Channels When:  Trend-following is primary strategy, trading volatile instruments with gaps, want ATR-based volatility measurement, prefer fewer higher-quality channel touches, seeking stable channel width during trends.
 Favor Bollinger Bands When:  Mean-reversion is primary strategy, trading instruments with limited gaps, want statistical framework based on standard deviation, need squeeze patterns for breakout identification, prefer more frequent trading opportunities.
 Use Both Together:  Bollinger Band squeeze + Keltner Channel breakout is powerful combination, price outside Bollinger Bands but inside Keltner Channels indicates moderate signal, price outside both indicates very strong signal, Bollinger Bands for entries and Keltner Channels for trend confirmation.
 Limitations and Considerations: 
 General Limitations: 
 
 Lagging Indicator: All moving averages lag price, even with reduced-lag algorithms
 Trend-Dependent: Works best in trending markets, less effective in choppy conditions
 No Direction Prediction: Indicates volatility and deviation, not future direction, requires confirmation
 
 Enhanced Version Specific Considerations: 
 
 Optimization Risk: More parameters increase risk of curve-fitting historical data
 Complexity: Additional choices may overwhelm beginning traders
 Backtesting Challenges: Different algorithms produce different historical results
 
 Mitigation Strategies: 
 
 Use Confirmation: Combine with momentum indicators (RSI, MACD), volume, or price action
 Test Parameter Robustness: Ensure parameters work across range of values, not just optimized ones
 Multi-Timeframe Analysis: Confirm signals across different timeframes
 Proper Risk Management: Use appropriate position sizing and stops
 Start Simple: Begin with standard EMA/RMA before exploring alternatives
 
 Optimal Usage Recommendations: 
 For Maximum Effectiveness: 
 
 Start with standard EMA/RMA configuration to understand classic behavior
 Experiment with alternatives on demo account or paper trading
 Match algorithm combination to market condition and trading style
 Use channel width analysis to identify market phases
 Combine with complementary indicators for confirmation
 Implement strict risk management using ATR-based position sizing
 Focus on high-quality setups rather than trading every signal
 Respect the trend: trade with basis direction for higher probability
 
 Complementary Indicators: 
 
 RSI or Stochastic: Confirm momentum at channel extremes
 MACD: Confirm trend direction and momentum shifts
 Volume: Validate breakouts and trend strength
 ADX: Measure trend strength, avoid Keltner signals in weak trends
 Support/Resistance: Combine with traditional levels for high-probability setups
 Bollinger Bands: Use together for enhanced breakout and volatility analysis
 
 USAGE NOTES 
This indicator is designed for technical analysis and educational purposes. Keltner Channel Enhanced has limitations and should not be used as the sole basis for trading decisions. While the flexible moving average selection for both trend and volatility components provides valuable adaptability across different market conditions, algorithm performance varies with market conditions, and past characteristics do not guarantee future results.
Key considerations:
 
 Always use multiple forms of analysis and confirmation before entering trades
 Backtest any parameter combination thoroughly before live trading
 Be aware that optimization can lead to curve-fitting if not done carefully
 Start with standard EMA/RMA settings and adjust only when specific conditions warrant
 Understand that no moving average algorithm can eliminate lag entirely
 Consider market regime (trending, ranging, volatile) when selecting parameters
 Use ATR-based position sizing and risk management on every trade
 Keltner Channels work best in trending markets, less effective in choppy conditions
 Respect the trend direction indicated by price position relative to basis line
 
The enhanced flexibility of dual algorithm selection provides powerful tools for adaptation but requires responsible use, thorough understanding of how different algorithms behave under various market conditions, and disciplined risk management.
Opening Range IndicatorComplete Trading Guide: Opening Range Breakout Strategy
What Are Opening Ranges?
Opening ranges capture the high and low prices during the first few minutes of market open. These levels often act as key support and resistance throughout the trading day because:
Heavy volume occurs at market open as overnight orders execute
Institutional activity is concentrated during opening minutes
Price discovery happens as market participants react to overnight news
Psychological levels are established that traders watch all day
Understanding the Three Timeframes
OR5 (5-Minute Range: 9:30-9:35 AM)
Most sensitive - captures immediate market reaction
Quick signals but higher false breakout rate
Best for scalping and momentum trading
Use for early entry when conviction is high
OR15 (15-Minute Range: 9:30-9:45 AM)
Balanced approach - most popular among day traders
Moderate sensitivity with better reliability
Good for swing trades lasting several hours
Primary timeframe for most strategies
OR30 (30-Minute Range: 9:30-10:00 AM)
Most reliable but slower signals
Lower false breakout rate
Best for position trades and trend following
Use when looking for major moves
Core Trading Strategies
Strategy 1: Basic Breakout
Setup:
Wait for price to break above OR15 high or below OR15 low
Enter on the breakout candle close
Stop loss: Opposite side of the range
Target: 2-3x the range size
Example:
OR15 range: $100.00 - $102.00 (Range = $2.00)
Long entry: Break above $102.00
Stop loss: $99.50 (below OR15 low)
Target: $104.00+ (2x range size)
Strategy 2: Multiple Confirmation
Setup:
Wait for OR5 break first (early signal)
Confirm with OR15 break in same direction
Enter on OR15 confirmation
Stop: Below OR30 if available, or OR15 opposite level
Why it works:
Multiple timeframe confirmation reduces false signals and increases probability of sustained moves.
Strategy 3: Failed Breakout Reversal
Setup:
Price breaks OR15 level but fails to hold
Wait for re-entry into the range
Enter reversal trade toward opposite OR level
Stop: Recent breakout high/low
Target: Opposite side of range + extension
Key insight: Failed breakouts often lead to strong moves in the opposite direction.
Advanced Techniques
Range Quality Assessment
High-Quality Ranges (Trade these):
Range size: 0.5% - 2% of stock price
Clean boundaries (not choppy)
Volume spike during range formation
Clear rejection at range levels
Low-Quality Ranges (Avoid these):
Very narrow ranges (<0.3% of stock price)
Extremely wide ranges (>3% of stock price)
Choppy, overlapping candles
Low volume during formation
Volume Confirmation
For Breakouts:
Look for volume spike (2x+ average) on breakout
Declining volume often signals false breakout
Rising volume during range formation shows interest
Market Context Filters
Best Conditions:
Trending market days (SPY/QQQ with clear direction)
Earnings reactions or news-driven moves
High-volume stocks with good liquidity
Volatility above average (VIX considerations)
Avoid Trading When:
Extremely low volume days
Major economic announcements pending
Holidays or half-days
Choppy, sideways market conditions
Risk Management Rules
Position Sizing
Conservative: Risk 0.5% of account per trade
Moderate: Risk 1% of account per trade
Aggressive: Risk 2% maximum per trade
Stop Loss Placement
Inside the range: Quick exit but higher stop-out rate
Outside opposite level: More room but larger risk
ATR-based: 1.5-2x Average True Range below entry
Profit Taking
Target 1: 1x range size (take 50% off)
Target 2: 2x range size (take 25% off)
Runner: Trail remaining 25% with moving stops
Specific Entry Techniques
Breakout Entry Methods
Method 1: Immediate Entry
Enter as soon as price closes above/below range
Fastest entry but highest false signal rate
Best for strong momentum situations
Method 2: Pullback Entry
Wait for breakout, then pullback to range level
Enter when price bounces off former resistance/support
Better risk/reward but may miss some moves
Method 3: Volume Confirmation
Wait for breakout + volume spike
Enter after volume confirmation candle
Reduces false signals significantly
Multiple Timeframe Entries
Aggressive: OR5 break → immediate entry
Conservative: OR5 + OR15 + OR30 all align → enter
Balanced: OR15 break with OR30 support → enter
Common Mistakes to Avoid
1. Trading Poor-Quality Ranges
❌ Don't trade ranges that are too narrow or too wide
✅ Focus on clean, well-defined ranges with good volume
2. Ignoring Volume
❌ Don't chase breakouts without volume confirmation
✅ Always check for volume spike on breakouts
3. Over-Trading
❌ Don't force trades when ranges are unclear
✅ Wait for high-probability setups only
4. Poor Risk Management
❌ Don't risk more than planned or use tight stops in volatile conditions
✅ Stick to predetermined risk levels
5. Fighting the Trend
❌ Don't fade breakouts in strongly trending markets
✅ Align trades with overall market direction
Daily Trading Routine
Pre-Market (8:00-9:30 AM)
Check overnight news and earnings
Review major indices (SPY, QQQ, IWM)
Identify potential opening range candidates
Set alerts for range breakouts
Market Open (9:30-10:00 AM)
Watch opening range formation
Note volume and price action quality
Mark key levels on charts
Prepare for breakout signals
Trading Session (10:00 AM - 4:00 PM)
Execute breakout strategies
Manage existing positions
Trail stops as profits develop
Look for additional setups
Post-Market Review
Analyze winning and losing trades
Review range quality vs. outcomes
Identify improvement areas
Prepare for next session
Best Stocks/ETFs for Opening Range Trading
Large Cap Stocks (Best for beginners):
AAPL, MSFT, GOOGL, AMZN, TSLA
High liquidity, predictable behavior
Good range formation most days
ETFs (Consistent patterns):
SPY, QQQ, IWM, XLF, XLE
Excellent liquidity
Clear range boundaries
Mid-Cap Growth (Advanced traders):
Stocks with good volume (1M+ shares daily)
Recent news catalysts
Clean technical patterns
Performance Optimization
Track These Metrics:
Win rate by range type (OR5 vs OR15 vs OR30)
Average R/R (risk vs reward ratio)
Best performing market conditions
Time of day performance
Continuous Improvement:
Keep detailed trade journal
Review failed breakouts for patterns
Adjust position sizing based on win rate
Refine entry timing based on backtesting
Final Tips for Success
Start small - Paper trade or use tiny positions initially
Focus on quality - Better to miss trades than take bad ones
Stay disciplined - Stick to your rules even during losing streaks
Adapt to conditions - What works in trending markets may fail in choppy conditions
Keep learning - Markets evolve, so should your approach
The opening range strategy is powerful because it captures natural market behavior, but like all strategies, it requires practice, discipline, and proper risk management to be profitable long-term.
Clarix Trailing MasterClarix Trailing Master 
Advanced Manual Entry Trailing Stop Strategy
 Purpose :
Clarix Trailing Master is designed to give traders precise control over trade exits with a customizable trailing stop system. It combines manual entry inputs with dynamic and static trailing stop options, empowering users to protect profits while minimizing premature stop-outs.
 How It Works:
 You manually input your trade entry price and specify the trade direction (Long or Short).
 The strategy activates the trailing stop only after the price moves favorably by a configurable profit threshold. This helps avoid early stop losses during initial market noise.
 You can choose between a dynamic trailing stop based on Average True Range (ATR) or a fixed static trailing distance. The ATR can also be computed on a higher timeframe for enhanced stability.
 Once active, the trailing stop updates live with price movements, ensuring your gains are locked in progressively.
 If the price crosses the trailing stop, a clear alert triggers, and the stop-hit status displays visually on the chart.
 
 Key Features:
 Manual entry with exact price and timestamp input for precise trade tracking.
 Supports both Long and Short trades.
 Choice between dynamic ATR-based trailing or static trailing stops.
 Configurable profit threshold before trailing stop activation to avoid early exits.
 Visual markers for entry and stop-hit points (yellow and red respectively).
 Live dashboard displaying entry details, trade status, trailing mode, and current stop level.
 Works on all asset classes and timeframes, adaptable to various trading styles.
 Built-in audio alert notifies you immediately when the trailing stop is hit.
 
 Usage Tips:
 Adjust the profit threshold and ATR settings based on your asset’s volatility and timeframe. For example, use higher ATR multipliers for more volatile markets like crypto.
 Consider using higher timeframe ATR values for smoother trailing stops in fast-moving markets.
 Ideal for swing trading or position trading where precise stop management is crucial.
 Always backtest and paper trade before applying to live markets.
Commodity Trend Reactor [BigBeluga]
 🔵 OVERVIEW 
 A dynamic trend-following oscillator built around the classic CCI, enhanced with intelligent price tracking and reversal signals. 
 Commodity Trend Reactor   extends the traditional Commodity Channel Index (CCI) by integrating trend-trailing logic and reactive reversal markers. It visualizes trend direction using a trailing stop system and highlights potential exhaustion zones when CCI exceeds extreme thresholds. This dual-level system makes it ideal for both trend confirmation and mean-reversion alerts.
 🔵 CONCEPTS 
 
  Based on the CCI (Commodity Channel Index) oscillator, which measures deviation from the average price.
  Trend bias is determined by whether CCI is above or below user-defined thresholds.
  Trailing price bands are used to lock in trend direction visually on the main chart.
  Extreme values beyond ±200 are treated as potential reversal zones.
 
 🔵 FEATURES\ 
 
   CCI-Based Trend Shifts: 
Triggers a bullish bias when CCI crosses above the upper threshold, and bearish when it crosses below the lower threshold.
   Adaptive Trailing Stops: 
In bullish mode, a trailing stop tracks the lowest price; in bearish mode, it tracks the highest.
  
   Top & Bottom Markers: 
When CCI surpasses +200 or drops below -200, it plots colored squares both on the oscillator and on price, marking potential reversal zones.
  
   Background Highlights: 
Each time a trend shift occurs, the background is softly colored (lime for bullish, orange for bearish) to highlight the change.
  
 
 🔵 HOW TO USE 
 
  Use the oscillator to monitor when CCI crosses above or below threshold values to detect trend activation.
  
  Enter trades in the direction of the trailing band once the trend bias is confirmed.
  Watch for +200 and -200 square markers as warnings of potential mean reversals.
  Use trailing stop areas as dynamic support/resistance to manage stop loss and exit strategies.
  The background color changes offer clean confirmation of trend transitions on chart.
 
 🔵 CONCLUSION 
 Commodity Trend Reactor   transforms the simple CCI into a complete trend-reactive framework. With real-time trailing logic and clear reversal alerts, it serves both momentum traders and contrarian scalpers alike. Whether you’re trading breakouts or anticipating mean reversions, this indicator provides clarity and structure to your decision-making.
nineLivesUtilLibLibrary   "nineLivesUtilLib" 
 isDateInRange(currentTime, useTimeFilter, startDate, endDate) 
  Checks if the current time is within the specified date range.
  Parameters:
     currentTime (int) : The current bar's time (time).
     useTimeFilter (bool) : Bool 📅: Enable the date range filter.
     startDate (int) : Timestamp 📅: The start date for the filter.
     endDate (int) : Timestamp 📅: The end date for the filter.
  Returns: True if the current time is within the range or filtering is disabled, false otherwise.
@example
inDateRange = nineLivesUtilLib.isDateInRange(time, useTimeFilter, startDate, endDate)
if inDateRange
// Execute trading logic
 checkVolumeCondition(currentVolume, useVolumeFilter, volumeThresholdMultiplier, volumeLength) 
  Checks if the current volume meets the threshold condition.
  Parameters:
     currentVolume (float) : The current bar's volume (volume).
     useVolumeFilter (bool) : Bool 📊: Enable the volume filter.
     volumeThresholdMultiplier (float) : Float 📊: Volume threshold relative to average (e.g., 1.5 for 1.5x average).
     volumeLength (int) : Int 📊: Lookback length for the volume average.
  Returns: True if the volume condition is met or filtering is disabled, false otherwise.
@example
volumeOk = nineLivesUtilLib.checkVolumeCondition(volume, useVolumeFilter, volumeThreshold, volumeLength)
if volumeOk
// Proceed with trading logic
 checkMultiTimeframeCondition(currentClose, currentOpen, htfClose, htfOpen, useMultiTimeframe, alignment) 
  Checks alignment with higher timeframe direction.
  Parameters:
     currentClose (float) : Float: The current bar's closing price (close).
     currentOpen (float) : Float: The current bar's opening price (open).
     htfClose (float) : Float: The closing price from the higher timeframe (must be fetched by the calling script using request.security).
     htfOpen (float) : Float: The opening price from the higher timeframe (must be fetched by the calling script using request.security).
     useMultiTimeframe (bool) : Bool ⏱️: Enable multi-timeframe analysis.
     alignment (string) : String ⏱️: Desired alignment ("same", "opposite", "any").
  Returns: True if the timeframe alignment condition is met or analysis is disabled, false otherwise.
@example
// In the calling script:
  = request.security(syminfo.tickerid, higherTimeframe,  )
tfOk = nineLivesUtilLib.checkMultiTimeframeCondition(close, open, htfClose, htfOpen, useMultiTimeframe, tfAlignment)
if tfOk
// Proceed with trading logic
 checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode) 
  Detects the market regime (trending or ranging) and checks if trading is allowed.
  Parameters:
     useMarketRegime (bool) : Bool 🔍: Enable market regime detection.
     regimeIndicator (string) : String 🔍: Indicator to use ("ADX" or "Volatility").
     regimeThreshold (int) : Int 🔍: Threshold for trend strength/volatility.
     regimeLength (simple int) : Int 🔍: Lookback length for the indicator.
     regimeMode (string) : String 🔍: Trading mode based on regime ("trend_only", "range_only", "adaptive").
  Returns: A tuple containing:
 : conditionMet (bool) - True if trading is allowed based on the regime mode and detection, false otherwise.
 : inTrendingRegime (bool) - True if the current regime is trending based on the indicator and threshold.
@example
  = nineLivesUtilLib.checkMarketRegime(useMarketRegime, regimeIndicator, regimeThreshold, regimeLength, regimeMode)
if regimeOk
// Proceed with trading logic
 applyCooldown(buySignal, sellSignal, cooldownBars) 
  Applies a cooldown period after a signal.
  Parameters:
     buySignal (bool) : Bool: Buy signal (potentially after primary entry logic).
     sellSignal (bool) : Bool: Sell signal (potentially after primary entry logic).
     cooldownBars (int) : Int ⏳: The number of bars to wait after a signal before allowing another.
  Returns: A tuple containing:
 : cooldownFilteredBuy (bool) - Buy signal after cooldown filter.
 : cooldownFilteredSell (bool) - Sell signal after cooldown filter.
@example
  = nineLivesUtilLib.applyCooldown(rawBuySignal, rawSellSignal, iCool)
 applyAllFilters(rawBuy, rawSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, drawdownOk, cooldownOkBuy, cooldownOkSell) 
  Applies all filtering conditions to the buy and sell signals.
  Parameters:
     rawBuy (bool) : Bool: The initial buy signal candidate (from primary entry logic, e.g., after cooldown).
     rawSell (bool) : Bool: The initial sell signal candidate (from primary entry logic, e.g., after cooldown).
     inDateRange (bool) : Bool 📅: Result from isDateInRange.
     tradeDirection (string) : String 🔄: Overall trade direction preference ("longs_only", "shorts_only", "both").
     volumeOk (bool) : Bool 📊: Result from checkVolumeCondition.
     tfOk (bool) : Bool ⏱️: Result from checkMultiTimeframeCondition.
     regimeOk (bool) : Bool 🔍: Result from checkMarketRegime.
     drawdownOk (bool) : Bool 📉: Result from checkDrawdownExceeded (or equivalent).
     cooldownOkBuy (bool) : Bool ⏳: Result from applyCooldown for buy.
     cooldownOkSell (bool) : Bool ⏳: Result from applyCooldown for sell.
  Returns: A tuple containing:
 : finalBuySignal (bool) - The final buy signal after all filters.
 : finalSellSignal (bool) - The final sell signal after all filters.
@example
  = nineLivesUtilLib.applyAllFilters(cooldownBuy, cooldownSell, inDateRange, tradeDirection, volumeOk, tfOk, regimeOk, !drawdownExceeded, cooldownBuy, cooldownSell)
NOTE: This function filters signals generated by your primary entry logic (e.g., EMA crossover).
 checkDrawdownExceeded(currentEquity, useMaxDrawdown, maxDrawdownPercent) 
  Tracks maximum equity and checks if current drawdown exceeds a threshold.
  Parameters:
     currentEquity (float) : Float: The strategy's current equity (strategy.equity).
     useMaxDrawdown (bool) : Bool 📉: Enable max drawdown protection.
     maxDrawdownPercent (float) : Float 📉: The maximum allowed drawdown as a percentage.
  Returns: True if drawdown protection is enabled and the current drawdown exceeds the threshold, false otherwise.
@example
drawdownExceeded = nineLivesUtilLib.checkDrawdownExceeded(strategy.equity, useMaxDrawdown, maxDrawdownPercent)
if drawdownExceeded
// Consider stopping entries or exiting positions in the strategy script
 calculateExitPrice(positionAvgPrice, percentage, isStop, isLong) 
  Calculates a stop loss or take profit price based on a percentage from the average entry price.
  Parameters:
     positionAvgPrice (float) : Float: The average price of the current position (strategy.position_avg_price).
     percentage (float) : Float: The stop loss or take profit percentage (e.g., 2.0 for 2%).
     isStop (bool) : Bool: True if calculating a stop loss price, false if calculating a take profit price.
     isLong (bool) : Bool: True if the position is long, false if short.
  Returns: The calculated stop price or take profit price, or na if no position or percentage is invalid.
@example
longSL = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, stopLossPercent, true, true)
shortTP = nineLivesUtilLib.calculateExitPrice(strategy.position_avg_price, takeProfitPercent, false, false)
 calculateTrailingStopLevel(positionAvgPrice, trailOffsetPercent, trailPercent, currentHigh, currentLow, isLong) 
  Calculates the current trailing stop level for a position.
  Parameters:
     positionAvgPrice (float) : Float: The average price of the current position (strategy.position_avg_price).
     trailOffsetPercent (float) : Float 🔄: The percentage price movement to activate the trailing stop.
     trailPercent (float) : Float 🔄: The percentage distance the stop trails behind the price.
     currentHigh (float) : Float: The current bar's high (high).
     currentLow (float) : Float: The current bar's low (low).
     isLong (bool) : Bool: True if the position is long, false if short.
  Returns: The calculated trailing stop price if active, otherwise na.
@example
longTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, true)
shortTrailStop = nineLivesUtilLib.calculateTrailingStopLevel(strategy.position_avg_price, trailOffset, trailPercent, high, low, false)
if not na(longTrailStop)
strategy.exit("Long Trail", from_entry="Long", stop=longTrailStop)
DEMA Trend Oscillator Strategy📌 Overview 
The DEMA Trend Oscillator Strategy is a dynamic trend-following approach based on the Normalized DEMA Oscillator SD.
It adapts in real-time to market volatility with the goal of improving entry accuracy and optimizing risk management.
⚠️ This strategy is provided for educational and research purposes only.
Past performance does not guarantee future results.
 🎯 Strategy Objectives 
The main goal of this strategy is to respond quickly to sudden price movements and trend reversals,
by combining momentum-based signals with volatility filters.
It is designed to be user-friendly for traders of all experience levels.
 ✨ Key Features 
   Normalized DEMA Oscillator: A momentum indicator that normalizes DEMA values on a 0–100 scale, allowing intuitive identification of trend strength
 Two-Bar Confirmation Filter: Requires two consecutive bullish or bearish candles to reduce noise and enhance entry reliability
 ATR x2 Trailing Stop: In addition to fixed stop-loss levels, a trailing stop based on 2× ATR is used to maximize profits during strong trends
 
 📊 Trading Rules 
 Long Entry: 
   Normalized DEMA > 55 (strong upward momentum)
 Candle low is above the upper SD band
 Two consecutive bullish candles appear
 
 Short Entry: 
 Normalized DEMA < 45 (downward momentum)
 Candle high is below the lower SD band
 Two consecutive bearish candles appear
 
 Exit Conditions: 
 Take-profit at a risk-reward ratio of 1.5
 Stop-loss triggered if price breaks below (long) or above (short) the SD band
 Trailing stop activated based on 2× ATR to secure and extend profits
 
 💰 Risk Management Parameters 
 Symbol & Timeframe: Any (AUDUSD 5M example)
 Account size (virtual): $3000
 Commission: 0.4PIPS(0.0004)
 Slippage: 2 pips
 Risk per trade: 5%
 Number of trades (backtest):534
 
All parameters can be adjusted based on broker specifications and individual trading profiles.
 ⚙️ Trading Parameters & Considerations 
Indicator: Normalized DEMA Oscillator SD
Parameter settings:
   DEMA Period (len_dema): 40
 Base Length: 20
 Long Threshold: 55
 Short Threshold: 45
 Risk-Reward Ratio: 1.5
 ATR Multiplier for Trailing Stop: 2.0
 
 🖼 Visual Support 
The chart displays the following visual elements:
  
 Upper and lower SD bands (±2 standard deviations)
 Entry signals shown as directional arrows
 
 🔧 Strategy Improvements & Uniqueness 
This strategy is inspired by “Normalized DEMA Oscillator SD” by QuantEdgeB,
but introduces enhancements such as a two-bar confirmation filter and an ATR-based trailing stop.
Compared to conventional trend-following strategies, it offers superior noise filtering and profit optimization.
 ✅ Summary 
The DEMA Trend Oscillator Strategy is a responsive and practical trend-following method
that combines momentum detection with adaptive risk management.
Its visual clarity and logical structure make it a powerful and repeatable tool
for traders seeking consistent performance in trending markets.
⚠️ Always apply appropriate risk management. This strategy is based on historical data and does not guarantee future results.






















