The Pyth Network provides a high-frequency, low-latency aggregate price and confidence interval for each supported asset. The EMA Price and TWAP Calculation Standard defines how two critical derived values—the Exponentially-Weighted Moving Average (EMA) and the Time-Weighted Average Price (TWAP)—are computed from this raw streaming data. This standard is essential for DeFi protocols that require smoothed price signals to mitigate the impact of short-term volatility, flash crashes, or manipulation on sensitive operations like liquidations, funding rate calculations, and settlement.

EMA Price and TWAP Calculation Standard
Introduction
Specification for computing Exponentially-Weighted Moving Average (EMA) and Time-Weighted Average Price (TWAP) values from Pyth Network's streaming aggregate price.
This specification details the configurable parameters that govern the smoothing behavior of each calculation, such as the half-life for the EMA and the lookback window for the TWAP. It clarifies the distinct intended use cases for each: an EMA price, which weights recent observations more heavily, is often preferred for lending protocols to make liquidation thresholds responsive to current market conditions, while a TWAP, which gives equal weight to all observations in a window, is a common choice for settlement prices in perpetual futures to resist manipulation. The standard defines the precise mathematical formulas and operational boundaries, ensuring that any protocol consuming these derived values can reproduce and verify them independently.
For integration engineers and risk teams, this standard is the authoritative reference for how Pyth's derived prices behave at the protocol level. Understanding the calculation methodology is critical for correctly parameterizing a protocol's own risk controls, such as setting a liquidation discount relative to the EMA or choosing a TWAP window that aligns with a market's liquidity profile. A misalignment between a protocol's assumptions and the actual calculation can create systemic risk. Chainscore Labs helps teams audit these integration points, ensuring that the consumption of derived prices is mathematically sound and operationally safe within the context of a specific DeFi primitive.
Quick Facts
Key operational and integration facts about the standard for computing Exponentially-Weighted Moving Average and Time-Weighted Average Price values from the Pyth aggregate price.
| Field | Value | Why it matters |
|---|---|---|
Standard Status | Verify against canonical Pyth Improvement Proposal process | Determines if the calculation is a ratified standard or a draft; affects integration stability and audit scope. |
Core Computation | Derives EMA and TWAP from the streaming aggregate price and confidence interval | Protocols consuming these values must understand the smoothing and windowing logic to parameterize risk correctly. |
Configurable Parameters | Half-life (EMA) and time window (TWAP) | Incorrect parameterization can lead to stale or overly reactive prices, causing failed liquidations or unfair arbitrage. |
Primary Consumers | Lending markets, perpetual protocols, and stablecoins | These DeFi primitives use TWAP/EMA to mitigate manipulation of spot prices for liquidations and funding rates. |
Integration Dependency | On-chain Pyth receiver contract must expose the derived values | A faulty or outdated receiver contract will serve incorrect EMA/TWAP values, regardless of the upstream calculation's correctness. |
Data Freshness | Depends on the frequency of aggregate price updates on the destination chain | A low update frequency can cause the TWAP/EMA to diverge from the true market price, introducing a silent oracle risk. |
Manipulation Resistance | TWAP/EMA are inherently more resistant to single-block manipulation than spot price | This is the primary reason for their use, but the resistance is a function of the window length and update cadence. |
Audit Focus | Correct implementation of the smoothing algorithm and parameter management | The most common integration bug is an off-by-one error in the window or a miscalculation of the decay factor. |
Technical Mechanism
How Pyth Network computes EMA and TWAP values from its streaming aggregate price to serve different DeFi primitives.
The Pyth Network produces a high-frequency, slot-weighted aggregate price and confidence interval from its publisher set. The EMA Price and TWAP Calculation Standard defines how two distinct derived values are computed from this raw stream: an Exponentially-Weighted Moving Average (EMA) and a Time-Weighted Average Price (TWAP). These calculations are performed off-chain by Pyth services and are included as optional fields within a standard Pyth price update message, allowing consuming protocols to select the value best suited to their use case without performing their own on-chain averaging.
The EMA price is computed using a configurable smoothing factor (alpha) that applies greater weight to recent observations, making it responsive to current market conditions while still filtering high-frequency noise. This value is typically preferred by perpetual futures protocols and other derivatives platforms where a lagging oracle could create arbitrage opportunities. In contrast, the TWAP price is calculated as the arithmetic mean of the aggregate price sampled at fixed intervals over a configurable lookback window. This produces a deliberately slower-moving value that is resistant to short-term manipulation, making it the standard choice for lending markets that rely on oracle prices to trigger liquidations. The specification defines the exact mathematical formulas, the configurable parameters (such as the EMA half-life or TWAP window duration), and the expected behavior when the aggregate price stream experiences gaps or stalls.
For integration engineers, consuming these derived values requires parsing the additional fields within the PriceFeed binary structure as defined by the Pyth Price Feed Specification. A consuming protocol's on-chain verification logic must confirm that the EMA or TWAP value is authentic and was computed according to the canonical standard. The standard also clarifies the relationship between the spot aggregate price, the EMA, and the TWAP, helping risk teams understand the expected divergence between these values during volatile market conditions. Chainscore Labs can assist protocol architects in reviewing their oracle consumption logic to ensure that the chosen averaging method aligns with their protocol's risk parameters and that the on-chain verification path correctly validates the derived price's integrity.
Affected Actors
DeFi Protocol Builders
Protocols consuming EMA or TWAP values must audit their integration logic against the canonical calculation standard. The primary risk is a mismatch between the protocol's expected price behavior and the oracle's actual smoothing parameters.
Action Items:
- Verify that the configured half-life or time window aligns with the protocol's liquidation and pricing latency requirements.
- Ensure that stale price checks account for the inherent lag introduced by moving averages.
- For lending protocols, confirm that the chosen EMA/TWAP does not delay liquidations beyond safe collateralization thresholds during high volatility.
- Implement explicit fallback logic if the derived EMA/TWAP feed deviates from the spot aggregate by a governance-defined tolerance.
Chainscore Labs can review your oracle consumption logic to ensure the smoothing parameters match your protocol's economic security model.
Implementation Impact by Use Case
The EMA and TWAP calculation standard introduces new derived values that require specific integration patterns, risk parameter updates, and fallback logic for consuming protocols.
Lending Protocols: Liquidation Thresholds
Lending markets must decide whether to use the aggregate price, EMA, or TWAP for liquidation calculations. Using the raw aggregate price exposes protocols to manipulation via short-term spot volatility, while the EMA provides a smoothed value that resists single-block attacks. Integrators need to update oracle wrapper contracts to expose the EMA value and adjust liquidation thresholds to account for the dampened volatility profile. A stale EMA, however, can lag the true market price during rapid moves, creating bad debt risk. Teams should implement a secondary staleness check comparing the EMA against the current aggregate price and trigger a fallback if the deviation exceeds a governance-set threshold.
Perpetual Futures: Funding Rate Calculation
Perpetual protocols commonly use a TWAP of the index price to calculate funding rates, preventing manipulation of the funding payment at a single timestamp. This standard defines the canonical TWAP calculation, allowing perps engineers to consume a pre-computed value directly from the Pyth oracle rather than maintaining an off-chain TWAP accumulator. The integration requires updating the funding rate contract to call the TWAP function on the Pyth receiver and ensuring the TWAP window parameter matches the protocol's funding interval. A mismatch between the oracle's TWAP window and the protocol's funding period can create arbitrage opportunities that drain the insurance fund.
Stablecoins: Minting and Redemption Pricing
Stablecoin protocols that mint against volatile collateral should use the EMA price for minting and redemption operations to prevent flash loan attacks that temporarily spike the collateral value. The EMA's smoothing effect makes it economically unfeasible to manipulate the price for the duration required to move the average. Implementers must configure the EMA's half-life parameter to be long enough to resist manipulation but short enough to track genuine price declines. A half-life that is too long can allow undercollateralized minting during a sustained drawdown, while a half-life that is too short provides insufficient manipulation resistance. Risk teams should backtest the chosen parameter against historical volatility events.
Options Protocols: Settlement Price Determination
European-style options require a reliable settlement price at expiry. The TWAP over a defined window before expiry is the industry standard for preventing manipulation of the settlement print. This standard provides a canonical on-chain TWAP that options protocols can consume directly, eliminating the need for a separate oracle or manual settlement process. The integration requires the options contract to record the TWAP value at the exact expiry timestamp and use it for all settlement calculations. Protocols must ensure the TWAP window used for settlement is aligned with the oracle's configured window and that the expiry timestamp is synchronized with the oracle's clock to avoid disputes.
Risk Monitoring: Deviation Alerts
Risk teams should build monitoring that compares the EMA price against the raw aggregate price in real time. A significant and sustained deviation between the two signals an impending volatility event or a potential manipulation attempt. The standard defines the exact calculation, allowing monitoring systems to replicate the EMA off-chain and trigger alerts when the deviation exceeds a configurable threshold. This is particularly critical for protocols that use the aggregate price for some operations and the EMA for others, as a divergence can create cross-function arbitrage. Chainscore Labs can assist with designing deviation thresholds and integrating Pyth EMA monitoring into existing risk dashboards.
Cross-Chain Deployments: Consistent Parameterization
Protocols deployed across multiple chains must ensure that the EMA half-life and TWAP window parameters are identical on every deployment. Inconsistent parameters create cross-chain arbitrage where the same asset is priced differently on different chains, leading to value extraction from the protocol. The standard defines the parameters as part of the on-chain configuration, but governance must ratify them consistently. A deployment checklist should include verification that the Pyth receiver contract on each chain exposes the same EMA and TWAP configuration. Chainscore Labs provides cross-chain configuration audits to prevent parameter drift across deployments.
Risk and Compatibility Matrix
Evaluates the operational and integration risks introduced by the EMA and TWAP calculation standard for protocols consuming derived Pyth price values.
| Area | What changes | Who is affected | Action |
|---|---|---|---|
Lending Protocols | Shift from spot to EMA/TWAP for collateral valuation | Risk managers, protocol architects | Recalibrate loan-to-value ratios and liquidation thresholds using the new confidence interval characteristics |
Perpetual Futures | Funding rate calculation may depend on a TWAP or EMA of the index price | Derivatives protocol engineers | Verify funding rate formula compatibility with the new calculation standard and update off-chain keeper logic |
On-Chain Verification | New derived values are not part of the core signed price update; they require off-chain computation | Smart contract developers | Do not attempt to verify EMA/TWAP values on-chain without a trusted relayer or oracle compute solution |
Data Relayers | Hermes or custom relayers must implement the new calculation logic before serving EMA/TWAP values | Relayer operators, infrastructure teams | Update relayer software to the canonical implementation and monitor for calculation drift against the specification |
Backtesting Systems | Historical EMA/TWAP values must be recomputed from raw aggregate prices using the new standard | Quantitative analysts, risk teams | Rebuild historical datasets using the specified parameters to avoid look-ahead bias in backtesting |
Fallback Oracles | Secondary oracles may not provide a compatible EMA/TWAP, causing a mismatch during failover | DeFi protocol architects | Design fallback logic that defaults to a spot price with a wider staleness tolerance when derived values are unavailable |
Governance Parameter Setting | Configurable parameters like half-life windows can be changed via governance | Governance delegates, risk councils | Monitor governance proposals for parameter changes and assess the impact on downstream protocol risk models |
Integration Readiness Checklist
A technical checklist for protocol engineers integrating Pyth's EMA and TWAP price feeds. Each item confirms that your smart contracts correctly consume, validate, and act on these derived values, preventing mispricing, stale data usage, and manipulation vulnerabilities.
What to check: Confirm that the specific price feed ID you are consuming has EMA and TWAP values published by the Hermes relay. Not all feeds may have these derived values available.
Why it matters: Assuming availability without verification can lead to transaction reverts or fallback oracle usage when the expected data field is empty.
Readiness signal: Query the Hermes /v2/updates/price/latest endpoint for your feed IDs and confirm the presence and non-zero values of ema_price and twap fields in the response payload.
Source Resources
Canonical and implementation-facing resources for teams validating EMA price and TWAP behavior against Pyth price feeds, receiver contracts, historical data, and governance changes.
Historical Price and Benchmark Data
TWAP validation requires a historical reference set, not only latest-price reads. Teams should compare their windowing, sampling, and interpolation rules against Pyth’s available historical or benchmark data sources where applicable. This is especially important for perps funding, lending collateral haircuts, settlement prices, and backtests that assume a continuous price series. Risk teams should record how missing updates, delayed publication, or outlier confidence intervals are handled in the derived calculation.
Looking to build on a specific blockchain?
We build smart contracts, DeFi applications, wallets, tokenization platforms, and blockchain infrastructure across the major ecosystems teams choose today. That includes Ethereum, Arbitrum, Optimism, Polygon, Avalanche, Solana, Sui, Aptos, Hedera, Stellar, and NEAR, with support for additional EVM and non-EVM networks based on your product requirements.
EVM ecosystems
- Ethereum
- Arbitrum
- Optimism
- Polygon
- Avalanche
- Cronos

