How To Get Real Time Crypto Market Data

Using the Kucoin Exchange API #HowToBUIDL (7/n)

In the previous article, we focused on obtaining approximate price data for just about any cryptocurrency or ERC20 token listed on any exchange. Some people in crypto don’t necessarily need the most up-to-date data, so the article on using the CoinMarketCap API might suffice. It provides “good enough” data to give people some sort of idea on the overall market. For those that are trying to actually build businesses that exchange tokens for goods and services, run stores that sell items for crypto, or active traders, CMC is simply not good enough. The longer you stay in crypto, at some point you’re going to need more accurate data. To get this information, you need a market data service provider, or even more directly, an exchange itself.

For this set of code examples, we’ll look at #BUIDLing a command line tool or custom web app for requesting current trade data from the Kucoin API. You might even be so bold as to create a custom AirSwap Team maker, so that you can integrate with the #decentralized market tool that allows you to securely participate in atomic swaps. “AirSwap is not just a marketplace, but a secure consumer token trading network that can only exist with a truly decentralized peer-to-peer protocol. When you buy and sell on AirSwap, you’re doing so with others around the world, wallet-to-wallet, between a buyer, a seller, and a smart contract. No friction, no custody, no fees.”

Market makers provide liquidity by suggesting exchange rates for one quantity of token versus another, and takers accept the bids or offers, creating a sort of atomic token swap that would not really be possible without the current centralized options of performing two different trades versus BTC. Now, if you wanted to create your own Maker for AirSwap, you better have some information about current market prices, so we’ll look into how you might go about getting that info with Kucoin.

AirSwap was built from the ground up with market makers in mind. We’ve published Swap Protocol clients for both JavaScript and Python, with quick start guides coming soon. — Don Mosites

Kucoin is a Chinese digital currency exchange based in Hong Kong. I’m choosing it for this example because it is often easier or more affordable to list a coin here than something like Binance, and as a result, contains some of the coins I’ll be using for my examples. In addition, it seems to be one of the more reliable exchanges, hasn’t suffered any security breaches to my knowledge. As an added bonus, Kucoin offers profit-sharing of fees with their KCS token holders, so there are user incentives to hold tokens as passive dividend income. That’s a bit of a rarity among centralized crypto exchanges. Let’s get started.

Let’s install the open source javascript RESTful API wrapper for Kucoin.

I’m using a forked version of the satoshinaire/kucoin-api.

The full API documentation can be read here.

Special thanks to Satoshinaire for his API wrapper!

npm install kucoin-api

Now that it’s available in our project, obtain a reference to the library, and instantiate an instance of the API object.

Kucoin = require("kucoin-api");

kucoin = new Kucoin(); // read only, not passing in API (key,secret)

Exploring the API

Let’s obtain a list of all available coins with the async getCoins function.

kucoin.getCoins();

coins = _;

Now let’s inspect it. We’ll see the same 177 coins in the list as on the site.

coins.data.length; //177

locicoin = coins.data.filter(c=> c.coin==’LOCI’)[0];

{ withdrawMinFee: 4, coinType: 'ERC20', withdrawMinAmount: 10, withdrawRemark: null, orgAddress: null, txUrl: 'https://etherscan.io/tx/{txId}', userAddressName: null, withdrawFeeRate: 0.001, confirmationCount: 12, infoUrl: null, enable: true, name: 'LOCIcoin', tradePrecision: 4, depositRemark: null, enableWithdraw: true, enableDeposit: true, coin: 'LOCI' }

That JSON representation of LOCI tells us a few interesting things. We can determine it is an ERC20 coinType , you must have a minimum of 10 in order to withdraw, there is a 4 coin withrawMinFee for any transfers out of the exchange, and any transfers into the exchange must wait 12 confirmationCount in order for any balances to be counted.

