PROTECTED SOURCE SCRIPT
MA Types - Auto Optimized

This indicator is a comprehensive Moving Average optimization engine designed to dynamically identify the most effective period for a selected Moving Average type (SMA, EMA, WMA, or RMA) based on historical price action. Unlike standard indicators that use a fixed length (e.g., a 50-period SMA) for the entire chart history, this script performs a "Walk-Forward" simulation on every bar to determine which period would have yielded the best risk-adjusted returns for a Long-Only strategy up to that specific moment.
The core concept is to adapt to changing market volatility and trends by mathematically scoring different lookback periods and projecting the "winner" onto the chart.
How It Works
The script runs an internal simulation loop for every candle, testing a range of periods (defined by the user, e.g., 2 to 50). For each period p in that range, it tracks a theoretical trading account that executes trades based on crossovers of that specific MA.
Simulation: It calculates the MA value for every period in the range using manual math implementations (to allow for dynamic length processing).
Trade Logic (Long Only):
Buy Signal: Simulates opening a Long position when the price crosses over the MA.
Sell Signal: Simulates closing the Long position when the price crosses under the MA.
Scoring: It calculates a "Score" for each period based on Net Profit, Drawdown, and Profit Factor.
Selection: The period with the highest score is selected as the "Best Period" for the current bar.
Visualization: The indicator plots the MA value of that winning period. This creates a composite "Optimized MA Line" that shifts its length as market conditions change.
Features & Settings
MA Types: Choose between Simple (SMA), Exponential (EMA), Weighted (WMA), and Relative (RMA) Moving Averages.
Optimization Range: Define the Min Period and Max Period to constrain the search space (e.g., searching for the best MA between 10 and 200).
Risk Management: Inputs for Initial Capital, Quantity %, and Commission % allow the simulation to account for trading costs and position sizing, ensuring the "Best Period" isn't selected based on unrealistic friction-less trading.
Dashboard: A table in the bottom right displays the performance metrics of the currently selected "Best Period," including Net Profit, Max Drawdown, Win Rate, and Profit Factor.
Pros and Cons
Pros:
Adaptability: The indicator adjusts to the market phase. It might select a fast MA during strong trends to capture moves early, and a slower MA during chop to avoid false signals.
Data-Driven: Signals are based on mathematical performance metrics rather than arbitrary fixed numbers.
Visual Clarity: Provides a single line and clear Buy/Sell labels, reducing chart clutter compared to plotting multiple MAs.
Cons:
Repainting/Lag: While the indicator DOES NOT repaint past signals (it is a walk-forward analysis), the "Best Period" can change from bar to bar. This means the MA line may appear "jagged" or shift character as the winner changes.
Curve Fitting: Because the script hunts for the best historical performance, there is an inherent risk of overfitting to past data. The "best" period of the past 100 bars is not guaranteed to be the best for the next 10.
Processing Heavy: Calculating dozens of moving averages and tracking their theoretical equity curves on every bar is computationally intensive.
Screenshots & Examples
1. Bitcoin (BTC/USDT) - SMA Optimization

This example shows the script optimizing a Simple Moving Average (SMA) on Bitcoin. The dashboard indicates a "Best Period" of 125, resulting in a high Profit Factor.
2. Gold (XAU/USD) - SMA Intraday

Here, the script is applied to Gold on a 1-hour chart. The optimization engine adapts to the intraday volatility, selecting a longer period (188) to filter out noise.
3. Bitcoin (BTC/USD) - WMA Optimization

Using a Weighted Moving Average (WMA), the script captures the aggressive trend of Bitcoin. The WMA places more weight on recent data, often reacting faster than the SMA.
4. Silver (XAG/USD) - RMA Optimization

