OPEN-SOURCE SCRIPT
Super Optimized SMA 20/200 Strategy - Long & Short_grok

### Description of the SMA 20/200 Trading Strategy with Proposed Optimizations
The "Super Optimized SMA 20/200 Strategy - Long & Short" is a technical trading strategy designed for TradingView, leveraging two Simple Moving Averages (SMA) — a 20-period SMA for short-term trend detection and a 200-period SMA for long-term support/resistance — to identify entry and exit points for both long and short positions. Originally inspired by Emmanuel Malyarovich's minimalist approach, the strategy has been enhanced with optimizations to improve profitability, reduce risk, and adapt to volatile markets like cryptocurrencies (e.g., XRPUSD). Below is a detailed description of the base strategy and the proposed optimizations.
#### **Base Strategy Overview**
- **Indicators Used**:
- **20 SMA**: Tracks short-term trends and serves as a dynamic support/resistance level for bounce entries.
- **200 SMA**: Acts as a long-term support (for long entries) or resistance (for short entries).
- **Entry Logic**:
- **Long Entry**: Triggered when the price bounces off the 20 SMA in an uptrend (20 SMA sloping upward over the last 3 bars), with the low touching or slightly below the 20 SMA and the close above it. The price must also be above the 200 SMA for confirmation.
- **Short Entry**: Triggered when the price rebounds off the 20 SMA in a downtrend (20 SMA sloping downward), with the high touching or slightly above the 20 SMA and the close below it. The price must be below the 200 SMA.
- **Exit Logic**:
- Default settings include a 2% take profit (TP) and 1% stop loss (SL) for both long and short positions.
- A trailing stop with a 0.1% offset can be activated to lock in profits during strong trends.
- **Visuals and Alerts**: The strategy plots 20 SMA (blue) and 200 SMA (red) on the chart, with green triangles for long entries and red triangles for short entries. Alerts notify users of entry signals with price details.
- **Initial Settings**: Starts with $10,000 capital, using 10% of equity per trade.
#### **Proposed Optimizations**
To address the observed 2% profitability (improved to 112% with trailing stop) and align with your feedback (e.g., 1H outperforming 4H, tolerance at 0.1% working well), the following enhancements have been integrated into the strategy:
1. **Flexible Take Profit and Trailing Stop**:
- Added a `useTakeProfit` boolean (default true) to toggle TP. If set to false, only the trailing stop (0.1% offset) is used, allowing unlimited profit capture in strong trends. This addresses your request to disable TP, potentially boosting profitability in bull/bear runs while increasing drawdown risk.
- **Recommendation**: Test with TP off on 1H for XRPUSD to confirm 112% holds; adjust offset to 0.2% if drawdown exceeds 20%.
2. **Dynamic Stop Loss with ATR**:
- Replaced fixed 1% SL with a dynamic SL based on ATR(14) * 1.5, calculated as `close * (1 - (ATR * multiplier / close))` for long and the inverse for short. Inputs `atrLength` (14) and `atrMultiplier` (1.5) are adjustable.
- **Benefit**: Adapts to market volatility, reducing premature exits in choppy conditions. Test with multiplier 1-2 to balance risk/reward.
- **Note**: A `useAtrStop` toggle (default true) allows reverting to fixed SL if needed.
3. **Tolerance for Pullback Adjustment**:
- Set to 0.1% (your successful tweak), allowing precise bounce detection. The strategy checks if the low is within ±0.1% of 20 SMA, with the close crossing above for long or below for short.
- **Optimization**: If trades are too few, increase to 0.3-0.5% to capture more opportunities, as seen in your original script’s 0.5% tolerance.
4. **RSI Filter**:
- Integrated RSI(14) with configurable `rsiOverbought` (default 70) and `rsiOversold` (default 30). Long entries require RSI > oversoldLevel, and short entries require RSI < overboughtLevel.
- **Benefit**: Filters out overbought/oversold conditions, improving signal quality. Test with neutral levels (50) for broader entries, potentially adding 10-20% to profitability.
5. **Market Sideways Filter**:
- Added a `sma20_flat` condition, checking if the 20 SMA variation over the last 5 bars (`flatCheckBars`) is below a `flatTolerance` (0.001). If true, entries are blocked.
- **Benefit**: Reduces false signals in range-bound markets, lowering drawdown. Adjust `flatCheckBars` to 3-7 based on volatility.
6. **Time/Day Filter**:
- Restricts trading to active hours (default 8:00-20:00 UTC, adjustable with `startHour` and `endHour`) and excludes weekends (Saturday/Sunday).
- **Benefit**: Focuses on high-volume periods in crypto, improving winning rate. Adjust hours to 9:00-17:00 UTC if testing on BTCUSD/ETHUSD.
7. **Volume Filter**:
- Retained from your script, with `minVolume` (default 0, disabled) to filter low-liquidity trades.
- **Optimization**: Set to a symbol-specific minimum (e.g., 10,000 for XRPUSD) to avoid slippage.
#### **Implementation Details**
- The strategy uses `strategy.entry` and `strategy.exit` with conditional logic for TP, SL, and trailing stops. Visuals (triangles) and alerts remain for manual oversight.
- Inputs are fully customizable, allowing backtesting to fine-tune parameters.
#### **Testing Recommendations**
- **Timeframe**: Stick to 1H for XRPUSD, as 4H underperformed. Test 2H or Daily on BTCUSD/ETHUSD for stability.
- **Symbols**: Beyond XRPUSD, try BTCUSD (stable) or ETHUSD (volatile but liquid) to diversify gains.
- **Backtesting**: Run on the last 2 years (Oct 2023-Oct 2025), with 70% for optimization and 30% for out-of-sample testing. Include 0.1% commissions and 0.05% slippage.
- **Metrics to Watch**: Aim for profit >6%, drawdown <30%, and winning rate >50%. If 112% persists, validate with live demo trading.
#### **Next Steps**
This optimized strategy balances your successful tweaks (0.1% tolerance, trailing stop) with robust filters (RSI, sideways, time). Test on TradingView, adjust inputs based on results, and report back with drawdown or trade count for further tuning!
The "Super Optimized SMA 20/200 Strategy - Long & Short" is a technical trading strategy designed for TradingView, leveraging two Simple Moving Averages (SMA) — a 20-period SMA for short-term trend detection and a 200-period SMA for long-term support/resistance — to identify entry and exit points for both long and short positions. Originally inspired by Emmanuel Malyarovich's minimalist approach, the strategy has been enhanced with optimizations to improve profitability, reduce risk, and adapt to volatile markets like cryptocurrencies (e.g., XRPUSD). Below is a detailed description of the base strategy and the proposed optimizations.
#### **Base Strategy Overview**
- **Indicators Used**:
- **20 SMA**: Tracks short-term trends and serves as a dynamic support/resistance level for bounce entries.
- **200 SMA**: Acts as a long-term support (for long entries) or resistance (for short entries).
- **Entry Logic**:
- **Long Entry**: Triggered when the price bounces off the 20 SMA in an uptrend (20 SMA sloping upward over the last 3 bars), with the low touching or slightly below the 20 SMA and the close above it. The price must also be above the 200 SMA for confirmation.
- **Short Entry**: Triggered when the price rebounds off the 20 SMA in a downtrend (20 SMA sloping downward), with the high touching or slightly above the 20 SMA and the close below it. The price must be below the 200 SMA.
- **Exit Logic**:
- Default settings include a 2% take profit (TP) and 1% stop loss (SL) for both long and short positions.
- A trailing stop with a 0.1% offset can be activated to lock in profits during strong trends.
- **Visuals and Alerts**: The strategy plots 20 SMA (blue) and 200 SMA (red) on the chart, with green triangles for long entries and red triangles for short entries. Alerts notify users of entry signals with price details.
- **Initial Settings**: Starts with $10,000 capital, using 10% of equity per trade.
#### **Proposed Optimizations**
To address the observed 2% profitability (improved to 112% with trailing stop) and align with your feedback (e.g., 1H outperforming 4H, tolerance at 0.1% working well), the following enhancements have been integrated into the strategy:
1. **Flexible Take Profit and Trailing Stop**:
- Added a `useTakeProfit` boolean (default true) to toggle TP. If set to false, only the trailing stop (0.1% offset) is used, allowing unlimited profit capture in strong trends. This addresses your request to disable TP, potentially boosting profitability in bull/bear runs while increasing drawdown risk.
- **Recommendation**: Test with TP off on 1H for XRPUSD to confirm 112% holds; adjust offset to 0.2% if drawdown exceeds 20%.
2. **Dynamic Stop Loss with ATR**:
- Replaced fixed 1% SL with a dynamic SL based on ATR(14) * 1.5, calculated as `close * (1 - (ATR * multiplier / close))` for long and the inverse for short. Inputs `atrLength` (14) and `atrMultiplier` (1.5) are adjustable.
- **Benefit**: Adapts to market volatility, reducing premature exits in choppy conditions. Test with multiplier 1-2 to balance risk/reward.
- **Note**: A `useAtrStop` toggle (default true) allows reverting to fixed SL if needed.
3. **Tolerance for Pullback Adjustment**:
- Set to 0.1% (your successful tweak), allowing precise bounce detection. The strategy checks if the low is within ±0.1% of 20 SMA, with the close crossing above for long or below for short.
- **Optimization**: If trades are too few, increase to 0.3-0.5% to capture more opportunities, as seen in your original script’s 0.5% tolerance.
4. **RSI Filter**:
- Integrated RSI(14) with configurable `rsiOverbought` (default 70) and `rsiOversold` (default 30). Long entries require RSI > oversoldLevel, and short entries require RSI < overboughtLevel.
- **Benefit**: Filters out overbought/oversold conditions, improving signal quality. Test with neutral levels (50) for broader entries, potentially adding 10-20% to profitability.
5. **Market Sideways Filter**:
- Added a `sma20_flat` condition, checking if the 20 SMA variation over the last 5 bars (`flatCheckBars`) is below a `flatTolerance` (0.001). If true, entries are blocked.
- **Benefit**: Reduces false signals in range-bound markets, lowering drawdown. Adjust `flatCheckBars` to 3-7 based on volatility.
6. **Time/Day Filter**:
- Restricts trading to active hours (default 8:00-20:00 UTC, adjustable with `startHour` and `endHour`) and excludes weekends (Saturday/Sunday).
- **Benefit**: Focuses on high-volume periods in crypto, improving winning rate. Adjust hours to 9:00-17:00 UTC if testing on BTCUSD/ETHUSD.
7. **Volume Filter**:
- Retained from your script, with `minVolume` (default 0, disabled) to filter low-liquidity trades.
- **Optimization**: Set to a symbol-specific minimum (e.g., 10,000 for XRPUSD) to avoid slippage.
#### **Implementation Details**
- The strategy uses `strategy.entry` and `strategy.exit` with conditional logic for TP, SL, and trailing stops. Visuals (triangles) and alerts remain for manual oversight.
- Inputs are fully customizable, allowing backtesting to fine-tune parameters.
#### **Testing Recommendations**
- **Timeframe**: Stick to 1H for XRPUSD, as 4H underperformed. Test 2H or Daily on BTCUSD/ETHUSD for stability.
- **Symbols**: Beyond XRPUSD, try BTCUSD (stable) or ETHUSD (volatile but liquid) to diversify gains.
- **Backtesting**: Run on the last 2 years (Oct 2023-Oct 2025), with 70% for optimization and 30% for out-of-sample testing. Include 0.1% commissions and 0.05% slippage.
- **Metrics to Watch**: Aim for profit >6%, drawdown <30%, and winning rate >50%. If 112% persists, validate with live demo trading.
#### **Next Steps**
This optimized strategy balances your successful tweaks (0.1% tolerance, trailing stop) with robust filters (RSI, sideways, time). Test on TradingView, adjust inputs based on results, and report back with drawdown or trade count for further tuning!
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.