Coinmarketcap API


#1

Can someone make a tutorial on how to use the coinmarketapi with javascript
and teach us how to import charts on websites

I can display the price with php but i cant fgure out how to uarse the cmc api in javascript


#2

Hi @yayo, sorry but I don’t have a tutorial, but check out the following:-

There’s a nice node.js library for accessing the cmc api:
https://www.npmjs.com/package/node-coinmarketcap

The ticker data can be parsed and plotted using CanvasJS (a great little free js graphing toolkit):


(There are loads of CanvasJS code examples online, and of course tutorials on Youtube).

Also, the cmc ticker widget can be used quite simply. It doesn’t update in real-time (I don’t think), but with some css styling it can look ok; maybe even make your own dashboard. E.g.:

<!doctype html>
<html>
  <head>
   <title>CMC Widgets</title>
   <script type="text/javascript" src="https://files.coinmarketcap.com/static/widget/currency.js"></script>
   <style>
    .coinmarketcap-currency-widget {        
        width: 33%;
        margin: 30px auto;        
    }
   </style>
  </head>
  <body>

    <div class="coinmarketcap-currency-widget" data-currency="bitcoin" data-base="USD" ></div>
    <div class="coinmarketcap-currency-widget" data-currency="ethereum" data-base="USD" data-secondary="BTC"></div>
    <div class="coinmarketcap-currency-widget" data-currency="ripple" data-base="USD" data-secondary="BTC"></div>
    <div class="coinmarketcap-currency-widget" data-currency="cardano" data-base="USD" data-secondary="BTC"></div>

  </body>
</html>

#3

great this works but if i run node coinmarketcap.js in the terminal with
console.log it works fine

however if i try to do document.write() i get an error

what can i do to print the last price of any currency on my website using JS, i dont understand why this is so complicated

i used to parse it before with php and it was so easy but with javascript and node parsing drives me crazy

var CoinMarketCap = require(“node-coinmarketcap”);
var coinmarketcap = new CoinMarketCap();
// If you want to check a single coin, use get() (You need to supply the coinmarketcap id of the cryptocurrency, not the symbol)
// If you want to use symbols instead of id, use multi.
coinmarketcap.get(“bitcoin”, coin => {
console.log(coin.price_usd); // Prints the price in USD of BTC at the moment.
});

this scrit is saved as coinmarketcap.js how can i viw the result on my html site?


#4

im just trying out the coinmarketcap package and i just found out it doesnt even come with all coins

for most coins i cant even use the symbol or id


#5

seriously, does coinmarketcap only let me use the first 100 coins??
lol


#6

coinmarketcap is useless since it only allows me to parse the top 100 coins

are there better ways to track coins

CMC Is so fucking useless to me


#7

isnt there a better way to do this?

can i not just parse it with json parse and json decode like in php?
does this not work in javascript

and whats the point of nodejs- why would i use this crap? what does it do for me when i can run js in the console but not on my website?


#8

GraphQL maybe? Bring it in as Json then parse it with Graphql. I dont know just guessing.


#9

Hi @yayo, you are right about node js being useless for the browser. Node doesn’t run in a browser, rather it is a JavaScript based service layer, and is intended as a server-side api.

My apologies, as I sent you down a wrong path there.

I have a crypto trading bot which connects to the Binance exchange directly, and is limited to the few 100 currencies that they support. Which is plenty for my purposes.

Might I ask why you want to get market data from coin market cap? I.e. what are you intending to do with the market data?

The reason I ask is that I also have a bot that crawls cmc web pages and extracts the data from the HTML. I’ve used dotnet core, but something similar could be done with a JavaScript framework like phantom js.

http://phantomjs.org


#10

So, finally had a chance to put together a q&d (quick and dirty) sample of html/js accessing coinmarketcap.

The problem with this is after about 10 requests for ticker data I got the following:

But where there’s a will, there’s a way.
If ‘rate-limiting’ is a problem, then I would suggest using an exchange’s dedicated api.
This involves signing up with an exchange and you will then be issued with an api key that you can use to authenticate api calls; thus rate-limiting is no longer a problem, you can just fill your boots with data.

Personally, I use Binance, but also I highly recommend GDAX, as their api can retrieve info from multiple exchanges, and you can setup favourites and lots of other fun stuff.

Anyway, for the sake of posterity, here is the q&d html/js:
The only special thing to note is this makes use of a javascript plugin: jquery - which is a handy library that comes with an $.ajax() method for making api calls across the web.

<!DOCTYPE html>
<html>
<head>
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"
		integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
		crossorigin="anonymous">
	</script>

	<script>
		/*
		* Note that if you get the following error message, then coinmarketcap has detected too many requests from your ip (status code 429):
		* Failed to load https://api.coinmarketcap.com/v2/global/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 429.			 	    
		* */

		function clickMe() {			
			$.ajax({					
				url: 'https://api.coinmarketcap.com/v2/global/',
				type: 'GET',				
				success: function (response) {

					//this is raw response data
					console.log(JSON.stringify(response));

					console.log('Coinmarketcap Global data summary...');
					console.log('active_cryptocurrencies: ' + response.data.active_cryptocurrencies);
					console.log('active_markets: ' + response.data.active_markets);
					console.log('bitcoin_percentage_of_market_cap: ' + response.data.bitcoin_percentage_of_market_cap);		

					var limit = 100;
					for (var i = 0; i < response.data.active_cryptocurrencies; i += limit) {
						var tickerUrl = 'https://api.coinmarketcap.com/v2/ticker/?start=' + i + '&limit=' + limit;
						console.log('Getting ticker info from ' + tickerUrl);
						$.ajax({
							url: tickerUrl,
							type: 'GET',
							success: function (response) {
								//this is the raw response data
								console.log(JSON.stringify(response));

								//You get the idea...
							},
							error: function (err) {
								console.log('An error occurred while getting ticker info...');
								console.log(JSON.stringify(err));
							}
						});
					}
				},
				error: function (err) {
					console.log('An error occurred while getting global data...');					
					console.log(JSON.stringify(err));
				}
			});
		}

	</script>
