Simple Moving Average (SMA)

An average computed by summing values over a fixed number of periods and dividing by that count, giving equal weight to each observation.

A Simple Moving Average (SMA) is the most straightforward type of moving average, calculated by summing all values within a fixed window and dividing by the number of observations. Every data point in the window receives equal weight, making the SMA easy to understand and implement but slower to respond to recent changes compared to an Exponential Moving Average.

Formula

1SMA = (P₁ + P₂ + P₃ + ... + Pₙ) / n

Where P represents each price observation and n is the number of periods.

On-chain implementation

Implementing SMA in Solidity requires storing historical values:

1uint256[] public priceHistory;
2uint256 public constant WINDOW_SIZE = 10;
3
4function updateSMA(uint256 newPrice) external returns (uint256 sma) {
5 priceHistory.push(newPrice);
6
7 uint256 sum = 0;
8 uint256 start = priceHistory.length > WINDOW_SIZE
9 ? priceHistory.length - WINDOW_SIZE
10 : 0;
11 uint256 count = priceHistory.length - start;
12
13 for (uint256 i = start; i < priceHistory.length; i++) {
14 sum += priceHistory[i];
15 }
16
17 sma = sum / count;
18}

Limitations in DeFi

  • Storage cost: Maintaining an array of historical values is gas-expensive on-chain.
  • Equal weighting: Old data has the same influence as new data, creating lag in trend detection.
  • Precision loss: Integer division in Solidity truncates remainders, compounding errors over many calculations.
  • Manipulation: An attacker who controls data points at the edges of the window can disproportionately affect the average.

SMA vs EMA in DeFi

PropertySMAEMA
Weight distributionEqualExponentially decreasing
ResponsivenessSlowerFaster
Storage requirementFull windowSingle value
Gas costHigher (loop)Lower (single update)
Manipulation resistanceModerateModerate

For most on-chain applications, EMAs are preferred due to lower storage requirements and faster responsiveness. SMAs are more common in off-chain analytics and technical analysis tooling.

Need expert guidance on Simple Moving Average (SMA)?

Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.

Get a Quote

oog
zealynx

Subscribe to Our Newsletter

Stay updated with our latest security insights and blog posts

© 2024 Zealynx