Logo

dev-resources.site

for different kinds of informations.

Fetch Real-Time Price Data in Solidity

Published at
10/30/2020
Categories
blockchain
solidity
price
stock
Author
patrickalphac
Categories
4 categories in total
blockchain
open
solidity
open
price
open
stock
open
Author
13 person written this
patrickalphac
open
Fetch Real-Time Price Data in Solidity

Introduction

Fetching data from outside Ethereum or whatever blockchain platform is something that most smart contract engineers need to really empower their dApps. Fetching reliable real-time price data in solidity can be the difference between having a powerful DeFi protocol and a quick "Get poor quick" scheme.

We've seen a number of incredibly successful defi projects already pull in real-world price data such as Aave, Synthetix, and yearn.finance. These are protocols at the moment that are securing billions of dollars in the defi space.

Having reliable price data means you can make protocols involving borrowing, lending, trading, synthetic assets, backing collateral, and so much more. Get the price data wrong, and you now have a chance to ruin millions of people's lives.

And just in time for Halloween, a nice spooky platform.

Dex with bad data

I'm having too much fun in this post already.

Price Data Quality

Whether you're fetching your data from a Stock API, Crypto API, or your cousin Larry is uploading coin prices for you, you're going to want to know where your price data is coming from, and you'll want to have that data decentralized if you're going to put it in a smart contract.

So if Larry really wants to be the price oracle for you, just make sure he isn't the only one to do it.

In our smart contracts, we need the data to be decentralized, otherwise we might as well just not build the application in blockchain. Having a centralized data provider in a decentralized system defeats the purpose of building on a decentralized platform in the first place!

So we want to pull from a network of Chainlink oracles to keep our data reliable and decentralized, and have the network pull data from multiple Cryptocurrency API and (if we want another asset class) Stock API providers.

There are currently two approaches, each approach involves using a blockchain oracle.

1. Chainlink Price Feeds

Chainlink Price Feeds are the easiest, most decentralized, and reliable way to fetch real-time price data in your solidity smart contracts. They pull data in from a network of Chainlink nodes and update and aggregate an answer on chain. You can see the responses of all the nodes so you know if any is being malicious.

The function to get the data is just a simple view function as well, so you don't even need to spend any gas to fetch the most recent price!

Here is a sample of how to get the latest ETH/USD price on Kovan, you can try deploying it on remix with this link.

pragma solidity ^0.6.7;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Kovan
     * Aggregator: ETH/USD
     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
     */
    constructor() public {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // If the round is not complete yet, timestamp is 0
        require(timeStamp > 0, "Round not complete");
        return price;
    }
}
Enter fullscreen mode Exit fullscreen mode

Once you deploy the contract on kovan, you can just call the getLatestPrice function, and boom, you've just fetched the price data!

This works because we know the proxy contract of the currency pair. We can find a list of supported pairs in the chainlink documentation. We can even get the fast gas price in solidity! Meaning, inside your smart contracts you can estimate how much it will cost in gas to make a certain execution.

The feeds.chain.link page has a number of visualizations to show more information on the price pairs, included when it was last updated, what the nodes are responding with, gas costs, and more.

Fetch price data from Chainlink Price Feeds

2. Chainlink API Calls

If you've read my previous blog on getting off-chain data in ethereum, you know that with Chainlink you can access any API of data source.

It's no different for fetching price data, you simply make several decentralized Chainlink API calls, and aggregate them on chain. If you haven't made a Chainlink API call before, I recommend either checking out my last blog or going through the example walkthrough.

Click here for a demo on remix that shows you how to get stock price data from Alpha Vantage on Ropsten.

You'd want to do this multiple times with multiple nodes and data providers to make sure that it's decentralized. If you do this, you'll basically have yourself a price feed.

Summary

These are some of the tools a number of the defi giants use to get data into their protocols. Let's see what you build out there! Be sure to ping me at @patrickalphac on twitter once you do, we'd love to see what you've built!

Also, join the Chainlink developers discord to join the community, learn, and grow!

stock Article's
30 articles in total
Favicon
How Forex Quotes Live Enable Better Risk Management
Favicon
How to Access Detailed Live Stock Charts
Favicon
FINQ's weekly market insights: Peaks and valleys in the S&P 500 - May 9, 2024
Favicon
The โ€˜What Couldโ€™ve Beenโ€™ Calculator: A Tale of Stocks and Time
Favicon
Beginner's Guide: ETF Investment Strategies
Favicon
Pros and Cons of Forex Investment
Favicon
Master Stock Trading: Top Stock Market Courses in Bangalore with SMM
Favicon
StockCake - Captivating Free Images for Every Occasion!
Favicon
Best Website to View Stock Charts in 2024
Favicon
How to Backtest a Stock Trading Strategy in 2024?
Favicon
What is a Stock Market Design Portfolio?
Favicon
[Review] Seeking Alpha: Stock Analysis Platform
Favicon
Test Before You Invest: The Art of Portfolio Backtesting
Favicon
How Does the Stock Market Work
Favicon
7 Use Cases For Cryptocurrency
Favicon
EOD Stock Market API for developers
Favicon
Stock Tracker [ A web app to track the real-time stock market data ]
Favicon
Best Stock Market APIs (with sample code)
Favicon
How to Build a Stock Trading App In 2023
Favicon
Rivian stock price prediction 2023 | Rivian stock Forecast
Favicon
what is protraders
Favicon
Magento2 stock update via REST API
Favicon
The Only stock resources library you will ever need.
Favicon
Do you guys invest in the stock market? What broker do you use? What strategy do you follow? What stocks do you invest in?
Favicon
Magento 2 product saleable quantity
Favicon
Best Sites With High Quality Free Stock Photos
Favicon
Lucid Stock
Favicon
Fetch Real-Time Price Data in Solidity
Favicon
Stock charts with fl_chart library
Favicon
TICKER SEARCH API

Featured ones: