128

I want to do my own bitcoin chart.

Would you know any reliable way to retrieve bitcoins historical price data? Is there any way to retrieve it using REST? I saw Bitfloor, which supports REST, but it is not returning any useful value, it has a "internal server error".

I saw also Bitcoincharts, but I think it's limited to 2000 data values.

Would you suggest me any framework or system to work about it?

Cod1ngFree
  • 1,873
  • 6
  • 21
  • 33

7 Answers7

155

Actually, you CAN get the whole Bitcoin trades history from Bitcoincharts in CSV format here : http://api.bitcoincharts.com/v1/csv/

it is updated twice a day for active exchanges, and there is a few dead exchanges, too.

EDIT: Since there are no column headers in the CSVs, here's what they are : column 1) the trade's timestamp, column 2) the price, column 3) the volume of the trade

Lykegenes
  • 1,726
  • 1
  • 14
  • 10
  • 3
    +1 yes, it is in fact very useful for charting established trades. Data can also be acquired live through bitstamp's pusher API which is what I'm doing right now. After indexing bitstamp for a day, I downloaded the bitstampUSD.csv and prepended the data to have a complete picture – nurettin Mar 05 '14 at 17:40
  • @Lykegenes also the list of trades doesn't show info on market depth, the depth is an instantaneous picture of the whole two order books at a certain time while the trade sequence is just the point where the order books met – anddam May 30 '14 at 17:18
  • @anddam I don't know if you were looking for market depth data, but if you end up finding it, please share! :) – Lykegenes Jun 30 '14 at 13:35
  • 2
    @Lykegenes What is the second column? The values are in the range 0.5-33, which can't be the exchange rate USD/BTC. – holdenlee Oct 28 '14 at 14:03
  • @holdenlee As I said in my original answer, the columns are as follow : UNIX timestamp, price and amount. If you look in the Bitstamp or the BTC-e files and scroll down to the bottom to see the very latest prices, you'll see that they correspond to the current ones on these sites. – Lykegenes Oct 31 '14 at 21:36
  • @Lkyegenes Thanks for your answer. Do you know if bitcoincharts updating their CSV files twice a day is still true? – Brandon Bradley Jan 16 '15 at 15:42
  • @brandon-bradley Not sure, as of right now, many exchanges weren't updated since ~8 days, so I wouldn't rely on this... Also, all update times are between 11h00 and 11h30, so I would say only once a day, and roll a dice ;P – Lykegenes Jan 27 '15 at 22:44
  • @Lkyegenes I viewed times between 23h00 and 23h30 sometime in the past two week. However, I found out how to download them when times or filesizes change using only the 'wget' linux command. Much thanks! – Brandon Bradley Jan 28 '15 at 13:30
  • 4
    Beware of big gaps in `bitcoincharts.com` data. Also note that there is no tick "buy/sell" information. – Petr Javorik Jul 10 '17 at 16:01
  • That Time Stamp field - is it milliseconds since 01/01/1970? I'm trying to convert it into the actual DateTime for some data. – theJerm Aug 05 '17 at 21:23
  • 2
    @theJerm It's in the UNIX timestamp format, so the number of **seconds** since 01/01/1970 in the UTC timezone – Lykegenes Aug 08 '17 at 19:34
  • 2
    Where can I get data for Litecoin, Ethereum or other important coins? – skan Dec 20 '17 at 21:34
  • 1
    @skan It's difficult to find raw data for other coins. I found this site which offers CSV files for a few coins on Bitfinex : [cryptodatasets.com](https://www.cryptodatasets.com). – Lykegenes May 17 '18 at 14:26
  • Can we get 2009 bitcoin data having fields such as "transferred from", "transferred to" and "time stamp". – DreamerP Aug 31 '18 at 09:11
  • https://github.com/stpoa/bitcoin-price-scraper - this is a simple tool to get data from bitcoincharts – stpoa Mar 07 '21 at 14:14
  • I was loading data using this script: https://stackoverflow.com/questions/124492/c-sharp-httpwebrequest-command-to-get-directory-listing regex guide: https://www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet regex test: https://regexr.com/ regex I came up with for GET request: @"[^""']*)[""']|(?<1>\S+))>(?\S+\.\S+\.\S+)" I was using C# – M22 May 23 '21 at 13:28
  • I downloaded all of them via script, it takes 50,330,095,113 bytes total – M22 May 23 '21 at 17:36
  • My script: https://gist.github.com/Miha22/ec38e6e4014b72c3ece065a5ecff32cb – M22 May 23 '21 at 18:44
  • directly binance exchange is another way-> https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT. That is what's powering https://everycoinprice.com – ayush narula Jun 21 '21 at 05:52
  • @skan query directly from binance like this-> For Litecoin etc, https://api.binance.com/api/v3/ticker/24hr?symbol=LTCUSDT That is how https://everycoinprice.com does it – ayush narula Jun 21 '21 at 05:54
33

You can find a lot of historical data here: https://www.quandl.com/data/BCHARTS-Bitcoin-Charts-Exchange-Rate-Data

Max Mikhaylov
  • 772
  • 13
  • 32
Sean
  • 431
  • 5
  • 4
  • 2
    Link only answers are not encouraged on SO. Also he is looking for a way to retrieve data, not only the data itself. – fancyPants Jul 05 '13 at 15:43
  • 2
    You're right, I should have been more comprehensive in my answer. However it does answer his request, as the API calls for retrieving the data are listed on the right side of the page. – Sean Jul 08 '13 at 20:59
  • The link is broken – Guillaume Chevalier Mar 06 '17 at 04:07
  • 2
    @GuillaumeChevalier i've found https://www.quandl.com/data/BCHARTS-Bitcoin-Charts-Exchange-Rate-Data – Jörn Apr 22 '17 at 14:09