kucoin.getLanguages(); { success: true, code: 'OK', msg: 'Operation succeeded.', timestamp: 1531253711223, data: [ [ 'en_US', 'English', true ], [ 'ru_RU', 'русский', true ], [ 'ko_KR', '한국어', true ], [ 'pt_PT', 'Portugues', true ], [ 'zh_CN', '中文简体', true ], [ 'nl_NL', 'Nederlands', true ], [ 'zh_HK', '中文繁体', true ], [ 'de_DE', 'Deutsch', true ], [ 'fr_FR', 'Français', true ], [ 'es_ES', 'Español', true ], [ 'vi_VN', 'Tiếng Việt', true ], [ 'tr_TR', 'Türkçe', true ] ] } languages = _;

Hmm. Ok. Kucoin supports (12) languages.length on the site. Great for internationalization. There must be a way to change the user’s preferred language through the API. I took some Spanish es_ES back in my younger years, but for now I’ll leave that alone. US English en_US will do.

While all that is interesting and all, it wasn’t what we came here for. Sometimes simply exploring an API and playing around with it in the code is necessary just to gain your bearings and determine what you can and cannot do with a chunk of code. Junior developers often don’t understand that “software development” isn’t just banging out precise code all day. It involves exploration, planning, navigating code, certainly writing, but a lot more reading of code you didn’t write, and often those that did are no longer with the company. That’s all part of the experience you build up by checking out other projects and learning how to navigate new-to-you codebases.

Exchange Rates for Papa Bitcoin

There’s a function called getExchangeRates . That sounds like something we might really be interested in.

kucoin.getExchangeRates();

xrates = _;

Now xrates.data.currencies contains an array list of [name,symbol] pairs.

[[ 'USD', '$' ], [ 'EUR', '€' ], [ 'AUD', '$' ], ... ]

and xrates.data.rates contains a property for BTC that is a mapping of those currencies to the value in that currency:

BTC : { /*...*/ EUR: 5442.33, DKK: 40570.1, USD: 6380.3, /*...*/ }

Now, these exchange rates are moving around constantly, so I can’t really grab an exact screenshot from when I pulled the rates, but if I look at what Bitstamp is reporting for the BTC/USD rate, it’s ~6380 there as well. Since Kucoin doesn’t really have USD fiat trading pairs, the closest you’d be able to get is comparing BTC/USDT, which is the pair with the “stable coin” called USDT or Tether.

bitcoinwisdom.com/markets/bitstamp/btcusd

So, if you had a ticker that was priced in BTC, like LOCI/BTC, you could take the current price times the xrates.data.rates.BTC.USD and obtain the US Dollar equivalent price.

Trading Pairs and Price Data

So how would we go about finding the trading symbol pairs that are available through the Kucoin Exchange API? Well, there’s a getTradingSymbols function. This goes one step further than just getCoins . Not every single coin has all BTC , ETH , NEO , USDT , and KCS pairs. Most have just BTC & ETH.

kucoin.getTradingSymbols();

symbols = _; symbols.data.length; // 353



You’d see this graphically on the Kucoin website on the Markets screen.

https://www.kucoin.com/#/markets

So we can see there are more tradingSymbols pairs than coins, and we’d expect that. From our earlier getCoins example, locicoin is a coin, whereas

locipairs = symbols.data.filter( s=> s.coinType === locicoin.coin );

is a set of all pairs for locicoin.coin (coin property is 'LOCI' ).

[

{ coinType: 'LOCI', trading: true, symbol: 'LOCI-BTC', lastDealPrice: 0.00000517, buy: 0.00000457, sell: 0.00000514, change: -7e-8, coinTypePair: 'BTC', sort: 100, feeRate: 0.001, volValue: 0.09000668, high: 0.00000552, datetime: 1531255308000, vol: 18075.6256, low: 0.00000452, changeRate: -0.0134 }, { coinType: 'LOCI', trading: true, symbol: 'LOCI-ETH', lastDealPrice: 0.00008, buy: 0.0000675, sell: 0.000081, change: 0.000007, coinTypePair: 'ETH', sort: 0, feeRate: 0.001, volValue: 1.55628934, high: 0.00008, datetime: 1531255308000, vol: 20357.2562, low: 0.0000652, changeRate: 0.0959 }



]