Non-EVM ecosystems
- Solana
- Sui
- Aptos
- Hedera
- Stellar
- NEAR
Additional ecosystems
- Polkadot
- Cosmos
- TON
- Cardano
- Algorand
- Tempo
Also available for Base, appchains, custom EVM networks, and cross-chain product architecture.
Frequently Asked Questions
Common questions from protocol architects and engineers about consuming, verifying, and parameterizing Pyth's EMA and TWAP values.
The Exponentially-Weighted Moving Average (EMA) is computed by applying a recursive smoothing formula to the streaming aggregate price. Each new aggregate update is blended with the previous EMA value using a smoothing factor determined by a configurable half-life parameter.
Key operational details:
- The calculation is performed off-chain by the Pyth publisher network and included in the signed price update payload.
- The half-life window defines how quickly the EMA reacts to price changes. A shorter half-life makes the EMA more responsive; a longer half-life provides greater smoothing.
- The EMA value is delivered alongside the spot aggregate price and confidence interval in the same on-chain update.
Integration check: Verify that your consuming contract reads the correct field from the PriceFeed struct. The EMA value is a separate field from the spot price and must not be used interchangeably without understanding the smoothing lag.
Delivering blockchain solutions for 5+ years.
We have partnered with 50+ leading DeFi protocols, NFT ecosystems, and fintech innovators to build secure, scalable, and capital-efficient blockchain products.
Selected Partners & Clients
“I've been working with Chainscore Labs for last 3+ years, they've consistently delivered with strong ownership across multiple projects. The team is reliable and detail-oriented.”
How to get started?
If you're looking for blockchain integration, ChainScore Labs has 5+ years of experience helping teams build and integrate exchanges, wallets, smart contracts, tokenization solutions, and protocol-connected products, we can help you choose the right path, integrate securely, and get to production faster. Our team consists of experienced blockchain developers and architects who can help you with your blockchain integration needs.
Exploration & Strategy
Define your product goals and choose the right blockchain architecture for your use case.
Architecture & Design
Design the smart contracts, tokenomics, and security parameters of your system.
Development & Integration
Build and integrate with wallets, oracles, and front-end dApps for a seamless experience.
Security & Launch
Comprehensive audits followed by a risk-managed mainnet deployment to protect your users.
Discover our
blockchain development services.
We build production-grade blockchain solutions for top-tier projects across DeFi and Web3.
Need a blockchain engineering team?
Send the project context and we will respond with next steps, scope questions, and a practical path to delivery.