17

In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.

The script uses python websocket-client and pusher_client_python libraries, so install them.

#!/usr/bin/python

import pusherclient
import time
import logging
import sys
import datetime
import signal
import os

logging.basicConfig()
log_file_fd = None

def sigint_and_sigterm_handler(signal, frame):
    global log_file_fd
    log_file_fd.close()
    sys.exit(0)


class BitstampLogger:

    def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
        self.channel = channel
        self.event = event
        self.log_file_fd = open(log_file_path, "a")
        self.log_file_reload_path = log_file_reload_path
        self.pusher = pusherclient.Pusher(pusher_key)
        self.pusher.connection.logger.setLevel(logging.WARNING)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()

    def callback(self, data):
        utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
        line = str(utc_timestamp) + " " + data + "\n"
        if os.path.exists(self.log_file_reload_path):
            os.remove(self.log_file_reload_path)
            self.log_file_fd.close()
            self.log_file_fd = open(log_file_path, "a")
        self.log_file_fd.write(line)

    def connect_handler(self, data):
        channel = self.pusher.subscribe(self.channel)
        channel.bind(self.event, self.callback)


def main(log_file_path, log_file_reload_path):
    global log_file_fd
    bitstamp_logger = BitstampLogger(
        log_file_path,
        log_file_reload_path,
        "de504dc5763aeef9ff52",
        "live_trades",
        "trade")
    log_file_fd = bitstamp_logger.log_file_fd
    signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
    signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
    while True:
        time.sleep(1)


if __name__ == '__main__':
    log_file_path = sys.argv[1]
    log_file_reload_path = sys.argv[2]
    main(log_file_path, log_file_reload_path

and logrotate file config

/mnt/data/bitstamp_logs/bitstamp-trade.log
{
    rotate 10000000000
    minsize 10M
    copytruncate
    missingok
    compress
    postrotate
        touch /mnt/data/bitstamp_logs/reload_log > /dev/null
    endscript
}

then you can run it on background

nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &
mettw
  • 439
  • 5
  • 10
10

Bitstamp has live bitcoin data that are publicly available in JSON at this link. Do not try to access it more than 600 times in ten minutes or else they'll block your IP (plus, it's unnecessary anyway; read more here). The below is a C# approach to getting live data:

using (var WebClient = new System.Net.WebClient())
{
     var json = WebClient.DownloadString("https://www.bitstamp.net/api/ticker/");
     string value = Convert.ToString(json);
     // Parse/use from here
}

From here, you can parse the JSON and store it in a database (or with MongoDB insert it directly) and then access it.

For historic data (depending on the database - if that's how you approach it), do an insert from a flat file, which most databases allow you to use (for instance, with SQL Server you can do a BULK INSERT from a CSV file).

user123
  • 545
  • 2
  • 7
  • 13
5

I have written a java example for this case:

Use json.org library to retrieve JSONObjects and JSONArrays. The example below uses blockchain.info's data which can be obtained as JSONObject.

    public class main 
    {
        public static void main(String[] args) throws MalformedURLException, IOException
        {
            JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
            JSONArray data_array = data.getJSONArray("values");

            for (int i = 0; i < data_array.length(); i++)
            {
                JSONObject price_point = data_array.getJSONObject(i);

                //  Unix time
                int x = price_point.getInt("x");

                //  Bitcoin price at that time
                double y = price_point.getDouble("y");

                //  Do something with x and y.
            }

        }

        public static JSONObject getJSONfromURL(String URL)
        {
            try
            {
                URLConnection uc;
                URL url = new URL(URL);
                uc = url.openConnection();
                uc.setConnectTimeout(10000);
                uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                uc.connect();

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(uc.getInputStream(), 
                        Charset.forName("UTF-8")));

                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1)
                {
                    sb.append((char)cp);
                }

                String jsonText = (sb.toString());            

                return new JSONObject(jsonText.toString());
            } catch (IOException ex)
            {
                return null;
            }
        }
    }
domi
  • 968
  • 1
  • 10
  • 18
5

Coinbase has a REST API that gives you access to historical prices from their website. The data seems to show the Coinbase spot price (in USD) about every ten minutes.

Results are returned in CSV format. You must query the page number you want through the API. There are 1000 results (or price points) per page. That's about 7 days' worth of data per page.

leishman
  • 1,017
  • 11
  • 7
5

Scraping it to JSON with Node.js would be fun :)

https://github.com/f1lt3r/bitcoin-scraper

enter image description here

[
  [
    1419033600,  // Timestamp (1 for each minute of entire history)
    318.58,      // Open
    318.58,      // High
    318.58,      // Low
    318.58,      // Close
    0.01719605,  // Volume (BTC)
    5.478317609, // Volume (Currency)
    318.58       // Weighted Price (USD)
  ]
]
f1lt3r
  • 2,176
  • 22
  • 26
  • Thank you for the script! It seems that now the downloaded files just contain "undefined." – Chad Johnson Jan 02 '17 at 04:55
  • I just checked out the repo, ran `npm install`, and then `cat bitstampUSD-2014-9-9.json` looks fine to me. If you're invested in getting it working, lets take it to Github rather than Stackoverflow comments? Leave me a bug report? – f1lt3r Jan 02 '17 at 18:41
  • if I understand your code allows me to get the full history of bitcoin price on a scale of 1 minute ? – Mayeul sgc Mar 27 '17 at 06:27
  • Yes that is right – f1lt3r Mar 28 '17 at 07:01
  • It didn't work for me. I created a working solution based on your script: https://github.com/stpoa/bitcoin-price-scraper – stpoa Mar 07 '21 at 14:12