</head>
<body>
	<a href="javascript:clickMe();">Click Me</a>	
</body>
</html>

For a full description of the coinmarketcap apis and (the all important) response data, see:

Also, if you want to dev/test raw apis (no need to wrestle with javascript) then I highly recommend Postman.
A great tool for interacting with apis:


#11

great thanks, i will use exchange apis since there are to many restricitons with CMC, like i said i cant even acces more than the top 100 coins


#12

what is this postman?
what can i do with this and how does this work?


#13

Hi @yayo,

Postman is The Tool for testing and developing against (RESTful) apis.
It emulates http requests and supports every http method:
Get, Post, Put, Patch, Delete, Head, Options, etc.

Basically, it allows you to interact with apis, and view the response.
If you’re building an app that uses apis, then you can interactively test the endpoints and see what your code needs to do.

Postman also supports authentication, allowing you to add your credentials as key/value pairs in the request header.

The response is displayed in the bottom pane.

The following cmc examples are public apis (no authentication is required).
Paste in the url and click ‘Send’.

The first 10 ticker items (sorted by id):
(https://api.coinmarketcap.com/v2/ticker/?limit=10&sort=id)

Starting at the 101st item, retrieve the next 10 ticker items:
(https://api.coinmarketcap.com/v2/ticker/?start=101&limit=10)


#14

@yayo,
P.s. As an aside, if you are going to build an app that uses data from the exchange, then I would recommend looking at Message Queues. Almost every major exchange provides them in some form.

Queues are slightly more advanced than api requests, and they operate almost in reverse.

Essentially, an app connects to an exchange’s queue and whenever an update occurs on the exchange, it is pushed onto the queue and the app receives that update almost instantaneously (within milliseconds). No need to make a request (pull) for new data, it is instantly and automatically sent from the exchange to the app.

It is especially useful for ticker data and order book data as these update so frequently (several times a second).

This deserves a whole other topic, but if you’re interested we could discuss further.


#15

im working on a listing site and i wan tto display the price, marketcap and 24hour volume on my site

i use php and json decode it and than echo it out, i have no prolem getting the price but i cant get marketcap from ethereum and 24 hour volume

<?php $decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE); function price($curr) { global $decoded_json; $js = array_column($decoded_json, 'price_usd', 'id'); return $js[$curr]; } ?>

and than i just echo (“ethereum”)


#16

Message queues! Now you’ve got my attention!
I need to know when an order might have traded, so I am not continually distracted from actually getting on with other work, like doing my coding course.


#17

Hi @ian,

When I first started automated trading, the bot would place the order at a price somewhere between the Ask and Bid. Depending on the ticker activity (up vs down), there was no guarantee that the order would execute, and the bot would need to check the status of the order, and cancel if a specified time had passed.

This got to be way too much work, and some exchanges (such as Binance) monitor for suspicious behavior - like repeatedly placing and cancelling orders, which can look like ‘spoofing’ - and block your ip address.

In my case, the bot is placing several orders an hour, and detects a trade by comparing price differentials. To get around the extra work of checking/cancelling orders, I changed the bot to make the trade at the specified Ask or Bid price. This is effectively a Market Order, and seeing as the price differential has already been calculated (i.e. the bot is happy with the math), the order always executes immediately, so no follow up or checking is required.

Of course, this only applies to day trading - catching the highs and dips throughout the day.
For a longer term trade of days or weeks, and the case where orders are placed across multiple exchanges, the logic would be different. However, the mechanics of connecting to the exchange’s Order Book or Ticker are the same.

My advice: Don’t Reinvent The Wheel.
There are some great programming libraries out there that have been tried and tested.
Use these wherever possible, rather than coding your own library from the ground up.
You will save yourself days, if not weeks; and sometimes it’s the difference between success and failure.

For example, check out all the open source libraries (and languages) that support Binance:
https://github.com/search?q=binance

There are over 900 for Python alone.
And 250+ for C#.

Of course, The Purists will argue:
“But how will I learn if I don’t code my own library?”
“I don’t trust anybody else’s code”

It’s open source: read the code if you want to learn, or are paranoid.
By using open source libraries, you don’t need to bother with 99% of the plumbing; that is, all of the grunt work that goes into creating a queue, connecting the queue, handling exceptions, buffer limits, serialization, testing it, debugging it, etc.

A queue is a queue is a queue.
There are many great coders that have gone before; they’ve written some pretty awesome stuff, and made it freely available. And a whole community of people have tested and improved it.

Then we can get on with the Fun Stuff.


#18

P.s. coinmarketcap repos on github.


#19

Thanks. I found this one, https://github.com/sammchardy/python-binance and he also has one for KuCoin. It will still take me quite some time. Or maybe you meant this one. https://github.com/yasinkuyu/binance-trader


#20

Why does the exchange API use a jargon like “Kline” with no definition? Even “the Internet” doesn’t know what it means.