TWAP vs. VWAP Price Algorithms

Definition
DEFINITION

TWAP and VWAP are different methodologies for calculating asset prices used across the DeFi ecosystem.

Time-weighted average price (TWAP) and volume-weighted average price (VWAP) algorithms apply different methodologies for calculating asset prices, an integral element of almost all decentralized finance (DeFi) primitives.

In this article, we cover the differences between TWAP and VWAP algorithms, explain how they work in the context of pricing assets within blockchain environments, and explore their respective advantages and trade-offs. By making more informed security design choices and leveraging the most secure infrastructure, DeFi protocols can provide users with more accurate, reliable, and fair prices. Knowing the differences between TWAP and VWAP algorithms is a crucial part of this process.  

What is TWAP?

TWAP stands for “time-weighted average price”. It’s a pricing algorithm used to calculate the average price of an asset over a set period.

In DeFi, a type of decentralized exchange (DEX) known as an automated market maker (AMM) can be used to generate TWAP prices that can be used in other protocols. TWAP can also refer to a trading strategy used to execute a large-volume order by breaking it into equal parts across a set period in order to minimize slippage and signaling. In this post, we focus on the pricing mechanism rather than the trading strategy.

How Is TWAP Calculated?

TWAP is calculated by summing prices at multiple points across a set period and then dividing this total by the total number of price points.

Here’s a common TWAP formula:

  • TWAP = (TP1+ TP2… + TPn) / n, where;
  • TP1 is the price at the first timepoint, and
  • n is the total number of timepoints.

For example, imagine we wanted to calculate the TWAP of an asset over one minute using 15-second price point intervals. If the prices were $100 at zero seconds, $102 at 15 seconds, $101 at 30 seconds, $98 at 45 seconds, and $103 at 60 seconds, then to calculate the TWAP we would sum all price points (100, 102, 101, 99, 103) and then divide them by the number of timepoints (five). In this example, the TWAP is $101.

Advantages of TWAP

Simplicity

TWAP is simple to calculate and computationally inexpensive to execute compared to more rigorous pricing mechanisms. This can make them easy to implement on-chain and efficient to run.

Protection Against Flash Loan Attacks

Flash loans are uncollateralized loans that let a user borrow assets and pay them back within the same transaction. This can lead to exploits of dApps using AMM DEXs as a spot pricing mechanism for liquidity pools, where prices are calculated simply by dividing the number of one asset against the other in a two-sided liquidity pool. In this circumstance, malicious actors can borrow large amounts of funds in a single transaction, use them to manipulate the spot price, and attack any smart contracts relying on spot prices derived from that liquidity pool.

By using TWAP to generate prices across multiple blocks from AMM DEXs, protocols can protect themselves from these flash loan attacks.

What is VWAP?

VWAP stands for “volume-weighted average price”. It’s a mechanism used to calculate the price of an asset by taking price data from multiple trading environments and weighting each price by the amount of volume on each liquid market an asset is trading on. A VWAP algorithm underpins the majority of DeFi protocols, as it is used by the industry-leading price oracle solution: Chainlink Price Feeds.

The VWAP calculation methodology is also used more broadly across finance as a technical indicator for traders, an order option offered by brokers or exchanges, and a benchmark. In this article, we focus on its use as a pricing mechanism.

How is VWAP Calculated?

VWAP is calculated by taking the price an asset was traded at from across multiple trading environments and weighting those price points with respect to the volume that was traded on each exchange, with wash trading and other outliers commonly filtered out.

Here’s a common VWAP formula:

  • VWAP = (V1 x P1 + V2 x P2… + Vn x Pn) / Total Volume, where;
  • V1 and P1 are the volume and price an asset was traded at on the first trading environment, and
  • n is the total number of trading environments used in the calculation.

As an example, we’ll calculate the VWAP of a fictional asset across a specific timeframe. Let’s say 100 tokens were traded at a price of $101 on exchange X, 150 tokens were traded at a price of $102 on exchange Y, and 500 tokens were traded at a price of $100 on exchange Z. We first multiply the price by the volume on each trading environment (100 x 101 + 150 x 102 + 500 x 100) and then divide the result by the total volume traded (100 + 150 + 500). We get 75,400 divided by 750, giving us a VWAP of $100.53.

Advantages of VWAP

Market Coverage

VWAP can provide users with a global market price that reflects the asset price across various trading environments, including both small and large exchanges. This works to filter out outliers on lower-liquidity markets that are more susceptible to market manipulation, placing more emphasis on markets where more trading activity takes place. As liquidity shifts across various markets, a market-wide price can still be generated.  

Highly Accurate and Fresh Data

By incorporating data from multiple trading environments, users of VWAP mechanisms are leveraging price data that more accurately reflects the global supply/demand of the asset. Furthermore, the data used is fresher and more up-to-date, allowing VWAP-based price points to closely track the market-wide price of an asset.

Manipulation-Resistant

VWAP algorithms are more resistant to manipulation because they don’t rely on a single trading market that can be manipulated by well-capitalized malicious actors or through flash loan attacks. A malicious actor would have to manipulate the majority of the asset’s trading markets, which would require moving the market-wide price of the asset itself in the process.

Disadvantages of TWAP

While both TWAP and VWAP price mechanisms have certain advantages, TWAP algorithms have a number of disadvantages that make them unsuitable for the majority of DeFi use cases.

Lagging Indicator

