Moving averages have been the cornerstone of technical analysis for decades. From the simple moving average (SMA) to the exponential moving average (EMA), traders have relied on these tools to smooth price action and identify trends. But what if there was a more sophisticated approach that could adapt to market dynamics while maintaining mathematical elegance?

Enter the Logarithmic Moving Average (LMA) — a powerful indicator that leverages logarithmic weighting to create a more responsive and intelligent trend-following system.
The Problem with Traditional Moving Averages
Before diving into the LMA, let’s understand why we need an alternative:
- Linear Decay: Traditional MAs use linear or exponential weight decay, which may not accurately reflect how market information ages
- Fixed Responsiveness: Most MAs have a fixed relationship between recent and historical data
- Lack of Quality Metrics: Standard MAs don’t incorporate trend strength or quality measures
The Logarithmic Advantage
The LMA addresses these limitations through several innovative features:
1. Logarithmic Weight Distribution
Instead of linear or exponential decay, the LMA uses a logarithmic function to assign weights to historical data:
weight = 1 / (log(i + steepness))²
This creates a more nuanced weight distribution that can be fine-tuned through the steepness parameter. Higher steepness values prioritize recent data more aggressively, while lower values create a more gradual decay.
2. Trend Quality Assessment
The LMA incorporates R-squared (R²) analysis to measure trend quality. By calculating the correlation coefficient of log prices over the lookback period, the indicator can assess whether the market is trending strongly or moving sideways. This quality metric is then used to adjust signal strength.
3. Momentum Confirmation
The indicator calculates annualized log returns and uses them to confirm signal direction. When momentum aligns with the LMA signal, the indicator applies a confirmation weight multiplier, strengthening high-probability setups.
Understanding the Signal Generation
The LMA generates its signal through a multi-step process:
- Calculate the logarithmic weighted average of prices
- Measure the slope of this average (percentage change over 10 bars)
- Assess trend quality using R-squared analysis
- Combine slope and quality:
signal = slope × (0.5 + R² × 0.5) - Apply momentum confirmation when directions align
- Smooth the final signal using your choice of MA type
Strategy Presets: One Size Doesn’t Fit All
Recognizing that different trading styles require different parameters, the LMA includes five preset configurations:
Default (Universal)
- Period: 100 | Steepness: 2.5 | Smoothing: 10
- Balanced for general trading across multiple timeframes
Scalping
- Period: 60 | Steepness: 3.0 | Smoothing: 5
- Highly responsive for quick intraday trades
Swing Trading
- Period: 120 | Steepness: 2.0 | Smoothing: 15
- Filters noise while capturing multi-day swings
Trend Following
- Period: 150 | Steepness: 1.8 | Smoothing: 20
- Maximum stability for long-term position trades
Mean Reversion
- Period: 80 | Steepness: 3.5 | Smoothing: 8
- Sensitive to extremes for counter-trend opportunities
Visual Intelligence: The Color Gradient System
One of the LMA’s most innovative features is its dynamic color gradient system. Rather than binary bullish/bearish colors, the indicator uses color blending to show signal strength:
- Strong Bullish (above long threshold): Full green
- Weak Bullish (0 to threshold): Gradient from yellow to green
- Neutral (near zero): Yellow
- Weak Bearish (0 to threshold): Gradient from yellow to red
- Strong Bearish (below short threshold): Full red
This visual system provides immediate insight into not just direction, but conviction.
Reading the Numbers: A Practical Guide
Before diving into trading signals, it’s crucial to understand what the LMA numbers actually represent. The indicator oscillates around zero, typically ranging from -5 to +5, with each value telling a story about trend strength and quality.
The Scale Explained
+2.0 and above → Very Strong Bullish Trend
+0.5 to +2.0 → Bullish Trend (Trading Zone)
0 to +0.5 → Weak Bullish / Transitioning
0 → Neutral / No Clear Trend
0 to -0.5 → Weak Bearish / Transitioning
-0.5 to -2.0 → Bearish Trend (Trading Zone)
-2.0 and below → Very Strong Bearish Trend
These aren’t arbitrary numbers — they represent a composite score combining:
- Trend slope (how fast prices are moving)
- Trend quality (how consistent the movement is)
- Momentum confirmation (whether short-term action supports the trend)
Understanding Increasing vs Declining Values
The direction of the LMA signal itself tells you about trend acceleration:
When LMA Signal is Increasing (Moving Higher):
- Bullish momentum is accelerating
- Buyers are gaining control
- Trend strength is improving
- Higher highs are likely
When LMA Signal is Declining (Moving Lower):
- Bullish momentum is waning (if above zero)
- Bearish pressure is building
- Trend strength is deteriorating
- Corrections or reversals may be approaching
Critical Insight: The signal can decline while still remaining positive. This indicates the uptrend is slowing but not yet reversed — often seen during healthy consolidations.
Critical Threshold Levels
The indicator uses three key reference points:
- Long Threshold (default +0.5): Crossing above signals sufficient bullish strength for long entries
- Short Threshold (default -0.5): Crossing below indicates bearish conviction for short positions
- Zero Line: The neutral divide between bullish and bearish territories
Real-World Examples
- Signal at +1.5: A strong uptrend with excellent follow-through. Institutions are likely accumulating.
- Signal at +0.3: Positive but unconvincing. The market is drifting higher without conviction.
- Signal at -2.0: Aggressive selling with momentum. Risk-off sentiment dominates.
- Signal near 0: Choppy, directionless action. Perfect conditions for whipsaws.
The beauty lies in the nuance — you’re not just seeing “up” or “down,” but understanding the quality and conviction behind each move.
Why Short Signals Fail: Lessons from NIFTY
Examining the NIFTY futures chart reveals a crucial lesson about failed short signals, particularly visible in 2024-2025. Several short signals (when LMA crossed below -0.5) were quickly reversed. Here’s why:
1. Bull Market Dynamics
In strong bull markets, corrections are:
- Shallow: Rarely reaching oversold extremes
- Brief: Lasting days rather than weeks
- V-shaped: Sharp down, sharper up
The LMA correctly identified bearish momentum, but the underlying bull trend reasserted itself quickly.
2. Support Level Bounces
Notice how several short signals occurred just as price reached major support levels (visible as previous resistance). The market’s memory at these levels created swift reversals that trapped short sellers.
3. Momentum vs Structure
The LMA measures momentum and trend quality, not market structure. When short signals fire into strong structural support, the probability of failure increases dramatically.
4. Time Frame Misalignment
Daily chart sell signals during weekly/monthly uptrends often fail. The indicator is doing its job on the daily timeframe, but higher timeframe trends dominate.
Best Practices for Short Signals
- Context Matters: Check higher timeframe trends before shorting
- Respect Support: Avoid shorting into major support levels
- Confirmation: Wait for the signal to stabilize below threshold, not just touch it
- Risk Management: Use tighter stops on counter-trend trades
- Market Regime: Recognize when you’re in a strong bull market where “buy the dip” prevails
The NIFTY Example
In your NIFTY chart, we can see:
- March-May 2024: Short signal worked well during genuine correction
- October 2024: Brief short signal failed as dip buyers emerged
- Early 2025: Multiple failed shorts as bull market resumed
The lesson? In trending markets, trade with the major trend. Use opposite signals more for profit-taking than new position initiation.
Trading Signals and Implementation
The LMA generates clear trading signals based on these threshold crossings:
- Buy Signal: When the smoothed signal crosses above the long threshold
- Sell/Short Signal: When the signal crosses below the short threshold
- Exit Signals: Star markers indicate when to close positions
The indicator plots these signals with distinctive arrows and shapes, making them easy to spot even on busy charts.
Mathematical Foundation: Why Logarithms?
Logarithmic scaling offers several advantages for financial data:
- Percentage-Based: Log returns represent percentage changes, making them more relevant for trading
- Symmetry: A 50% loss and 100% gain have equal magnitude in log space
- Statistical Properties: Log returns tend to be more normally distributed
- Compound Growth: Logarithms naturally model compound growth patterns
Practical Applications
Trend Confirmation
Use the LMA alongside price action to confirm trend direction. When price is above its moving average and LMA signal is bullish, confidence increases.
Divergence Detection
Watch for divergences between price and the LMA signal. These often precede trend reversals.
Multi-Timeframe Analysis
Run the LMA on multiple timeframes to identify confluence zones where signals align.
Risk Management
The signal strength (distance from zero) can help size positions — stronger signals may warrant larger positions.
Implementation Considerations
When implementing the LMA in your trading:
- Backtest Thoroughly: Each market has unique characteristics that may favor different parameters
- Combine with Other Tools: The LMA works best as part of a comprehensive system
- Respect the Thresholds: Don’t anticipate signals; wait for clear threshold breaks
- Monitor Trend Quality: Low R² values suggest choppy conditions where signals may be less reliable
The Code Behind the Magic
The AmiBroker AFL implementation showcases several advanced concepts:
- Array Processing: Efficient calculation across entire price history
- Dynamic Parameter Adjustment: Strategy presets modify multiple parameters simultaneously
- Conditional Color Mapping: Complex color gradients based on signal strength
- Statistical Calculations: R-squared and correlation computed within AFL
The Logarithmic Moving Average – Amibroker AFL Code
_SECTION_BEGIN("Logarithmic Moving Average (LMA)");
// Set chart options with dates on X-axis
SetChartOptions(0, chartShowArrows | chartShowDates);
/* --------------------------------------------------------------------------- */
/* PARAMETER DEFINITIONS */
/* --------------------------------------------------------------------------- */
// Strategy Presets
strategy_preset = ParamList("Strategy Preset", "Default|Scalping|Swing Trading|Trend Following|Mean Reversion|Custom", 0);
// LMA Core Settings
LMA_Period = Param("LMA Period", 100, 50, 200, 1);
log_steepness = Param("Log Steepness", 2.5, 1.5, 5.0, 0.1);
ma_type_param = ParamList("Smoothing MA Type", "EMA|SMA|WMA|RMA|VWMA", 0);
signal_smooth = Param("Signal Smoothing", 10, 3, 25, 1);
momentum_weight = Param("Momentum Confirmation Weight", 1.2, 1.0, 2.0, 0.1);
// Trading Thresholds
long_threshold = Param("Long Entry Threshold", 0.5, 0.1, 2.0, 0.1);
short_threshold = Param("Short Entry Threshold", -0.5, -2.0, -0.1, 0.1);
// Visual Settings
bullish_color = ParamColor("Bullish Color", colorGreen);
bearish_color = ParamColor("Bearish Color", colorRed);
neutral_color = ParamColor("Neutral Color", colorYellow);
color_bars = ParamToggle("Color Price Bars", "No|Yes", 1);
/* --------------------------------------------------------------------------- */
/* STRATEGY PRESET IMPLEMENTATION */
/* --------------------------------------------------------------------------- */
// Apply strategy presets
if (strategy_preset == "Scalping")
{
LMA_Period = 60;
log_steepness = 3.0;
signal_smooth = 5;
long_threshold = 0.3;
short_threshold = -0.3;
}
else if (strategy_preset == "Swing Trading")
{
LMA_Period = 120;
log_steepness = 2.0;
signal_smooth = 15;
long_threshold = 0.7;
short_threshold = -0.7;
}
else if (strategy_preset == "Trend Following")
{
LMA_Period = 150;
log_steepness = 1.8;
signal_smooth = 20;
long_threshold = 1.0;
short_threshold = -1.0;
}
else if (strategy_preset == "Mean Reversion")
{
LMA_Period = 80;
log_steepness = 3.5;
signal_smooth = 8;
long_threshold = 0.4;
short_threshold = -0.4;
}
/* --------------------------------------------------------------------------- */
/* LOGARITHMIC MOVING AVERAGE CALCULATION */
/* --------------------------------------------------------------------------- */
// Initialize arrays for LMA calculation
LMA = 0;
total_weight = 0;
// Calculate logarithmic weights and weighted average
for (i = 0; i < LMA_Period; i++)
{
// Ensure we never have log(value) where value <= 1
log_arg = Max(i + log_steepness, 2.0);
weight = 1.0 / (log(log_arg) * log(log_arg));
// Add weighted price to LMA
price_i = Ref(Close, -i);
valid_price = IIf(IsNull(price_i), 0, price_i);
valid_weight = IIf(IsNull(price_i), 0, weight);
LMA = LMA + valid_price * valid_weight;
total_weight = total_weight + valid_weight;
}
// Normalize LMA
LMA = IIf(total_weight > 0, LMA / total_weight, Close);
/* --------------------------------------------------------------------------- */
/* SLOPE AND MOMENTUM CALCULATIONS */
/* --------------------------------------------------------------------------- */
// Calculate LMA slope (percentage change over 10 bars)
LMA_Slope = 0;
LMA_prev = Ref(LMA, -10);
LMA_prev_valid = IIf(IsNull(LMA_prev) OR LMA_prev == 0, 0, LMA_prev);
LMA_Slope = IIf(LMA_prev_valid != 0,
(LMA - LMA_prev) / LMA_prev * 100, 0);
// Calculate log returns and momentum
log_returns = 0;
prev_close = Ref(Close, -1);
prev_close_valid = IIf(IsNull(prev_close) OR prev_close <= 0, 0, prev_close);
close_valid = IIf(Close <= 0, 0, Close);
log_returns = IIf(prev_close_valid > 0 AND close_valid > 0,
log(Close / prev_close), 0);
// Annualized log momentum
log_momentum = Sum(log_returns, LMA_Period) * 252 / LMA_Period;
/* --------------------------------------------------------------------------- */
/* TREND QUALITY CALCULATION */
/* --------------------------------------------------------------------------- */
// Calculate R-squared for trend quality
sum_x = 0;
sum_y = 0;
sum_xy = 0;
sum_x2 = 0;
sum_y2 = 0;
valid_count = 0;
for (i = 0; i < LMA_Period; i++)
{
price_ref = Ref(Close, -i);
valid_price_ref = IIf(IsNull(price_ref) OR price_ref <= 0, 0, price_ref);
price_is_valid = IIf(IsNull(price_ref) OR price_ref <= 0, 0, 1);
x_val = i;
y_val = IIf(price_is_valid, log(Max(valid_price_ref, 0.001)), 0);
sum_x = sum_x + x_val * price_is_valid;
sum_y = sum_y + y_val * price_is_valid;
sum_xy = sum_xy + x_val * y_val * price_is_valid;
sum_x2 = sum_x2 + x_val * x_val * price_is_valid;
sum_y2 = sum_y2 + y_val * y_val * price_is_valid;
valid_count = valid_count + price_is_valid;
}
// Calculate correlation coefficient using arrays
denominator_calc = (valid_count * sum_x2 - sum_x * sum_x) *
(valid_count * sum_y2 - sum_y * sum_y);
denominator = sqrt(Max(denominator_calc, 0));
numerator = valid_count * sum_xy - sum_x * sum_y;
// Use IIf to handle the division and minimum valid points
corr_coef = IIf(valid_count > 10 AND denominator != 0,
numerator / denominator, 0);
// R-squared (clamped between 0 and 1)
r_squared = Max(0, Min(1, corr_coef * corr_coef));
/* --------------------------------------------------------------------------- */
/* SIGNAL GENERATION */
/* --------------------------------------------------------------------------- */
// Generate raw signal
raw_signal = LMA_Slope * (0.5 + r_squared * 0.5);
// Apply momentum confirmation weight
signal_sign = IIf(raw_signal > 0, 1, IIf(raw_signal < 0, -1, 0));
momentum_sign = IIf(log_momentum > 0, 1, IIf(log_momentum < 0, -1, 0));
momentum_confirmed = (signal_sign == momentum_sign) AND abs(log_momentum) > 0.01;
weighted_signal = IIf(momentum_confirmed, raw_signal * momentum_weight, raw_signal);
// Smooth the signal based on selected MA type
if (ma_type_param == "EMA")
{
smooth_signal = EMA(weighted_signal, signal_smooth);
}
else if (ma_type_param == "SMA")
{
smooth_signal = MA(weighted_signal, signal_smooth);
}
else if (ma_type_param == "WMA")
{
smooth_signal = WMA(weighted_signal, signal_smooth);
}
else if (ma_type_param == "RMA")
{
smooth_signal = AMA(weighted_signal, 1/signal_smooth);
}
else if (ma_type_param == "VWMA")
{
smooth_signal = Sum(weighted_signal * Volume, signal_smooth) / Sum(Volume, signal_smooth);
}
else
{
smooth_signal = EMA(weighted_signal, signal_smooth); // Default to EMA
}
/* --------------------------------------------------------------------------- */
/* POSITION CLASSIFICATION */
/* --------------------------------------------------------------------------- */
// Determine market position
position_bullish = smooth_signal > long_threshold;
position_bearish = smooth_signal < short_threshold;
position_neutral = NOT position_bullish AND NOT position_bearish;
/* --------------------------------------------------------------------------- */
/* VISUALIZATION */
/* --------------------------------------------------------------------------- */
// Calculate gradient ratios for color blending
// Ensure gradient ratios are between 0 and 1
gradient_ratio_bull = IIf(smooth_signal > 0 AND smooth_signal <= long_threshold,
Min(Max(smooth_signal / long_threshold, 0), 1),
IIf(smooth_signal > long_threshold, 1, 0));
gradient_ratio_bear = IIf(smooth_signal < 0 AND smooth_signal >= short_threshold,
Min(Max(abs(smooth_signal) / abs(short_threshold), 0), 1),
IIf(smooth_signal < short_threshold, 1, 0));
// Create color array for each bar
signal_color = 0;
for (i = 0; i < BarCount; i++)
{
if (smooth_signal[i] > long_threshold)
{
signal_color[i] = bullish_color;
}
else if (smooth_signal[i] < short_threshold)
{
signal_color[i] = bearish_color;
}
else if (smooth_signal[i] > 0)
{
// Weak bullish - blend from neutral to bullish
blend_factor = gradient_ratio_bull[i];
signal_color[i] = ColorBlend(neutral_color, bullish_color, blend_factor);
}
else if (smooth_signal[i] < 0)
{
// Weak bearish - blend from neutral to bearish
blend_factor = gradient_ratio_bear[i];
signal_color[i] = ColorBlend(neutral_color, bearish_color, blend_factor);
}
else
{
signal_color[i] = neutral_color;
}
}
// Plot LMA signal line (as area/line for underlying indicator)
Plot(smooth_signal, "LMA Signal", signal_color, styleArea | styleThick, -10, 10);
// Plot threshold lines
Plot(long_threshold, "Long Threshold", bullish_color, styleDashed, -10, 10);
Plot(short_threshold, "Short Threshold", bearish_color, styleDashed, -10, 10);
Plot(0, "Neutral Line", colorGrey40, styleThick, -10, 10);
// Add grid for better readability
PlotGrid(long_threshold, bullish_color, 10);
PlotGrid(short_threshold, bearish_color, 10);
PlotGrid(0, colorGrey40, 1);
// Color bars if enabled
if (color_bars)
{
SetBarFillColor(signal_color);
}
/* --------------------------------------------------------------------------- */
/* TRADING SIGNALS & ALERTS */
/* --------------------------------------------------------------------------- */
// Generate Buy/Sell signals based on threshold crossovers
Buy = Cross(smooth_signal, long_threshold);
Sell = Cross(short_threshold, smooth_signal);
Short = Sell;
Cover = Buy;
// Apply Exrem to remove redundant signals
Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
Short = ExRem(Short, Cover);
Cover = ExRem(Cover, Short);
// Set trade delays
SetTradeDelays(0, 0, 0, 0);
// Set trade prices
BuyPrice = ValueWhen(Buy, Close);
SellPrice = ValueWhen(Sell, Close);
ShortPrice = ValueWhen(Short, Close);
CoverPrice = ValueWhen(Cover, Close);
/* --------------------------------------------------------------------------- */
/* INFORMATION DISPLAY */
/* --------------------------------------------------------------------------- */
// Display current position in interpretation window
position_text = WriteIf(position_bullish, "BULLISH",
WriteIf(position_bearish, "BEARISH", "NEUTRAL"));
printf("\n======== LMA INDICATOR STATUS ========\n");
printf("Current Position: " + position_text + "\n");
printf("LMA Value: %.2f\n", LMA);
printf("Signal Value: %.2f\n", smooth_signal);
printf("LMA Slope: %.2f%%\n", LMA_Slope);
printf("Log Momentum: %.2f\n", log_momentum);
printf("R-Squared: %.2f\n", r_squared);
printf("======================================\n");
_SECTION_END();
The Logarithmic Moving Average represents an evolution in technical analysis — not a revolution. It builds upon time-tested concepts while incorporating modern mathematical techniques and visual design principles.
By combining logarithmic weighting, trend quality assessment, momentum confirmation, and intuitive visualization, the LMA provides traders with a sophisticated yet practical tool for navigating today’s markets.
Whether you’re a scalper seeking responsive signals or a position trader filtering for high-probability setups, the LMA adapts to your style while maintaining its mathematical integrity.
The future of technical analysis lies not in discarding what works, but in enhancing it with better mathematics, clearer visualization, and more intelligent design. The LMA exemplifies this philosophy, offering a glimpse of what’s possible when we apply modern thinking to classical problems.
Remember: No indicator is perfect. The LMA, like all technical tools, should be used as part of a comprehensive trading approach that includes proper risk management, market analysis, and disciplined execution.