6

Are there any oracles available for Bitcoin price? I'd like to do a currency conversion math inside the smart contract code.

8

Thomas from Oraclize here.

One simple yet quite secure way to get a Bitcoin reference price into your contract is to use existing exchanges as datasources thanks to their APIs. I suppose here that what you want is BTCUSD, if it was BTCETH instead than minor code changes are required but the same reasoning applies.

Doing that in Solidity via Oraclize is trivial, I would suggest not to rely on a single exchange only, but for simplicity reasons the example that follows is using just one (Kraken).

I think the following code is self explanatory, but in case you have any questions feel free to ask here or via our support channels (gitter, email, ..).

/*
   Kraken-based ETH/USD price ticker

   This contract keeps in storage an updated ETH/USD price,
   which is optionally updated every ~60 seconds.
*/

pragma solidity ^0.4.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract KrakenPriceTicker is usingOraclize {

    uint public ETHUSD;

    event newOraclizeQuery(string description);
    event newKrakenPriceTicker(string price);

    function KrakenPriceTicker() {
        // FIXME: enable oraclize_setProof is production
        // oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        update(0);
    }

    function __callback(bytes32 myid, string result, bytes proof) {
        if (msg.sender != oraclize_cbAddress()) throw;
        newKrakenPriceTicker(result);
        ETHUSD = parseInt(result, 2); // save it in storage as $ cents
        // do something with ETHUSD
        // update(60); // FIXME: comment this out to enable recursive price updates
    }

    function update(uint delay) payable {
        if (oraclize_getPrice("URL") > this.balance) {
            newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
        } else {
            newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
            oraclize_query(delay, "URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0");
        }
    }

} 

You can see this in action here thanks to the Oraclize browser-solidity integration, just click on the link and click on the contract "Create" button on the panel you find on the right!

Oraclize Kraken Price Ticker Example

  • What additional exchanges do you recommend? And do you recommend taking a median value? Or, alternatively, say the highest ask (if buying) or lowest bid (if selling)? – Mowzer May 8 '18 at 12:48
  • At that link, I don't see a "create" button on the panel to the right. I only see several error messages. – Mowzer May 8 '18 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.