This chart demonstrates the Relative Moving Average (RMA) on Silver. The RMA is smoother and often used in RSI calculations; here it provides a steady trend-following line with a high win rate.
Usage Note
This script is intended as a trend-following tool for spot trading or long-biased strategies. It works best in trending markets and may produce whipsaws in ranging sideways markets. Always use it in conjunction with other forms of analysis, such as support/resistance or volume, to confirm signals.
Disclaimer
Not Financial Advice: This script and its description are for educational and informational purposes only. Nothing here constitutes financial, investment, or trading advice.
Risk Warning: Trading financial markets involves a high level of risk and may not be suitable for all investors. You should never trade with money you cannot afford to lose.
Past Performance: This tool relies on historical optimization ("curve fitting"). Please be aware that past performance is not indicative of future results. A Moving Average period that performed perfectly in the last 100 bars may fail completely in the next 100 bars due to changing market volatility and conditions.
Liability: The author assumes no responsibility or liability for any errors, omissions, or for any trading losses incurred from the use of this script. Always perform your own due diligence and use this tool as part of a broader risk management strategy.
The core concept is to adapt to changing market volatility and trends by mathematically scoring different lookback periods and projecting the "winner" onto the chart.
How It Works
The script runs an internal simulation loop for every candle, testing a range of periods (defined by the user, e.g., 2 to 50). For each period p in that range, it tracks a theoretical trading account that executes trades based on crossovers of that specific MA.
Simulation: It calculates the MA value for every period in the range using manual math implementations (to allow for dynamic length processing).
Trade Logic (Long Only):
Buy Signal: Simulates opening a Long position when the price crosses over the MA.
Sell Signal: Simulates closing the Long position when the price crosses under the MA.
Scoring: It calculates a "Score" for each period based on Net Profit, Drawdown, and Profit Factor.
Selection: The period with the highest score is selected as the "Best Period" for the current bar.
Visualization: The indicator plots the MA value of that winning period. This creates a composite "Optimized MA Line" that shifts its length as market conditions change.
Features & Settings
MA Types: Choose between Simple (SMA), Exponential (EMA), Weighted (WMA), and Relative (RMA) Moving Averages.
Optimization Range: Define the Min Period and Max Period to constrain the search space (e.g., searching for the best MA between 10 and 200).
Risk Management: Inputs for Initial Capital, Quantity %, and Commission % allow the simulation to account for trading costs and position sizing, ensuring the "Best Period" isn't selected based on unrealistic friction-less trading.
Dashboard: A table in the bottom right displays the performance metrics of the currently selected "Best Period," including Net Profit, Max Drawdown, Win Rate, and Profit Factor.
Pros and Cons
Pros:
Adaptability: The indicator adjusts to the market phase. It might select a fast MA during strong trends to capture moves early, and a slower MA during chop to avoid false signals.
Data-Driven: Signals are based on mathematical performance metrics rather than arbitrary fixed numbers.
Visual Clarity: Provides a single line and clear Buy/Sell labels, reducing chart clutter compared to plotting multiple MAs.
Cons:
Repainting/Lag: While the indicator DOES NOT repaint past signals (it is a walk-forward analysis), the "Best Period" can change from bar to bar. This means the MA line may appear "jagged" or shift character as the winner changes.
Curve Fitting: Because the script hunts for the best historical performance, there is an inherent risk of overfitting to past data. The "best" period of the past 100 bars is not guaranteed to be the best for the next 10.
Processing Heavy: Calculating dozens of moving averages and tracking their theoretical equity curves on every bar is computationally intensive.
Screenshots & Examples
1. Bitcoin (BTC/USDT) - SMA Optimization
This example shows the script optimizing a Simple Moving Average (SMA) on Bitcoin. The dashboard indicates a "Best Period" of 125, resulting in a high Profit Factor.
2. Gold (XAU/USD) - SMA Intraday
Here, the script is applied to Gold on a 1-hour chart. The optimization engine adapts to the intraday volatility, selecting a longer period (188) to filter out noise.
3. Bitcoin (BTC/USD) - WMA Optimization
Using a Weighted Moving Average (WMA), the script captures the aggressive trend of Bitcoin. The WMA places more weight on recent data, often reacting faster than the SMA.
4. Silver (XAG/USD) - RMA Optimization
This chart demonstrates the Relative Moving Average (RMA) on Silver. The RMA is smoother and often used in RSI calculations; here it provides a steady trend-following line with a high win rate.
Usage Note
This script is intended as a trend-following tool for spot trading or long-biased strategies. It works best in trending markets and may produce whipsaws in ranging sideways markets. Always use it in conjunction with other forms of analysis, such as support/resistance or volume, to confirm signals.
Disclaimer
Not Financial Advice: This script and its description are for educational and informational purposes only. Nothing here constitutes financial, investment, or trading advice.
Risk Warning: Trading financial markets involves a high level of risk and may not be suitable for all investors. You should never trade with money you cannot afford to lose.
Past Performance: This tool relies on historical optimization ("curve fitting"). Please be aware that past performance is not indicative of future results. A Moving Average period that performed perfectly in the last 100 bars may fail completely in the next 100 bars due to changing market volatility and conditions.
Liability: The author assumes no responsibility or liability for any errors, omissions, or for any trading losses incurred from the use of this script. Always perform your own due diligence and use this tool as part of a broader risk management strategy.
Protected script
This script is published as closed-source. However, you can use it freely and without any limitations – learn more here.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Protected script
This script is published as closed-source. However, you can use it freely and without any limitations – learn more here.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.