Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement Pyth Network Feeds for High-Frequency Market Data

This guide provides a technical walkthrough for integrating Pyth Network's pull-based oracle to fetch and verify low-latency price data for financial forecasting applications like binary options and derivatives.
Chainscore © 2026
introduction
DEVELOPER TUTORIAL

How to Implement Pyth Network Feeds for High-Frequency Market Data

This guide explains how to integrate Pyth Network's low-latency price feeds into a prediction market application, covering data sourcing, on-chain verification, and high-frequency update strategies.

Pyth Network is a first-party oracle protocol that delivers high-fidelity, low-latency financial market data directly to blockchains. Unlike traditional oracles that aggregate data from centralized exchanges, Pyth sources price data directly from over 90 primary sources, including major trading firms and exchanges like Jane Street and Binance. This direct sourcing model reduces latency and provides a verifiable data trail for each price update, which is critical for prediction markets where the accuracy and timeliness of information directly impacts market fairness and settlement.

To implement a Pyth feed, you first need to interact with the Pyth Price Service API for off-chain price retrieval and the on-chain Pyth Solana or EVM program for verification. The typical integration flow involves: 1) Querying the Pyth Price Service for the latest price feed for an asset (e.g., Crypto.BTC/USD), 2) Fetching the corresponding on-chain price account or contract, and 3) Submitting the price attestation along with a VAAs (Verifiable Action Approvals) signature for validation. This dual-step process ensures the data you use is both current and cryptographically proven to be from Pyth's publishers.

For high-frequency applications, you must manage update intervals and staleness. Pyth publishes major cryptocurrency prices on Solana every 400ms and on EVM chains as frequently as block times allow. Your smart contract should check the publish_time in the price feed and define a maximum acceptable age (e.g., 5 seconds) before considering a price stale. Here's a basic Solana Anchor example for reading a price:

rust
let price_account_info = next_account_info(account_info_iter)?;
let price_data = load_price_feed_from_account_info(price_account_info).unwrap();
let current_price = price_data.get_current_price().unwrap();
assert!(Clock::get()?.unix_timestamp - price_data.publish_time < 5); // Staleness check

Optimizing for cost and speed requires choosing the right update strategy. For prediction markets, you may not need to update your contract state with every Pyth publish. Instead, implement a heartbeat or deviation-based update logic. Update the on-chain reference price only when the off-chain price moves beyond a specified percentage threshold (e.g., 0.5%) or at regular intervals (e.g., every minute). This reduces gas costs while maintaining sufficient accuracy for market resolution. You can listen for Pyth price updates via their WebSocket stream to trigger these conditional updates.

Security best practices are paramount. Always verify the price confidence interval provided with each update, which represents the publishers' uncertainty. For critical settlement functions, require the price to be within a narrow confidence band. Furthermore, design your market to be pausable in the event of a Pyth governance-initiated emergency shutdown or if a price feed is identified as compromised. Relying on a single oracle point can be risky; for high-value markets, consider a fallback mechanism or using Pyth in conjunction with a decentralized oracle network like Chainlink for critical final price resolution.

To get started, visit the official Pyth Documentation for the latest client libraries (Python, JS), SDKs, and a list of all available price feeds. Test your integration on Pythnet or a devnet before mainnet deployment. By leveraging Pyth's high-frequency data and robust verification, prediction markets can achieve faster, more accurate settlements that reflect real-world market conditions, enabling novel products for events, sports, and volatility trading.

prerequisites
IMPLEMENTING PYTH NETWORK

Prerequisites and Setup

This guide details the technical requirements and initial configuration needed to integrate Pyth Network's high-frequency market data into your on-chain application.

Before writing any integration code, you must establish a development environment capable of interacting with the Solana blockchain and Pyth's on-chain programs. The core prerequisites are a Solana-compatible wallet (like Phantom) with devnet SOL for gas fees, the Solana Command Line Tools (CLI) for program interaction, and a Node.js environment (v16+) for running JavaScript/TypeScript examples. You will also need a basic understanding of Solana's account model and the concept of Program Derived Addresses (PDAs), as Pyth data is stored in specific on-chain accounts.

The primary method for accessing Pyth data on-chain is through its Solana program, which publishes price feeds to a collection of accounts. You need the program's address and the specific Product and Price account addresses for the asset you want to query. For development, use Pyth's devnet deployment. Key addresses include the mainnet program FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH and devnet program gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s. You can find a full list of active price feed account addresses in the Pyth Network Price Feed Accounts documentation.

For off-chain price retrieval or monitoring, Pyth provides the Hermes HTTP API and WebSocket streams. Setting this up requires no blockchain interaction, only an HTTP client library like axios or fetch. The base URL for the mainnet Hermes API is https://hermes.pyth.network. This API is ideal for back-end services, dashboards, or fetching historical data before submitting an on-chain transaction that depends on a recent price attestation.

