├── .gitignore ├── README.md ├── csharp-examples └── csharp-wrapper.cs ├── golang_examples ├── README.md └── src │ └── github.com │ └── bitcoinaverage.com │ └── golang-example │ ├── Gopkg.lock │ ├── Gopkg.toml │ └── basic_req.go ├── java_examples └── Authentication.java ├── javascript_examples └── authentication.js ├── node_npm_examples ├── constants.js ├── conversions.js ├── exchanges.js ├── history.js ├── ticker.js └── websocket │ ├── exchangeWebsocket.js │ └── tickerWebsocket.js ├── php_examples └── authentication.php ├── python_examples ├── authentication.py └── ticker_websocket.py ├── python_pip_examples ├── constants.py ├── conversions.py ├── exchanges.py ├── history.py ├── ticker.py └── websocket │ ├── exchange_websocket.py │ └── ticker_websocket.py ├── ruby_examples └── authentication.rb └── websocket_v2_orderbooks_snapshot.js /.gitignore: -------------------------------------------------------------------------------- 1 | config.yml 2 | .idea* 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BitcoinAverage API integration examples 2 | Examples of how to integrate with our API in various langauges 3 | 4 | ## BitcoinAverage Packages 5 | 6 | We have published our own npm and pip packages that do the heavy lifting for you (authentication, handling requests, remembering the full urls). 7 | 8 | ### NPM Package 9 | This library enables quick and easy access to our Bitcoin, Ethereum, Litecoin, Ripple and other cryptocurrency exchange rates. 10 | 11 | ### Install 12 | 13 | 14 | ``` 15 | npm install bitcoinaverage 16 | ``` 17 | 18 | 19 | ### Setup 20 | Get your public and private keys from our website and you are ready to run these examples. 21 | 22 | ```javascript 23 | const ba = require('bitcoinaverage'); 24 | 25 | var publicKey = 'yourPublicKey'; 26 | var secretKey = 'yourSecretKey'; 27 | 28 | var restClient = ba.restfulClient(publicKey, secretKey); 29 | var wsClient = ba.websocketClient(publicKey, secretKey); 30 | ``` 31 | 32 | 33 | 34 | ### Ticker Data 35 | The response received by https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD. 36 | 37 | The symbol_set can be one of: local, global, crypto and tokens. 38 | 39 | The symbol can be any pair from our [Full symbol list](https://apiv2.bitcoinaverage.com/constants/indices/ticker/symbols) 40 | ```javascript 41 | var symbol_set = 'global'; 42 | var symbol = 'BTCUSD'; 43 | 44 | restClient.getTickerDataPerSymbol('global', 'BTCUSD', function(response) { 45 | console.log(response); 46 | }, function(error){ 47 | console.log(error); 48 | }) ; 49 | ``` 50 | 51 | ### Exchange Data 52 | 53 | #### All price data from single exchange 54 | ```javascript 55 | restClient.perExchangeData('bitstamp', 56 | function(response){ 57 | console.log(response); 58 | }, 59 | function(err){ 60 | console.log(err); 61 | }); 62 | ``` 63 | 64 | #### Data from all exchanges for one symbol 65 | ```javascript 66 | restClient.allExchangeDataForSymbol('BTCGBP', 67 | function(response){ 68 | console.log(response); 69 | }, 70 | function(err){ 71 | console.log(err); 72 | }); 73 | ``` 74 | 75 | ### Websocket 76 | Connect to one of our websocket endpoints and get real-time updates for the Bitcoin Global Price Index. 77 | 78 | #### Ticker websocket 79 | 80 | ```javascript 81 | wsClient.connectToTickerWebsocket('global', 'BTCUSD', function(response) { 82 | console.log(response); 83 | }, function(error){ 84 | console.log(error) 85 | }, function(){ 86 | console.log("websocket closed"); 87 | }); 88 | ``` 89 | 90 | #### Orderbook websocket 91 | 92 | The orderbook channel starts by sending a "snapshot" message with the current state of the orderbook. 93 | Then it is followed by "update" messages that represent the changes in the orderbook. 94 | 95 | If the amount for an order is 0, the order has been completed, so it needs to be removed from the orderbook. 96 | 97 | If the amount is greater than 0 then we just update value. 98 | ```javascript 99 | var symbols = ['BTCUSD', 'ETHUSD']; 100 | var exchange = 'bitfinex'; 101 | var ORDERBOOKS = { 102 | BTCUSD: {}, 103 | ETHUSD: {} 104 | }; 105 | var symbol = ''; 106 | wsClient.connectToOrderbookWebsocket(exchange, symbols, function(response){ 107 | symbol = respnose.data.symbol; 108 | if(response.data.type === "snapshot"){ 109 | ORDERBOOKS[symbol].asks = response.data.asks; 110 | ORDERBOOKS[symbol].bids = response.data.bids; 111 | }else{ 112 | console.log(response.data.updates); 113 | for (var i = 0; i < response.data.updates.length; i++){ 114 | var item = response.data.updates[i]; 115 | if(item.amount === 0){ 116 | delete(ORDERBOOKS[symbol][item.side][item.price]); 117 | }else{ 118 | ORDERBOOKS[symbol][item.side][item.price] = item; 119 | } 120 | } 121 | } 122 | }, function(err){ 123 | console.log(err); 124 | }); 125 | ``` 126 | 127 | ### Python PIP Package 128 | 129 | 130 | ```bash 131 | pip install bitcoinaverage 132 | ``` 133 | 134 | #### Setup 135 | ```python 136 | from bitcoinaverage import RestfulClient 137 | restful_client = RestfulClient("", "") 138 | ``` 139 | 140 | #### Ticker data 141 | ```python 142 | ticker_global = restful_client.ticker_all_global(crypto="ETH", fiat="USD,EUR") 143 | print(ticker_global) 144 | ``` 145 | 146 | #### Exchange data 147 | ```python 148 | all_bitstamp_data = restful_client.per_exchange_data('bitstamp') 149 | all_coinbase_data = restful_client.per_exchange_data('gdax') 150 | 151 | all_exchange_data_gbp_brl = restful_client.all_exchange_data(crypto='BTC', fiat='GBP,BRL') 152 | ``` 153 | 154 | -------------------------------------------------------------------------------- /csharp-examples/csharp-wrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using System; 3 | using System.Net.Http; 4 | using System.Net.WebSockets; 5 | using System.Security.Cryptography; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | //https://apiv2.bitcoinaverage.com/ 11 | namespace InvestAgg.Server.BitcoinAverage 12 | { 13 | /// 14 | /// Asynchronous wrapper for the V2 API at bitcoinaverage. 15 | /// Written by Fredrik Nøring at Norkon Computing Systems 16 | /// 17 | public class BitcoinAverageApi 18 | { 19 | public const string BITCOIN_TICKER = "BTCUSD"; 20 | public const string GLOBAL_MARKET = "global"; 21 | 22 | private readonly string _publicKey; 23 | private readonly string _secretKey; 24 | private readonly HMACSHA256 _sigHasher; 25 | private readonly DateTime _epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 26 | 27 | public BitcoinAverageApi(string publicKey, string secretKey) 28 | { 29 | _secretKey = secretKey; 30 | _publicKey = publicKey; 31 | _sigHasher = new HMACSHA256(Encoding.ASCII.GetBytes(_secretKey)); 32 | } 33 | 34 | public string GetHeaderSignature() 35 | // deprecated method, no need for this signature anymore 36 | { 37 | var timestamp = (int)((DateTime.UtcNow - _epochUtc).TotalSeconds); 38 | var payload = timestamp + "." + _publicKey; 39 | var digestValueBytes = _sigHasher.ComputeHash(Encoding.ASCII.GetBytes(payload)); 40 | var digestValueHex = BitConverter.ToString(digestValueBytes).Replace("-", "").ToLower(); 41 | return payload + "." + digestValueHex; 42 | } 43 | 44 | public async Task GetJsonAsync(string url) 45 | { 46 | using (var httpClient = new HttpClient()) 47 | { 48 | httpClient.DefaultRequestHeaders.Add("x-ba-key", _publicKey); 49 | return JToken.Parse(await httpClient.GetStringAsync(url)); 50 | } 51 | } 52 | 53 | public Task GetBitcoinAllTimeHistoricalDataAsync() => GetAllTimeHistoricalDataAsync(BITCOIN_TICKER); 54 | 55 | public Task GetAllTimeHistoricalDataAsync(string symbol, string market = GLOBAL_MARKET) 56 | { 57 | var url = "https://apiv2.bitcoinaverage.com/indices/" + market + "/history/" + symbol + "?" 58 | + "&period=alltime" 59 | + "&format=json"; 60 | 61 | return GetJsonAsync(url); 62 | } 63 | 64 | public Task GetBitcoinDailyDataAsync() => GetDailyDataAsync(BITCOIN_TICKER); 65 | 66 | public Task GetDailyDataAsync(string symbol, string market = GLOBAL_MARKET) 67 | { 68 | var url = "https://apiv2.bitcoinaverage.com/indices/" + market + "/history/" + symbol + "?" 69 | + "&period=daily" 70 | + "&format=json"; 71 | 72 | return GetJsonAsync(url); 73 | } 74 | 75 | public Task GetBitcoinOhlcAsync() => GetOhlcAsync(BITCOIN_TICKER); 76 | 77 | public Task GetOhlcAsync(string symbol, string market = GLOBAL_MARKET) 78 | { 79 | var url = "https://apiv2.bitcoinaverage.com/indices/" + market + "/ticker/" + symbol; 80 | return GetJsonAsync(url); 81 | } 82 | 83 | public async Task GetWebsocketTicket() 84 | { 85 | var url = "https://apiv2.bitcoinaverage.com/websocket/get_ticket"; 86 | var jToken = await GetJsonAsync(url); 87 | return jToken["ticket"].Value(); 88 | } 89 | 90 | public Task StartBitcoinStreaming(CancellationToken ct, Action notifier) 91 | { 92 | var subscriptionMessage = new JObject 93 | { 94 | { "event", "message" }, 95 | { "data", new JObject 96 | { 97 | { "operation", "subscribe" }, 98 | { "options", new JObject 99 | { 100 | { "market", "global" }, 101 | { "currency", BITCOIN_TICKER } 102 | } 103 | } 104 | } 105 | } 106 | }; 107 | 108 | return StartWebsocketStreaming(ct, notifier, subscriptionMessage); 109 | } 110 | 111 | public async Task StartWebsocketStreaming(CancellationToken ct, Action notifier, JObject subscribeMessage) 112 | { 113 | var buffer = new byte[1048576]; //1MB 114 | var str = subscribeMessage.ToString(Newtonsoft.Json.Formatting.None); 115 | 116 | var ticket = await GetWebsocketTicket(); 117 | var url = "wss://apiv2.bitcoinaverage.com/websocket/ticker?public_key=" + _publicKey + "&ticket=" + ticket; 118 | 119 | using (var webSocket = new ClientWebSocket()) 120 | { 121 | await webSocket.ConnectAsync(new Uri(url), ct); 122 | 123 | //Send the subscribe message 124 | var subscribeArraySegment = new ArraySegment(buffer, 0, Encoding.UTF8.GetBytes(str, 0, str.Length, buffer, 0)); 125 | await webSocket.SendAsync(subscribeArraySegment, WebSocketMessageType.Text, true, ct); 126 | 127 | while (true) 128 | { 129 | ct.ThrowIfCancellationRequested(); 130 | notifier(await ReceiveNextWebsocketString(webSocket, buffer, ct)); 131 | } 132 | } 133 | } 134 | 135 | private async Task ReceiveNextWebsocketString(ClientWebSocket webSocket, byte[] buffer, CancellationToken ct) 136 | { 137 | var index = 0; 138 | 139 | while (true) 140 | { 141 | var receiveResult = await webSocket.ReceiveAsync(new ArraySegment(buffer, index, buffer.Length - index), ct); 142 | 143 | if (receiveResult.CloseStatus.HasValue) 144 | return null; 145 | 146 | index += receiveResult.Count; 147 | 148 | if (!receiveResult.EndOfMessage) 149 | continue; 150 | 151 | return Encoding.UTF8.GetString(buffer, 0, index); 152 | } 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /golang_examples/README.md: -------------------------------------------------------------------------------- 1 | # Go example 2 | 3 | This example uses Viper to access the values for the public and 4 | secret keys. The values are stored in `config.yml` (see below), 5 | which has been added to `.gitignore` so you can't easily 6 | push it to Github accidentally. 7 | 8 | To run this example, do the following: 9 | ```bash 10 | export GOPATH=`pwd` 11 | cd src/github.com/bitcoinaverage.com/golang-example 12 | go get github.com/golang/dep 13 | dep ensure -v 14 | cat >>config.yml 15 | publickey: "paste public key here" 16 | secretkey: "paste secret key here" 17 | go run basic_req.go 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /golang_examples/src/github.com/bitcoinaverage.com/golang-example/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/fsnotify/fsnotify" 6 | packages = ["."] 7 | revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" 8 | version = "v1.4.7" 9 | 10 | [[projects]] 11 | branch = "master" 12 | name = "github.com/hashicorp/hcl" 13 | packages = [ 14 | ".", 15 | "hcl/ast", 16 | "hcl/parser", 17 | "hcl/printer", 18 | "hcl/scanner", 19 | "hcl/strconv", 20 | "hcl/token", 21 | "json/parser", 22 | "json/scanner", 23 | "json/token" 24 | ] 25 | revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" 26 | 27 | [[projects]] 28 | name = "github.com/magiconair/properties" 29 | packages = ["."] 30 | revision = "c3beff4c2358b44d0493c7dda585e7db7ff28ae6" 31 | version = "v1.7.6" 32 | 33 | [[projects]] 34 | branch = "master" 35 | name = "github.com/mitchellh/mapstructure" 36 | packages = ["."] 37 | revision = "00c29f56e2386353d58c599509e8dc3801b0d716" 38 | 39 | [[projects]] 40 | name = "github.com/pelletier/go-toml" 41 | packages = ["."] 42 | revision = "acdc4509485b587f5e675510c4f2c63e90ff68a8" 43 | version = "v1.1.0" 44 | 45 | [[projects]] 46 | name = "github.com/pkg/errors" 47 | packages = ["."] 48 | revision = "645ef00459ed84a119197bfb8d8205042c6df63d" 49 | version = "v0.8.0" 50 | 51 | [[projects]] 52 | name = "github.com/spf13/afero" 53 | packages = [ 54 | ".", 55 | "mem" 56 | ] 57 | revision = "63644898a8da0bc22138abf860edaf5277b6102e" 58 | version = "v1.1.0" 59 | 60 | [[projects]] 61 | name = "github.com/spf13/cast" 62 | packages = ["."] 63 | revision = "8965335b8c7107321228e3e3702cab9832751bac" 64 | version = "v1.2.0" 65 | 66 | [[projects]] 67 | branch = "master" 68 | name = "github.com/spf13/jwalterweatherman" 69 | packages = ["."] 70 | revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" 71 | 72 | [[projects]] 73 | name = "github.com/spf13/pflag" 74 | packages = ["."] 75 | revision = "583c0c0531f06d5278b7d917446061adc344b5cd" 76 | version = "v1.0.1" 77 | 78 | [[projects]] 79 | name = "github.com/spf13/viper" 80 | packages = ["."] 81 | revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" 82 | version = "v1.0.2" 83 | 84 | [[projects]] 85 | branch = "master" 86 | name = "golang.org/x/sys" 87 | packages = ["unix"] 88 | revision = "2281fa97ef7b0c26324634d5a22f04babdac8713" 89 | 90 | [[projects]] 91 | name = "golang.org/x/text" 92 | packages = [ 93 | "internal/gen", 94 | "internal/triegen", 95 | "internal/ucd", 96 | "transform", 97 | "unicode/cldr", 98 | "unicode/norm" 99 | ] 100 | revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" 101 | version = "v0.3.0" 102 | 103 | [[projects]] 104 | name = "gopkg.in/yaml.v2" 105 | packages = ["."] 106 | revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" 107 | version = "v2.2.1" 108 | 109 | [solve-meta] 110 | analyzer-name = "dep" 111 | analyzer-version = 1 112 | inputs-digest = "db7f8b0ca3b8cc7d428a672ceca85bbe02d39e321caf8fba2ce3ea1c1477533f" 113 | solver-name = "gps-cdcl" 114 | solver-version = 1 115 | -------------------------------------------------------------------------------- /golang_examples/src/github.com/bitcoinaverage.com/golang-example/Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/spf13/viper" 30 | version = "1.0.2" 31 | 32 | [prune] 33 | go-tests = true 34 | unused-packages = true 35 | -------------------------------------------------------------------------------- /golang_examples/src/github.com/bitcoinaverage.com/golang-example/basic_req.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/pkg/errors" 14 | "github.com/spf13/viper" 15 | ) 16 | 17 | const ( 18 | baseURL = "https://apiv2.bitcoinaverage.com" 19 | ) 20 | 21 | func main() { 22 | viper.AddConfigPath(".") // optionally look for config in the working directory 23 | err := viper.ReadInConfig() // Find and read the config file 24 | if err != nil { // Handle errors reading the config file 25 | panic(errors.Wrap(err, "config file error")) 26 | } 27 | p := viper.Get("publickey") 28 | if p == nil { 29 | panic("missing publickey") 30 | } 31 | publicKey := p.(string) 32 | 33 | uriPath := "/indices/global/ticker/BTCUSD" 34 | 35 | // make request 36 | req, _ := http.NewRequest("GET", baseURL+uriPath, nil) 37 | 38 | // add needed header 39 | req.Header.Add("x-ba-key", publicKey) 40 | 41 | // read response 42 | res, _ := http.DefaultClient.Do(req) 43 | 44 | defer res.Body.Close() 45 | body, _ := ioutil.ReadAll(res.Body) 46 | 47 | fmt.Println(res) 48 | fmt.Println(string(body)) 49 | } 50 | -------------------------------------------------------------------------------- /java_examples/Authentication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Add reference to Gson Jar if you want to print nicely the received response. Otherwise you will need to delete the last lines in the Main. 3 | */ 4 | 5 | import java.io.BufferedReader; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.security.InvalidKeyException; 11 | import java.security.NoSuchAlgorithmException; 12 | 13 | import javax.crypto.Mac; 14 | import javax.crypto.spec.SecretKeySpec; 15 | import javax.xml.bind.DatatypeConverter; 16 | 17 | import com.google.gson.Gson; 18 | import com.google.gson.GsonBuilder; 19 | import com.google.gson.JsonElement; 20 | import com.google.gson.JsonParser; 21 | 22 | public class Authentication { 23 | 24 | public static void main(String[] args) throws IOException, 25 | NoSuchAlgorithmException, InvalidKeyException { 26 | String secretKey = "enter your secret key"; 27 | String publicKey = "enter your public key"; 28 | 29 | String url = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD"; 30 | URL urlObj = new URL(url); 31 | HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); 32 | connection.setRequestMethod("GET"); 33 | connection.setRequestProperty("x-ba-key", publicKey); 34 | 35 | // read all the lines of the response into response StringBuffer 36 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 37 | String inputLine; 38 | StringBuffer response = new StringBuffer(); 39 | 40 | while ((inputLine = bufferedReader.readLine()) != null) { 41 | response.append(inputLine); 42 | } 43 | bufferedReader.close(); 44 | 45 | // if you don't want to use Gson, you can just print the plain response 46 | //System.out.println(response.toString()); 47 | 48 | // print result in nice format using the Gson library 49 | Gson gson = new GsonBuilder().setPrettyPrinting().create(); 50 | JsonParser jp = new JsonParser(); 51 | JsonElement je = jp.parse(response.toString()); 52 | String prettyJsonResponse = gson.toJson(je); 53 | System.out.println(prettyJsonResponse); 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /javascript_examples/authentication.js: -------------------------------------------------------------------------------- 1 | /** 2 | * npm install -g crypto-js 3 | * npm install -g request 4 | */ 5 | 6 | var crypto = require('crypto-js'); 7 | 8 | var public_key = 'enter your public key'; 9 | var ticker_btcusd_url = 'https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD'; 10 | 11 | var request = require('request'); 12 | var options = { 13 | url: ticker_btcusd_url, 14 | headers: { 15 | 'x-ba-key': public_key 16 | } 17 | }; 18 | function callback(error, response, body) { 19 | if (!error && response.statusCode === 200) { 20 | console.log(body); 21 | } 22 | } 23 | 24 | request(options, callback); 25 | 26 | -------------------------------------------------------------------------------- /node_npm_examples/constants.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var restClient = ba.restfulClient(publicKey, secretKey); 6 | 7 | restClient.allSymbols(function (response) { 8 | console.log(response); 9 | }); 10 | 11 | restClient.symbolsLocal(function (response) { 12 | console.log(response); 13 | }); 14 | 15 | restClient.symbolsGlobal(function(response) { 16 | console.log(response); 17 | }); 18 | 19 | restClient.exchangeRatesLocal(function(response) { 20 | console.log(response); 21 | }); 22 | 23 | restClient.exchangeRatesGlobal(function(response) { 24 | console.log(response); 25 | }); 26 | 27 | restClient.serverTime(function(response) { 28 | console.log(response); 29 | }); -------------------------------------------------------------------------------- /node_npm_examples/conversions.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var restClient = ba.restfulClient(publicKey, secretKey); 6 | 7 | // Convert from ETH to USD 8 | var from = 'ETH', to = 'USD', amount = 3; 9 | restClient.performConversionLocal(from, to, amount, function (response) { 10 | response = JSON.parse(response); 11 | console.log("At time " + response.time + " the cost of " + amount + " " + from + " is " + response.price + " " + to); 12 | }); 13 | 14 | // Convert EUR to LTC 15 | var fromFiat = 'EUR', toCrypto = 'LTC'; 16 | restClient.performConversionLocal(fromFiat, toCrypto, amount, function (response) { 17 | response = JSON.parse(response); 18 | console.log("At time " + response.time + " the cost of " + amount + " " + fromFiat + " is " + response.price + " " + toCrypto); 19 | }); 20 | 21 | // Get price when given hash was mined 22 | var hash = 'f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449'; 23 | restClient.blockchainTxPrice('BTCUSD', hash, function (response) { 24 | response = JSON.parse(response); 25 | console.log("1 BTC was worth " + response.average + " when the transaction of the hash " + hash + " was conducted"); 26 | }); -------------------------------------------------------------------------------- /node_npm_examples/exchanges.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var restClient = ba.restfulClient(publicKey, secretKey); 6 | 7 | // Works only for Enterprise users 8 | restClient.allExchangesData('BTC', 'USD', function(response) { 9 | console.log(response); 10 | }); 11 | 12 | // Works only for Enterprise users 13 | restClient.allExchangeDataForSymbol('BTCUSD', function(response) { 14 | console.log(response); 15 | }); 16 | 17 | restClient.perExchangeData('gdax', function(response) { 18 | console.log(response); 19 | }); 20 | 21 | 22 | restClient.exchangeCount(function(response) { 23 | console.log(response); 24 | }); 25 | 26 | restClient.outlierExchanges(function(response) { 27 | console.log(response); 28 | }); 29 | 30 | restClient.ignoredExchanges(function(response) { 31 | console.log(response); 32 | }); 33 | 34 | restClient.inactiveExchanges(function(response) { 35 | console.log(response); 36 | }); 37 | 38 | restClient.currencyWeights(function(response) { 39 | console.log(response); 40 | }); 41 | 42 | restClient.exchangeWeights(function(response) { 43 | console.log(response); 44 | }); -------------------------------------------------------------------------------- /node_npm_examples/history.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var restClient = ba.restfulClient(publicKey, secretKey); 6 | 7 | restClient.historyLocal('BTCUSD', 'daily', function(response) { 8 | console.log(response); 9 | }); 10 | 11 | restClient.historyGlobal('BTCUSD', 'daily', function (response) { 12 | console.log(response); 13 | }); 14 | 15 | 16 | // Getting the Unix timestamp for the moment in time 10 minutes ago from now 17 | var now = new Date(); 18 | var minutesAgo = 10; 19 | var tenMinutesAgo = new Date(now.getTime() - minutesAgo * 60000); 20 | var timestamp = parseInt(tenMinutesAgo.getTime() / 1000); 21 | 22 | // Get local history for last 10 minutes 23 | restClient.dataSinceTimestampLocal('BTCUSD', timestamp, function (response) { 24 | console.log(response); 25 | }); 26 | 27 | // Get global history for last 10 minutes 28 | restClient.dataSinceTimestampGlobal('BTCUSD', timestamp, function (response) { 29 | console.log(response); 30 | }); 31 | 32 | // Get the local price at the moment closest to the specified timestamp 33 | restClient.priceAtTimestampLocal('BTCEUR', timestamp, function (response) { 34 | console.log(response); 35 | }); 36 | 37 | // Get the global price at the moment closest to the specified timestamp 38 | restClient.priceAtTimestampGlobal('BTCEUR', timestamp, function (response) { 39 | console.log(response); 40 | }); 41 | 42 | -------------------------------------------------------------------------------- /node_npm_examples/ticker.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var restClient = ba.restfulClient(publicKey, secretKey); 6 | 7 | // Get local ticker for BTCUSD and ETHUSD 8 | restClient.tickerAllLocal('BTC,ETH', 'USD', function (response) { 9 | console.log(response); 10 | }); 11 | 12 | // Get global ticker for BTCUSD and BTCEUR 13 | restClient.tickerAllGlobal('BTC', 'USD,EUR', function(response) { 14 | console.log(response); 15 | }); 16 | 17 | // Get local ticker for BTCUSD 18 | restClient.tickerLocalPerSymbol('BTCUSD', function (response) { 19 | console.log(response); 20 | }); 21 | 22 | // Get global ticker for BTCGBP 23 | restClient.tickerGlobalPerSymbol('BTCGBP', function (response) { 24 | console.log(response); 25 | }); 26 | 27 | 28 | // 4 examples for short ticker using the local market: 29 | // 1. Get local short ticker for BTCUSD and BTCEUR 30 | restClient.tickerShortLocal('BTC', 'USD,EUR', function (response) { 31 | console.log(response); 32 | }); 33 | 34 | // 2. Get local short ticker for BTC and all supported fiat currencies 35 | restClient.tickerShortLocal('BTC', '', function (response) { 36 | console.log(response); 37 | }); 38 | 39 | // 3. Get local short ticker for all crypto currencies, represented in USD 40 | restClient.tickerShortLocal('', 'USD', function (response) { 41 | console.log(response); 42 | }); 43 | 44 | // 4. Get local short ticker for all available crypto-fiat pairs 45 | restClient.tickerShortLocal('', '', function (response) { 46 | console.log(response); 47 | }); 48 | 49 | 50 | // 4 examples for short ticker using the global market: 51 | // 1. Get global short ticker for BTCUSD and BTCEUR 52 | restClient.tickerShortGlobal('BTC', 'USD,EUR', function (response) { 53 | console.log(response); 54 | }); 55 | 56 | // 2. Get global short ticker for BTC and all supported fiat currencies 57 | restClient.tickerShortGlobal('BTC', '', function (response) { 58 | console.log(response); 59 | }); 60 | 61 | // 3. Get global short ticker for all crypto currencies, represented in USD 62 | restClient.tickerShortGlobal('', 'USD', function (response) { 63 | console.log(response); 64 | }); 65 | 66 | // 4. Get global short ticker for all available crypto-fiat pairs 67 | restClient.tickerShortGlobal('', '', function (response) { 68 | console.log(response); 69 | }); 70 | 71 | // Custom ticker 72 | // Generate price index for BTCUSD based only on the data from Bitstamp and Kraken 73 | restClient.tickerCustomInclude('BTCUSD', 'bitstamp,kraken', function (response) { 74 | console.log(response); 75 | }); 76 | 77 | // Generate price index for BTCUSD based on the data from all exchanges except Bitstamp and Kraken 78 | restClient.tickerCustomExclude('BTCUSD', 'bitstamp,kraken', function (response) { 79 | console.log(response); 80 | }); 81 | 82 | // Get ticker and changes for all supported symbols 83 | restClient.tickerChangesAllLocal(function(response) { 84 | console.log(response); 85 | }); 86 | 87 | // Get Local Ticker and changes only for BTCUSD 88 | restClient.tickerChangesLocal('BTCUSD', function (response) { 89 | console.log(response); 90 | }); 91 | 92 | // Get Global Ticker and changes only for ETHUSD 93 | restClient.tickerChangesGlobal('ETHUSD', function (response) { 94 | console.log(response); 95 | }); -------------------------------------------------------------------------------- /node_npm_examples/websocket/exchangeWebsocket.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var ws = ba.websocketClient(publicKey, secretKey); 6 | 7 | // Connecting to the Exchange websocket and printing Bitstamp data 8 | ws.connectToExchangeWebsocket('bitstamp', function (response) { 9 | console.log(JSON.stringify(response, null, 4)); 10 | }); 11 | -------------------------------------------------------------------------------- /node_npm_examples/websocket/tickerWebsocket.js: -------------------------------------------------------------------------------- 1 | const ba = require('bitcoinaverage'); 2 | 3 | var publicKey = 'yourPublicKey'; 4 | var secretKey = 'yourSecretKey'; 5 | var ws = ba.websocketClient(publicKey, secretKey); 6 | 7 | // Connecting to the local ticker and printing BTCEUR price data; you can try it with 'global' 8 | ws.connectToTickerWebsocket('local', 'BTCEUR', function (response) { 9 | console.log(JSON.stringify(response, null, 4)); 10 | }); -------------------------------------------------------------------------------- /php_examples/authentication.php: -------------------------------------------------------------------------------- 1 | 15 | array( 16 | 'method' => 'GET', 17 | ) 18 | ); 19 | $aHTTP['http']['header'] = "X-Signature: " . $signature; 20 | $context = stream_context_create($aHTTP); 21 | $content = file_get_contents($tickerUrl, false, $context); 22 | 23 | echo $content; 24 | 25 | ?> -------------------------------------------------------------------------------- /python_examples/authentication.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | import requests 4 | import time 5 | 6 | public_key = 'enter your public key' 7 | url = 'https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD' 8 | headers = {'x-ba-key': public_key} 9 | result = requests.get(url=url, headers=headers) 10 | print(result.json()) 11 | 12 | -------------------------------------------------------------------------------- /python_examples/ticker_websocket.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example how to subscribe to ticker websocket. 3 | ''' 4 | import hashlib 5 | import hmac 6 | import requests 7 | import time 8 | from websocket import create_connection 9 | import simplejson as json 10 | 11 | public_key = 'your public key' 12 | 13 | ticket_url = "https://apiv2.bitcoinaverage.com/websocket/get_ticket" 14 | ticket_header = {"x-ba-key": public_key} 15 | ticket = requests.get(url=ticket_url, headers=ticket_header).json()["ticket"] 16 | 17 | url = "wss://apiv2.bitcoinaverage.com/websocket/ticker?public_key={}&ticket={}".format(public_key, ticket) 18 | ws = create_connection(url) 19 | 20 | # Here the values for currency and market may be changed. 21 | # Market is either local or global. 22 | subscribe_message = json.dumps({"event": "message", 23 | "data": { 24 | "operation": "subscribe", 25 | "options": { 26 | "currency": "BTCUSD", 27 | "market": "local" 28 | } 29 | } 30 | }) 31 | 32 | ws.send(subscribe_message) 33 | 34 | while True: 35 | result = ws.recv() 36 | print("Received '%s'" % result) -------------------------------------------------------------------------------- /python_pip_examples/constants.py: -------------------------------------------------------------------------------- 1 | 2 | from bitcoinaverage import RestfulClient 3 | 4 | if __name__ == '__main__': 5 | secret_key = '' or input('Enter your secret key: ') 6 | public_key = '' or input('Enter your public key: ') 7 | 8 | restful_client = RestfulClient(secret_key, public_key) 9 | 10 | all_symbols = restful_client.all_symbols() 11 | print('all symbols:') 12 | print(all_symbols) 13 | 14 | symbols_local = restful_client.symbols_local() 15 | print('local symbols') 16 | print(symbols_local) 17 | 18 | symbols_global = restful_client.symbols_global() 19 | print('global symbols') 20 | print(symbols_global) 21 | 22 | 23 | exchange_rates_local = restful_client.exchange_rates_local() 24 | print('local exchange rates') 25 | print(exchange_rates_local) 26 | 27 | exchange_rates_global = restful_client.exchange_rates_global() 28 | print('global exchange rates') 29 | print(exchange_rates_global) 30 | 31 | 32 | server_time = restful_client.server_time() 33 | print('Server time') 34 | print(server_time) -------------------------------------------------------------------------------- /python_pip_examples/conversions.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import RestfulClient 2 | 3 | if __name__ == '__main__': 4 | secret_key = '' or input('Enter your secret key: ') 5 | public_key = '' or input('Enter your public key: ') 6 | 7 | restful_client = RestfulClient(secret_key, public_key) 8 | 9 | # convert from BTC to USD 10 | conversion_local = restful_client.perform_conversion_local('BTC', 'USD', amount=3) 11 | print('3 BTC are worth {} USD'.format(conversion_local['price'])) 12 | 13 | # convert from EUR to ETH 14 | conversion_global = restful_client.perform_conversion_global('EUR', 'ETH', amount=100) 15 | print('100 EUR are worth {} ETH'.format(conversion_global['price'])) 16 | 17 | # get the price of BTCUSD when the transaction for the provided hash was confirmed 18 | blockchain_tx_price = restful_client.blockchain_tx_price('BTCUSD', 'f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449') 19 | print(blockchain_tx_price) -------------------------------------------------------------------------------- /python_pip_examples/exchanges.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import RestfulClient 2 | 3 | if __name__ == '__main__': 4 | secret_key = '' or input('Enter your secret key: ') 5 | public_key = '' or input('Enter your public key: ') 6 | 7 | restful_client = RestfulClient(secret_key, public_key) 8 | 9 | all_exchange_data = restful_client.all_exchange_data(crypto='BTC', fiat='USD,CNY') 10 | print('data from all exchanges for BTCUSD and BTCCNY') 11 | print(all_exchange_data) 12 | 13 | all_exchange_data_BTCUSD = restful_client.all_exchange_data_for_symbol('BTCUSD') 14 | print('data from all exchanges fro BTCUSD') 15 | print(all_exchange_data_BTCUSD) 16 | 17 | gdax_data = restful_client.per_exchange_data('gdax') 18 | print('data from GDAX') 19 | print(gdax_data) 20 | 21 | exchange_count = restful_client.exchange_count() 22 | print('exchange count') 23 | print(exchange_count) 24 | 25 | outlier_exchanges = restful_client.outlier_exchanges() 26 | print('outlier exchanges') 27 | print(outlier_exchanges) 28 | 29 | ignored_exchanges = restful_client.ignored_exchanges() 30 | print('ignored exchanges') 31 | print(ignored_exchanges) 32 | 33 | inactive_exchanges = restful_client.inactive_exchanges() 34 | print('inactive exchanges') 35 | print(inactive_exchanges) 36 | 37 | currency_weights = restful_client.currency_weights() 38 | print('currency weights') 39 | print(currency_weights) 40 | 41 | exchange_weights = restful_client.exchange_weights() 42 | print('exchange weights') 43 | print(exchange_weights) -------------------------------------------------------------------------------- /python_pip_examples/history.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import RestfulClient 2 | from datetime import datetime, timedelta 3 | 4 | if __name__ == '__main__': 5 | secret_key = '' or input('Enter your secret key: ') 6 | public_key = '' or input('Enter your public key: ') 7 | 8 | restful_client = RestfulClient(secret_key, public_key) 9 | 10 | # load local history as dict 11 | history_local_json = restful_client.history_local('BTCUSD', 'daily', 'json') 12 | 13 | # save history in history_local.csv 14 | restful_client.save_history_local(symbol='BTCUSD', period='daily', csv_path='history_local.csv') 15 | 16 | # load global history as dict 17 | history_global_json = restful_client.history_global('BTCUSD', 'daily', 'json') 18 | 19 | # save history in history_global.csv format 20 | restful_client.save_history_global(symbol='LTCEUR', period='alltime', csv_path='history_global.csv') 21 | 22 | # get unix format timestamp for 10 minutes ago 23 | timestamp = int((datetime.now() - timedelta(minutes=10)).timestamp()) 24 | # get all local history data since the specified timestamp (for the last 10 minutes) 25 | data_since_timestamp = restful_client.data_since_timestamp_local('BTCUSD', since=timestamp) 26 | print('local data for the last 10 minutes (since {} timestamp)'.format(timestamp)) 27 | print(data_since_timestamp) 28 | 29 | timestamp = int((datetime.now() - timedelta(minutes=10)).timestamp()) 30 | # get all global history data since the specified timestamp (for the last 10 minutes) 31 | data_since_timestamp = restful_client.data_since_timestamp_global('BTCUSD', since=timestamp) 32 | print('global data for the last 10 minutes (since {} timestamp)'.format(timestamp)) 33 | print(data_since_timestamp) 34 | 35 | timestamp = int((datetime.now() - timedelta(minutes=10)).timestamp()) 36 | # get the global price at the moment closest to the specified timestamp 37 | price_at_timestamp_global = restful_client.price_at_timestamp_global('BTCEUR', timestamp) 38 | print('price at timestamp global') 39 | print(price_at_timestamp_global) -------------------------------------------------------------------------------- /python_pip_examples/ticker.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import RestfulClient 2 | 3 | 4 | if __name__ == '__main__': 5 | secret_key = '' or input('Enter your secret key: ') 6 | public_key = '' or input('Enter your public key: ') 7 | 8 | restful_client = RestfulClient(secret_key, public_key) 9 | 10 | ticker_all_local = restful_client.ticker_all_local(crypto='LTC', fiat='GBP') 11 | print('ticker all local') 12 | print(ticker_all_local) 13 | 14 | ticker_all_global = restful_client.ticker_all_global(crypto='BTC', fiat='USD,EUR') 15 | print('ticker all global') 16 | print(ticker_all_global) 17 | 18 | ticker_local_per_symbol = restful_client.ticker_local_per_symbol('BTCUSD') 19 | print('Local Ticker for BTCUSD') 20 | print(ticker_local_per_symbol) 21 | 22 | ticker_global_per_symbol = restful_client.ticker_global_per_symbol('BTCUSD') 23 | print('Global Ticker for BTCUSD') 24 | print(ticker_global_per_symbol) 25 | 26 | ticker_short_local = restful_client.ticker_short_local() 27 | print('Local Ticker Short') 28 | print(ticker_short_local) 29 | 30 | ticker_short_global = restful_client.ticker_short_global() 31 | print('Global Ticker Short') 32 | print(ticker_short_global) 33 | 34 | print('Generate price index for BTCUSD based only on the data from Bitstamp and Kraken') 35 | ticker_custom_include = restful_client.ticker_custom_include('BTCUSD', 'bitstamp,kraken') 36 | print(ticker_custom_include) 37 | 38 | print('Generate price index for BTCUSD based on the data from all exchanges except Bitstamp and Kraken') 39 | ticker_custom_exclude = restful_client.ticker_custom_exclude('BTCUSD', 'bitstamp,kraken') 40 | print(ticker_custom_exclude) 41 | 42 | ticker_changes_all_local = restful_client.ticker_changes_all_local() 43 | print('Local Ticker values with changes') 44 | print(ticker_changes_all_local) 45 | 46 | ticker_changes_local_btcusd = restful_client.ticker_changes_local('BTCUSD') 47 | print('Ticker including changes (for BTCUSD):') 48 | print(ticker_changes_local_btcusd) 49 | 50 | ticker_changes_global_btceur = restful_client.ticker_changes_global('BTCEUR') 51 | print('Ticker including changes (for BTCEUR):') 52 | print(ticker_changes_global_btceur) -------------------------------------------------------------------------------- /python_pip_examples/websocket/exchange_websocket.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import ExchangeWebsocketClient 2 | 3 | if __name__ == '__main__': 4 | secret_key = '' or input('Enter your secret key: ') 5 | public_key = '' or input('Enter your public key: ') 6 | 7 | print('Connecting to the exchange websocket...') 8 | ws = ExchangeWebsocketClient(public_key, secret_key) 9 | ws.exchange_data('bitstamp') 10 | -------------------------------------------------------------------------------- /python_pip_examples/websocket/ticker_websocket.py: -------------------------------------------------------------------------------- 1 | from bitcoinaverage import TickerWebsocketClient 2 | 3 | if __name__ == '__main__': 4 | secret_key = '' or input('Enter your secret key: ') 5 | public_key = '' or input('Enter your public key: ') 6 | 7 | print('Connecting to the ticker websocket...') 8 | ws = TickerWebsocketClient(public_key, secret_key) 9 | ws.ticker_data('local', 'BTCUSD') 10 | -------------------------------------------------------------------------------- /ruby_examples/authentication.rb: -------------------------------------------------------------------------------- 1 | require 'openssl' 2 | require 'date' 3 | require 'open-uri' 4 | 5 | public_key = 'enter your public key' 6 | 7 | ticker_url = 'https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD' 8 | response = open(ticker_url, 'x-ba-key' => public_key).read 9 | puts response -------------------------------------------------------------------------------- /websocket_v2_orderbooks_snapshot.js: -------------------------------------------------------------------------------- 1 | var ba = require('bitcoinaverage'); 2 | 3 | var pub = 'your public key'; 4 | var secret = 'your secret key'; 5 | 6 | function reorder(orderbook, symbols){ 7 | var bprices = Object.values(orderbook[symbols[0]].bids); 8 | sorted_bids = bprices.sort(function(a, b){ 9 | return a.price >= b.price ? -1 : 1; 10 | }); 11 | var aprices = Object.values(orderbook[symbols[0]].asks); 12 | sorted_asks = aprices.sort(function(a, b){ 13 | return a.price < b.price ? -1 : 1; 14 | }); 15 | } 16 | 17 | function connect_orderbook(exchange, symbols){ 18 | var ws = ba.websocketClient(pub, secret); 19 | var BOOK = {}; 20 | symbols.forEach(function(symbol){ 21 | BOOK[symbol] = { 22 | 'asks': [], 23 | 'bids': [] 24 | }; 25 | }); 26 | var symbol = ''; 27 | ws.connectToOrderbookWebsocket(exchange, symbols, function(response){ 28 | symbol = response.data.symbol; 29 | if(response.data.type === "snapshot"){ 30 | console.log("Got snapshot for " + symbol + response.data.asks.length); 31 | console.log("Best ASK: "); 32 | console.log(response.data.asks[0]); 33 | console.log("Best BID: "); 34 | console.log(response.data.bids[0]); 35 | BOOK[symbol].asks = response.data.asks; 36 | BOOK[symbol].bids = response.data.bids; 37 | }else{ 38 | console.log("Now updates " + response.data.updates.length + response.data.symbol); 39 | for (var i = 0; i < response.data.updates.length; i++){ 40 | var item = response.data.updates[i]; 41 | if(item.amount === 0){ 42 | delete(BOOK[symbol][item.side][item.price]); 43 | }else{ 44 | BOOK[symbol][item.side][item.price] = item; 45 | } 46 | } 47 | } 48 | }, function(err){ 49 | console.log(err); 50 | }); 51 | setInterval(function(){reorder(BOOK, symbols)}, 10000) 52 | } 53 | --------------------------------------------------------------------------------