TWAP algorithms rely on historical price data, making them an inherently lagging indicator. This lag can lead to prices that are out of sync with market-wide prices during periods of moderate to high volatility and create an opportunity for delayed pricing and exploits. While TWAP calculations can reduce this lag by using price points from a shorter timespan, this would then make it less expensive for a well-capitalized malicious actor to engage in manipulation.

In comparison, VWAP mechanisms can be used to calculate prices based on fresh market data and provide tamper-proof metrics that reflect the latest activity in an asset’s global trading markets.

Market Coverage

Market coverage refers to the number of trading environments that a pricing mechanism takes into account. TWAP algorithms, particularly when performed on-chain, typically rely on data from a single trading environment, meaning they don’t reflect global asset markets that feature a myriad of different centralized and decentralized exchanges.

This problem for TWAP algorithms is especially pertinent in DeFi, as decentralized exchange protocols often have different versions of their DEX operational at the same time in separate instances across multiple chains. As malicious actors only need to manipulate a single exchange to affect a TWAP algorithm, fragmented liquidity across exchanges means they require less capital for an attack to be successful. Furthermore, liquidity can shift over time, so while an exchange used for TWAP data could be liquid one day, there is no guarantee that such liquidity will persist.

A malicious actor would need to manipulate the entire market to affect a VWAP algorithm. That’s because VWAP algorithms can incorporate all of the different trading environments, including both CEX and DEX instances, that an asset trades on, providing more robust asset prices with global market coverage.

Security Scalability

TWAP mechanisms, when computed on-chain, are limited in their ability to increase their security. While extending the time period during which price points are measured would help increase tamper-resistance, this reduces freshness and therefore price accuracy. Essentially, there’s an inverse relationship between the security and accuracy of a TWAP mechanism that makes it impossible to optimize for both at the same time.

The only practical way for traditional on-chain TWAP mechanisms to become more secure is to increase the liquidity/volume on the tracked market, making it more expensive for attackers to compromise.

VWAP algorithms, in the context of providing market data to DeFi applications, can increase their security across many different vectors without impacting their price accuracy. Practical methods of increasing security include integrating more data sources to remove centralization risks and protect against API downtime, leveraging higher quality data providers that remove data outliers and suspicious trading activity, and incorporating cryptoeconomic incentives.

Asset Diversity

DeFi protocols using on-chain liquidity pools to generate TWAP pricing are limited by the assets available for trading on their exchange. This means they will always be limited by the tokens available on the blockchain they’re running on. For example, an Ethereum-based protocol can only generate TWAP prices for ERC-20 tokens priced against other tokens on that network.

Conversely, the Chainlink Network makes it possible for DeFi protocols to leverage VWAP price data for not only native assets from across the Web3 ecosystem, but for a wide range of real-world assets such as currencies, commodities, and synthetic assets, as well as assets priced against fiat currencies directly.

Vulnerable to Multi-Block Attacks

Protocols using on-chain TWAP pricing mechanisms on proof-of-stake blockchains can be vulnerable to multi-block MEV attacks. Instead of manipulating spot prices in an AMM DEX within a single transaction like in a flash loan, these attacks involve malicious actors manipulating prices across two or more consecutive blocks. This is possible because an attacker with a sufficiently large stake will occasionally control the validators assigned to publish two or more consecutive blocks and because the selected validators for future blocks are often known ahead of time.

Leveraging VWAP With Chainlink Price Feeds

While the Chainlink Network is able to support TWAP or any other pricing methodology, Chainlink Price Feeds use a VWAP-based mechanism, as it generates the most accurate, tamper-proof, and reliable market data.

Chainlink Price Feeds are powered by a collection of high-quality data providers that provide VWAP-based pricing on assets to power the DeFi economy with high-quality market data across a wide range of assets, retaining accuracy even during periods of extreme market volatility. This enables users to retrieve the latest pricing data for an asset to use either on-chain in a smart contract or in an off-chain application in a trust-minimized manner.

More specifically, Chainlink Price Feeds are on-chain reference contracts that store both the latest and historical asset prices, which are automatically updated by decentralized oracle networks (DONs) consisting of independent oracle node operators. As blockchains cannot natively access external systems, oracle networks play a key role in the DeFi ecosystem by enabling smart contracts to execute based upon inputs and outputs from the real world.

Chainlink Price Feeds power a wide range of DeFi use cases, including money markets, stablecoins, options, futures, synthetic assets, insurance, and more. As of September 1, 2022, Chainlink Price Feeds have delivered 4.2B data points on-chain, helping secure 1,470+ projects and tens of billions of dollars worth of value.

Chainlink Price Feeds underpin the DeFi economy with decentralized, reliable, and highly accurate market data.
Chainlink Price Feeds underpin the DeFi economy with decentralized, reliable, and highly accurate market data.

Conclusion

Accurate and tamper-proof price data lies at the heart of successful and secure DeFi protocols, helping ensure that users receive a fair price for their assets and malicious actors cannot manipulate prices. For the majority of DeFi use cases, VWAP-based price mechanisms are more suitable than TWAP calculations. With Chainlink Price Feeds, protocols can seamlessly integrate VWAP-based price data that’s hyper-reliable, high-quality, and decentralized at multiple levels in order to better serve users, projects, and the space more broadly.

To learn more, read about how Chainlink Price feeds secure the DeFi ecosystem, explore their use cases, or visit the docs.

Learn more about blockchain technology

Get the latest Chainlink content straight to your inbox.