Your smart contract or client must be able to parse the data structure of a Pyth Price Account. The account data is not a simple integer; it's a serialized struct containing fields like price, conf (confidence interval), expo (exponent for scaling), publish_time, and prev_price. In Solana programs written in Rust, you will use the pyth-sdk-solana crate to deserialize this data. For TypeScript clients, the @pythnetwork/client npm package provides helper functions like getPriceFromAccountData.

Finally, ensure your application handles the decentralized nature of the data. Pyth prices are updated by a network of publishers, typically every 400ms on Solana mainnet. Your logic should check the publish_time to ensure the price is fresh enough for your use case and consider the conf field, which represents the +/- uncertainty of the price, for risk management. A common pattern is to reject prices older than a certain threshold (e.g., 30 seconds) to prevent using stale data.

key-concepts-text
CORE CONCEPTS

How to Implement Pyth Network Feeds for High-Frequency Market Data

A technical guide for developers on integrating Pyth Network's low-latency price feeds to access real-time financial data on-chain.

Pyth Network is a specialized oracle protocol designed to deliver high-frequency market data directly to smart contracts. Unlike general-purpose oracles that aggregate data from multiple sources, Pyth sources price data directly from over 90 first-party publishers, including major trading firms and exchanges like Jane Street, CBOE, and Binance. This architecture minimizes latency and maximizes data integrity, making it the preferred solution for DeFi applications requiring precise, real-time pricing for assets like crypto, equities, FX pairs, and commodities. The data is aggregated and published on-chain as price feeds that update multiple times per second.

At the heart of Pyth's data delivery is the attestation model. Publishers sign price updates with their private keys, creating a verifiable cryptographic proof of the data's origin and integrity. These signed messages, or attestations, are submitted to the Pythnet appchain. The protocol's consensus mechanism then aggregates these individual attestations into a single authoritative price and confidence interval, which is published to supported blockchains like Solana, Ethereum, and Sui via Wormhole cross-chain messaging. This process ensures that the final on-chain price is tamper-resistant and reflects a broad market consensus.

To implement a Pyth feed, developers interact with the PythPriceFeed contract on their target chain. The core function is getPrice(), which returns the latest price and confidence data. For high-frequency applications, it's critical to also check the getValidTimePeriod() to ensure the price is not stale. Here's a basic Solidity example for fetching the BTC/USD price on Ethereum:

solidity
// Import the IPyth interface
import "@pythnetwork/pyth-sdk-solidity/IPyth.sol";
import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";

contract MyContract {
    IPyth pyth = IPyth(PYTH_ETH_MAINNET_ADDRESS);
    bytes32 btcPriceId = 0xf9c0172ba10dfa4d19088d94f5bf61d3b54d5bd7483a322a982e1373ee8ea31b;

    function getBtcPrice() public view returns (PythStructs.Price memory) {
        return pyth.getPrice(btcPriceId);
    }
}

For production use, you must handle price staleness and confidence intervals. The returned Price struct contains price, conf (confidence interval), expo (exponent), and publish_time. Always validate that block.timestamp - publish_time is within your application's allowed staleness threshold. The confidence interval represents the publisher's uncertainty; applications like perps may reject updates if conf is too large relative to price. Consider using Pyth's pull oracle design, where you request an update via updatePriceFeeds() and pay the fee, to guarantee fresh data for critical operations like liquidations.

Accessing feeds requires the correct Price Feed ID, a unique identifier for each asset pair. You can find IDs for all feeds in the Pyth Price Feed Directory. The Pyth SDKs for JavaScript, Python, and Solidity simplify integration. For advanced use, such as building a keeper bot, subscribe to the Pyth's real-time WebSocket stream for off-chain price updates to monitor markets and only submit on-chain updates when a threshold is breached, optimizing for cost and speed.

FEED COMPARISON

Pyth Price Feed Attributes and Use Cases

Key attributes of Pyth's primary price feed types and their typical on-chain applications.

Attribute / MetricPyth Mainnet (SOL/USD)Pyth Benchmarks (BTC/USD)Pyth Express (ETH/USD)

Update Frequency

< 400ms

~ 1-2 seconds

< 100ms

Confidence Interval

± $0.01

± $10

± $0.50

Publisher Count

40+

25+

15+

Primary Use Case

General DeFi (Lending, DEX)

Settlement & Derivatives

High-Freq Trading & Liquidations

On-Chain Program

Pyth Oracle

Pyth Benchmark

Pyth Express

Data Latency (Pull to On-Chain)

Cross-Chain Availability

Typical Update Cost (Solana)

$0.0001 - $0.001

$0.0005 - $0.005

$0.01 - $0.05

on-chain-verification
ON-CHAIN PRICE VERIFICATION LOGIC

How to Implement Pyth Network Feeds for High-Frequency Market Data

Integrate low-latency, institutional-grade price data directly into your smart contracts using Pyth Network's pull oracle model.

Pyth Network provides high-fidelity financial market data on-chain, aggregating price feeds from over 90 first-party publishers including major exchanges and trading firms. Unlike traditional push oracles that broadcast data at intervals, Pyth uses a pull oracle model. This means your smart contract actively requests the latest price when needed, paying a small fee for the on-demand update. This model is ideal for high-frequency applications like perpetual futures, options pricing, and liquidations, where data freshness is critical. The core data resides on Pythnet, a dedicated Solana-based appchain, and is made available to other chains via the Wormhole cross-chain messaging protocol.

To use a Pyth price feed, your contract must interact with the Pyth Price Feed contract deployed on your target chain. First, you need the priceFeedId for your desired asset pair (e.g., 0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace for BTC/USD). You can find these IDs in the Pyth Price Feed Addresses documentation. The primary function is getPriceNoOlderThan(priceId, age), which returns a price struct if an update exists within the specified age threshold (in seconds), otherwise it reverts. This ensures you don't use stale data.

Here is a basic Solidity example for fetching the BTC/USD price on Ethereum:

solidity
// Import the IPyth interface
import "@pythnetwork/pyth-sdk-solidity/IPyth.sol";
import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";

contract MyOracleUser {
    IPyth pyth;
    bytes32 btcPriceId = 0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace;

    constructor(address pythContract) {
        pyth = IPyth(pythContract);
    }

    function getBtcPrice() public view returns (PythStructs.Price memory) {
        // Require price updated within the last 60 seconds
        return pyth.getPriceNoOlderThan(btcPriceId, 60);
    }
}

The returned Price struct contains the price price, its confidence interval conf, the expo (exponent), and the publishTime.

For production use, you must handle the returned data correctly. The price and conf (confidence) are integers. To get a human-readable price, you calculate: price * (10 ^ expo). A negative exponent is typical; for USD pairs, expo is often -8, meaning you divide the price integer by 100,000,000. Always check the conf value, which represents the publisher-aggregated uncertainty. A high confidence interval relative to the price may indicate volatile or unreliable market conditions. You should implement logic to revert if confidence exceeds a safe threshold for your application.

To update a price on-chain, you must submit a price update VAAs (Verified Action Approvals) from Pythnet. This is typically done by calling pyth.updatePriceFeeds(vaaData) with the signed VAA payload. In practice, most developers rely on Pyth's off-chain service, the Hermes Relayer, which automatically posts these updates. For mainnet deployments, you can use the public RPC endpoint or run your own relayer for higher reliability. The update fee is paid in the native gas token of the destination chain and is generally minimal, often less than a cent per update on L2s.

Key considerations for implementation include gas optimization and data freshness. Use getPriceNoOlderThan with the shortest acceptable staleness window for your use case. For latency-sensitive protocols, you may need to subsidize update fees for users or batch multiple price requests into a single transaction. Always verify the publishTime in the price struct against your staleness tolerance. Pyth's design minimizes trust assumptions by using multiple publishers and on-chain aggregation, but your contract logic must still define acceptable parameters for price age and confidence to ensure robustness.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now integrated Pyth Network's high-frequency, low-latency market data into your application. This guide covered the core concepts and practical steps for a robust implementation.

Successfully implementing Pyth Network feeds provides your DeFi protocol, trading bot, or analytics dashboard with a critical competitive edge: access to institutional-grade, cross-chain price data updated multiple times per second. The key to a reliable integration is understanding the data flow—from the Pythnet aggregator to the target blockchain via the Wormhole protocol—and correctly handling the PriceFeed object's price, conf, and expo fields to compute the final, confidence-weighted value. Always verify the publish_time and check the attestation service status on the Pyth Data Explorer to ensure data freshness and validity.

For production applications, consider these advanced strategies to enhance robustness. Implement a fallback oracle mechanism (e.g., Chainlink) to hedge against potential Pyth data unavailability. Use the ema_price and ema_conf fields for smoother, less volatile price feeds in certain calculations. For maximum gas efficiency on EVM chains, explore using the Pyth Entropy service for verifiable randomness or the Pyth Pull Oracle model, where updates are fetched on-demand rather than pushed, which can significantly reduce costs for less time-sensitive data.

Your next steps should focus on security and optimization. Thoroughly test your integration on a testnet using the Pyth Price Service and monitor for any discrepancies. Review and implement access control for functions that update critical price feed IDs. For scaling, analyze the gas costs of your update logic and consider batching updates or using Layer 2 solutions. Join the Pyth Discord to stay updated on new data products, network upgrades, and best practices shared by the developer community.

How to Implement Pyth Network Feeds for High-Frequency Market Data | ChainScore Guides