GithubHelp home page GithubHelp logo

bitmex / api-connectors Goto Github PK

View Code? Open in Web Editor NEW
906.0 86.0 807.0 8.77 MB

Libraries for connecting to the BitMEX API.

Home Page: https://www.bitmex.com/app/restAPI

Shell 0.15% Python 7.83% Ruby 7.08% Scala 4.57% JavaScript 7.11% Batchfile 0.01% Java 14.70% Clojure 0.65% C# 14.97% Objective-C 4.19% PHP 13.24% TypeScript 2.36% Go 4.03% Swift 1.85% C++ 17.00% CMake 0.02% QMake 0.03% mIRC Script 0.01% VBA 0.20% VBScript 0.03%

api-connectors's Introduction

BitMEX API Connectors

A few simple connectors for connecting to the BitMEX API, which conforms to the Swagger spec.

Connectors in the clients directory are autogenerated. Connectors in the official-* directory are written or vetted by BitMEX employees to showcase various features.

Official Examples

HTTP

Websockets

The easiest way to get real-time data from BitMEX is via the BitMEX Delta Server, a locally-runnable HTTP server that subscribes to live data on your behalf. You can poll this local server as often as you want.

Auto-Generated Languages

Clients:

Swagger Output:

api-connectors's People

Contributors

andersea avatar andsoch avatar askmike avatar axeldomingues avatar bendelo avatar bitmexthomasb avatar bomper avatar boppleton avatar byshing avatar clefru avatar codler avatar dependabot[bot] avatar haehnchen avatar highfestiva avatar jlleitschuh avatar kevzettler avatar ko0f avatar mahendrangarg avatar nityendrasingh avatar pironmind avatar ryanfox avatar strml avatar stuelk avatar tanmaykumar avatar xavier59 avatar yshing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-connectors's Issues

tradeBin1m returns a huge array that keeps growing (nodejs bitmex-realtime-api)

tradeBin1m stream returns an array that keeps adding to existing data and keeps growing.
Code modified from example.js:
client.addStream('XBTUSD', 'tradeBin1m', (data) => { console.log(JSON.stringify(data)); console.log('\n'); });

Result:
`[{"timestamp":"2017-09-09T20:58:00.000Z","symbol":"XBTUSD","open":4294.4,"high":4293.6,"low":4287.4,"close":4293.6,"trades":2,"volume":19436,"vwap":4287.9808,"lastSize":1250,"turnover":453282764,"homeNotional":4.53282764,"foreignNotional":19436}]

[{"timestamp":"2017-09-09T20:58:00.000Z","symbol":"XBTUSD","open":4294.4,"high":4293.6,"low":4287.4,"close":4293.6,"trades":2,"volume":19436,"vwap":4287.9808,"lastSize":1250,"turnover":453282764,"homeNotional":4.53282764,"foreignNotional":19436},{"timestamp":"2017-09-09T20:59:00.000Z","symbol":"XBTUSD","open":4293.6,"high":4292.2,"low":4287.6,"close":4287.6,"trades":2,"volume":2500,"vwap":4290.0043,"lastSize":1250,"turnover":58276250,"homeNotional":0.5827625000000001,"foreignNotional":2500}]

[{"timestamp":"2017-09-09T20:58:00.000Z","symbol":"XBTUSD","open":4294.4,"high":4293.6,"low":4287.4,"close":4293.6,"trades":2,"volume":19436,"vwap":4287.9808,"lastSize":1250,"turnover":453282764,"homeNotional":4.53282764,"foreignNotional":19436},{"timestamp":"2017-09-09T20:59:00.000Z","symbol":"XBTUSD","open":4293.6,"high":4292.2,"low":4287.6,"close":4287.6,"trades":2,"volume":2500,"vwap":4290.0043,"lastSize":1250,"turnover":58276250,"homeNotional":0.5827625000000001,"foreignNotional":2500},{"timestamp":"2017-09-09T21:00:00.000Z","symbol":"XBTUSD","open":4287.6,"high":4287.6,"low":4287.6,"close":4287.6,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0}]`

Node.js: .getSymbol() is broken, crash

It's not really clear from the docs how to use client.getSymbol but I guess it should be like this (similar to the getTable example I've figured out and just added):

const client = new BitMEXClient();

client.addStream('XBTUSD', 'trade', () => {});
client.on('error', (e) => console.error('ERROR', e));  // not reached
setTimeout(() => {
  console.log('XBTUSD symbol info during the last few seconds:', client.getSymbol('XBTUSD'));
}, 5000);

This crashes though:

WebSocket [INFO]: Connected.
undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at clone (/bitmex/node_modules/bitmex-realtime-api/index.js:219:15)
    at BitMEXClient.getData (/bitmex/node_modules/bitmex-realtime-api/index.js:85:10)
    at BitMEXClient.getSymbol (/bitmex/node_modules/bitmex-realtime-api/index.js:99:15)
    at Timeout.setTimeout [as _onTimeout] (file:///bitmex/bitmex.js:17:24)
    at ontimeout (timers.js:466:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

client.getData('XBTUSD') crashes just the same.

I'm using v0.2.3 from npm because of #34.

[nodejs/ws] TypeError: Cannot read property 'length' of undefined

I get this error sometimes right when starting a script that adds a few streams. It's not reliably reproducible:

TypeError: Cannot read property 'length' of undefined
at BitMEXClient. ([...]/node_modules/bitmex-realtime-api/index.js:216:21)

That line is if (newData.length > client._maxTableLen), so newData is probably returned undefined by this line, which should return [].

Ruby gem doesn't work (syntax errors in code)

For instance this bit of code in models/api_key.rb:

    # Check to see if the all the properties in the model are valid
    # @return true if the model is valid
    def valid?
      return false if @id.nil?
      return false if @id.to_s.length < # <-- parse error here
      return false if @secret.nil?
      return false if @secret.to_s.length < # <-- parse error here
      return false if @name.nil?
      return false if @name.to_s.length < # <-- parse error here
      return false if @nonce.nil?
      return false if @cidr.to_s.length < # <-- parse error here
      return false if @user_id.nil?
      return true
    end

What is the difference between table, stream, and subscription?

I'm having trouble understanding from the Node.js web socket README what exactly are "tables", "streams" and "subscriptions". If I understand correctly,

  • tables are flat data sources like orderBookL2, trade or order.
  • a "stream" is
    • incoming data for a symbol (e.g. everything about XBTUSD),
    • or a table (trades for all symbols)
    • or a table within a symbol (e.g. all trades for XBTUSD).
  • You can "subscribe" to a "stream".

Is that correct?

Asking because https://github.com/BitMEX/api-connectors/blob/master/official-ws/nodejs/README.md#available-public-streams lists tables, but calls them "streams", and the https://www.bitmex.com/app/wsAPI links to "any available table" as "Subscriptions".

Cannot read property 'XBTUSD' of undefined

BitMEX:realtime-api { testnet: true,
BitMEX:realtime-api apiKeyID: '',
BitMEX:realtime-api apiKeySecret: '',
BitMEX:realtime-api endpoint: 'wss://testnet.bitmex.com/realtime' } +0ms
BitMEX:realtime-api:socket connecting to wss://testnet.bitmex.com/realtime +4ms
BitMEX-Delta-Server listening on http://localhost:4445
TypeError: Cannot read property 'XBTUSD' of undefined
at BitMEXClient.getData (/home/apoorv/api-connectors/official-ws/nodejs/index.js:70:38)
at /home/apoorv/api-connectors/official-ws/delta-server/lib/server.js:70:21
at Layer.handle [as handle_request] (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/layer.js:95:5)
at next (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/layer.js:95:5)
at /home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/index.js:281:22
at param (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/index.js:354:14)
at param (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/index.js:365:14)
at Function.process_params (/home/apoorv/api-connectors/official-ws/delta-server/node_modules/express/lib/router/index.js:410:3)

I am getting this error while running the websocket. I am using the latest version of node and npm and followed the instructions word by word.

Thanks

node/ws: long-running client stops receiving data

I have a long-running client that logs trade, instrument and orderBookL2 data to a TSDB. After 1-3 days, the client stops receiving data. Running with DEBUG=BitMEX:* doesn't show anything out of the ordinary:

Thu, 04 Jan 2018 08:18:44 GMT BitMEX:realtime-api:socket emitting orderBookL2:update:XBTUSD with data [{"symbol":"XBTUSD","id":8798510550,"side":"Sell","size":500}]
Thu, 04 Jan 2018 08:18:44 GMT BitMEX:realtime-api:socket emitting orderBookL2:insert:XBTUSD with data [{"symbol":"XBTUSD","id":8798510850,"side":"Sell","size":1898,"price":14891.5},{"sym
Thu, 04 Jan 2018 08:18:44 GMT BitMEX:realtime-api:socket emitting orderBookL2:insert:XBTUSD with data [{"symbol":"XBTUSD","id":8798504150,"side":"Sell","size":937700,"price":14958.5}]
Thu, 04 Jan 2018 08:18:44 GMT BitMEX:realtime-api:socket emitting orderBookL2:delete:XBTUSD with data [{"symbol":"XBTUSD","id":8798511750,"side":"Buy"}]
Thu, 04 Jan 2018 08:18:44 GMT BitMEX:realtime-api:socket emitting orderBookL2:insert:XBTUSD with data [{"symbol":"XBTUSD","id":8798512700,"side":"Buy","size":3571,"price":14873}]

After 04 Jan 2018 08:18:44 GMT, there is no more debugging information. Was there a server issue at that time?

Two hours before that, there was a reconnection:

Thu, 04 Jan 2018 06:08:58 GMT BitMEX:realtime-api:socket emitting orderBookL2:update:XBTUSD with data [{"symbol":"XBTUSD","id":8798489900,"side":"Sell","size":25532}]
WebSocket [ERROR]: Websocket closed.
Thu, 04 Jan 2018 06:08:59 GMT BitMEX:realtime-api:socket Connection to BitMEX at wss://www.bitmex.com/realtime closed.
Thu, 04 Jan 2018 06:08:59 GMT BitMEX:realtime-api:socket Reconnecting to BitMEX at  wss://www.bitmex.com/realtime
WebSocket [INFO]: Retry in 1000 ms
WebSocket [INFO]: Reconnecting...
WebSocket [INFO]: Connected.
Thu, 04 Jan 2018 06:09:00 GMT BitMEX:realtime-api:socket Connection to BitMEX at wss://www.bitmex.com/realtime opened.
{"op":"subscribe","args":"trade:XBTUSD"}
Thu, 04 Jan 2018 06:09:00 GMT BitMEX:realtime-api:socket:internal {"op":"subscribe","args":"trade:XBTUSD"}
{"op":"subscribe","args":"orderBookL2:XBTUSD"}
Thu, 04 Jan 2018 06:09:00 GMT BitMEX:realtime-api:socket:internal {"op":"subscribe","args":"orderBookL2:XBTUSD"}
{"op":"subscribe","args":"instrument:XBTUSD"}
Thu, 04 Jan 2018 06:09:00 GMT BitMEX:realtime-api:socket:internal {"op":"subscribe","args":"instrument:XBTUSD"}
Thu, 04 Jan 2018 06:09:02 GMT BitMEX:realtime-api:socket emitting trade:insert:XBTUSD with data [{"timestamp":"2018-01-04T06:09:00.829Z","symbol":"XBTUSD", ...

In case the library fails to reconnect, or just stops receiving data, how should client code reconnect based on its own logic?

CC @ko0f

16-seconds delay in TradeGetBucketed

At, say, 13:00:01 I use TradeGetBucketed to get the information about the candle that just formed. But this information available only at 13:00:16. That is too long for me. Why 16-seconds delay? Are there any other options to get it faster?

Python 3 urllib.parse error

In python 3 the urlparse has moved to urllib.
I tried adding in and changing the names
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse

Im still getting an error with the new urlparse function originating in the actual_kwargs function

Getting "Nonce is not increasing" error with Node.js WS Lib

I'm trying to use the WS library to get realtime updates and using the Swagger client to make orders. This is the error I get whenever I try to connect with the WebSocket library (Node.js: https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs).

Any help or pointers appreciated.

WebSocket [ERROR]: Unexpected response from server [400]: {"error":"Nonce is not increasing. This nonce: 1515130196494, last nonce: 1515128183690000"}
WebSocket [INFO]: The WebSocket will terminate. Please manually reconnect.
WebSocket [ERROR]: Closing Websocket

/node_modules/bitmex-realtime-api/lib/createSocket.js:71
    if (!listeners.length) throw new Error('WebSocket closed. Please check errors above.');
Error: WebSocket closed. Please check errors above.
    at WebSocketClient.wsClient.onend (/node_modules/bitmex-realtime-api/lib/createSocket.js:71:34)
    at WebSocket.instance.on (/node_modules/bitmex-realtime-api/lib/ReconnectingSocket.js:41:18)
    at emitOne (events.js:115:13)
    at WebSocket.emit (events.js:210:7)
    at IncomingMessage.response.on (/node_modules/bitmex-realtime-api/lib/ReconnectingSocket.js:69:27)
    at emitNone (events.js:110:20)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1045:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Missing module websocket-stream from delta-server

module.js:472
throw err;
^

Error: Cannot find module 'websocket-stream'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object. (/Users/bjschnei/bmx/third_party/api-connectors/official-ws/nodejs/lib/createSocket.js:1:82)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)

Swagger spec on Testnet suddenly failing validation

As a follow up to #7

Code to reproduce (note I explicitly disable validation too) (bravado version 9.2.2):

from bravado.client import SwaggerClient
client = SwaggerClient.from_url('https://testnet.bitmex.com/api/explorer/swagger.json',
                                config={'validate_swagger_spec': False})
client.Quote.Quote_get(symbol='XBTUSD').result()

Seems to be OK on live, have there been some recent schema changes rolled out on testnet?

Node.js client on 'data' event

Hi, I successfully connected to the data stream, which is confirmed by:

client.addStream('XBTUSD', 'trade', (data) => { console.log(data) });

But when the app is subscribed to an event nothing happens:

client.addStream('XBTUSD', 'trade', () => {});
client.on('data', function(data) {
    console.log(data);
});

Please advise.
Thank you.

Can't call function Execution_getTradeHistory with parameters in python.

If I run this code:

res, http_response = bitMEXAuthenticated.Execution.Execution_getTradeHistory(symbol = 'XBTUSD', end_time = '2013-10-20').result()

I get folowing error: bravado_core.exception.SwaggerMappingError: Execution_getTradeHistory does not have parameter end_time
Bu if I run this code:

res, http_response = bitMEXAuthenticated.Execution.Execution_getTradeHistory(symbol = 'XBTUSD').result()

I get folowing error:
bravado.exception.HTTPUnauthorized: 401 Unauthorized: {u'error': {u'message': u'Signature not valid.', u'name': u'HTTPError'}}

But if I run function without parameters, it's working fine:

res, http_response = bitMEXAuthenticated.Execution.Execution_getTradeHistory().result()

What I'm doing wrong?

Unable to connect clientAuthorizations

I am getting this error when I connect with APikey/secret.
Unable to connect: TypeError: Cannot read property 'add' of undefined

'use strict';
var SwaggerClient = require("swagger-client");
var _ = require('lodash');
var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization');

require('dotenv').config();

new SwaggerClient({
  // Switch this to `www.bitmex.com` when you're ready to try it out for real.
  // Don't forget the `www`!
  url: 'https://testnet.bitmex.com/api/explorer/swagger.json',
  usePromise: true
})
.then(function(client) {
  //console.log(client);
  // Comment out if you're not requesting any user data.
  client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET));

  // Print client capabilities
  //

})
.catch(function(e) {
  console.error("Unable to connect:", e);
})

KeyError due to improper handling of action in bitmex_websocket.

item = findItemByKeys(self.keys[table], self.data[table], updateData)

item = findItemByKeys(self.keys[table], self.data[table], deleteData)

This issue arises during startup of Websocket client.

item = findItemByKeys(self.keys[table], self.data[table], updateData)

KeyError: u'orderBookL2'

item = findItemByKeys(self.keys[table], self.data[table], deleteData)

KeyError: u'orderBookL2'
'

Cause: It is causing because keys table is not populate for that table (cases when update action is received before partial.)

How to resolve it?: We can ignore the actions update and delete before partial, one way is to lookup if keys are present for that table if not skip it else perform that action.

Example:

if table not in self.keys:

  break

official nodejs client for bitmex

Is there an official nodejs client for bitmex apart from the autogenerated swagger based one?
How do people use bitmex APIs till date in nodejs?

delta-server build issues

From a clean repo I am getting the following build errors when running npm install starting with:

osx 10.11.16

In file included from ../src/bufferutil.cc:16:
../../nan/nan.h:473:20: error: no type named 'GCEpilogueCallback' in
'v8::Isolate'
v8::Isolate::GCEpilogueCallback callback

nodejs/ws - can't run in the browser

I wanted to build an alternative front-end for BitMEX with a few custom trading features (and get free trading) but I can't get bitmex-realtime-api to work in the browser. Here's the webpack config:

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js',
  },
  node: {
    fs: 'empty',
  },
  devtool: 'source-map',
};

Webpack is missing modules (bufferutil, utf-8-validate) and adding separately them leads to "WARNING in ./node_modules/bindings/bindings.js - 81:22-40 Critical dependency: the request of a dependency is an expression"

In the browser console, I get

request.js:132 GET https://www.bitmex.com/realtime 426 (Upgrade Required)
ReconnectingSocket.js:90 WebSocket [ERROR]: Unexpected response from server [426]: Upgrade Required
ReconnectingSocket.js:85 WebSocket [INFO]: The WebSocket will terminate. Please manually reconnect.

and a CORS error,

Failed to load https://www.bitmex.com/api/v1/schema/websocketHelp: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 403.

followed by an exponential backoff trying to reconnect.

c# client - don't use

This client is awful. I'll save you some time now, because I wish someone had for me. The authentication doesn't work because they've done it in a way where the parameters can be reordered so you can sign the message properly without rewriting every. single. function. And the functions are terrible. So much code duplication it's embarrassing.

And despite the readme promising a websocket client -there isn't one.

Just don't use the autogenned swagger library at all, it's actually horrific. Code from scratch using the actual bitmex c# client. (not the autogenned c# client)

Ruby config example

Hi,
I am trying to figure out how to conntect to the API for the first time.

The readme says to use:

SwaggerClient.configure do |config|
  # Configure API key authorization: apiKey
  config.api_key['api-key'] = 'YOUR API KEY'

  # TODO
  # Configure API key authorization: apiNonce
  # config.api_key['api-nonce'] = 'YOUR API KEY'

  # Configure API key authorization: apiSignature
  config.api_key['api-signature'] = 'YOUR API KEY'

  # TODO
end

The docs say that signature is this:

 signature = HEX(HMAC_SHA256(apiSecret, verb + path + str(nonce) + data))

However, that doesn't look like something one puts in a config, just like the nonce that changes for each request. Can we get an example of config + making a an API request?

Delta server issue

I'm trying to use the delta server in light of the coming deprecation of the complete ws orderbook. I'm having some trouble though:

/api-connectors/official-ws/delta-server# node index.js
/root/api-connectors/official-ws/nodejs/index.js:148
    const [table, , symbol] = split;
          ^

SyntaxError: Unexpected token [
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/root/api-connectors/official-ws/delta-server/lib/server.js:5:22)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)

Note that:

  1. 'git clone [email protected]:BitMEX/api-connectors.git' from the docs didn't work for me (no permissions), I cloned using 'git clone https://github.com/BitMEX/api-connectors.git'

  2. I used a package manager to install node.js using 'apt install npm' and 'apt install nodejs-legacy' (because it told me to after trying to start with 'node index.js'

Other than that I followed the documentation to the letter I believe. I can provide more context if needed.

Node.js: example not working

I'm trying to run an example from "official-http/node-swagger" inserting the valid API key, but get an error in console:
Unable to connect: [TypeError: Cannot read property 'add' of undefined]
The error applies to this line:
client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization(key, secret));
Getting an object "client" is normal, but there is no parameter clientAuthorizations.
What could be the problem?

How to install on python 3?

Hi,

What command do I use to install swagger_client? I have tried pip install swagger_client and it does not work.

Thanks

Authorization errors when running delta-server against testnet

When running: node index.js

With the config.js excluding api_id and api_secret, no errors are seen.
When including and id and secret created on https://testnet.bitmex.com/app/apiKeys

The following errors are seen at startup:

Caught Websocket error: Error: unexpected server response (401)
at ClientRequest.response (/Users/bjschnei/code/btc_deriv/third_party/api-connectors/official-ws/nodejs/node_modules/ws/lib/WebSocket.js:719:15)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)

Are endpoints not requiring authentication failing if/when it is provided?

Can't call tradeHistory API from node-js

I'm trying to retrieve tradeHistory data.

I've picked up straight from the provided nodejs example to authenticate API

I see "Signature not valid." error. What am I doing wrong?

var request = require('request');
var crypto = require('crypto');

var apiKey = "";
var apiSecret = "";

var verb = 'GET',
  path = '/api/v1/execution/tradeHistory',
  expires = new Date().getTime() + (60 * 1000), // 1 min in the future
  data = '';

// Pre-compute the postBody so we can be sure that we're using *exactly* the same body in the request
// and in the signature. If you don't do this, you might get differently-sorted keys and blow the signature.
//var postBody = JSON.stringify(data);

var signature = crypto.createHmac('sha256', apiSecret).update(verb + path + expires + postBody).digest('hex');

var headers = {
  'content-type' : 'application/json',
  'Accept': 'application/json',
  'X-Requested-With': 'XMLHttpRequest',
  // This example uses the 'expires' scheme. You can also use the 'nonce' scheme. See
  // https://www.bitmex.com/app/apiKeysUsage for more details.
  'api-expires': expires,
  'api-key': apiKey,
  'api-signature': signature
};

request.post({
    headers: headers,
    url:'https://www.bitmex.com'+path,
    method: verb//,
    //body: postBody
  },
  function(error, response, body) {
    if (error) { console.log(error); }
    console.log(body);
  }
);

API authentication problem

My code always receives "Signature not valid" Am I doing something wrong ?
I tested the encoding function using the example. no problem.
I used a simple JSON string to be sure I am signing the same string that is sent
I don't know what else to try !
I tested the request using httpbin.org. result:

{ "args": {}, "data": "{'symbol':'XBTUSD','orderQty':50}", "files": {}, "form": {}, "headers": { "Accept-Encoding": "gzip", "Api-Key": "vYL7jyiOSVuQ4VansuTSQpeB", "Api-Nonce": "1513088793216", "Api-Signature": "395ac5844b5de5e8147da21816195deea4c9fc0042a40d6a558326edf6fb2fbe", "Connection": "close", "Content-Length": "33", "Content-Type": "application/json; charset=utf-8", "Host": "httpbin.org", "User-Agent": "okhttp/2.7.5" }, "json": null, "origin": "93.37.83.198", "url": "http://httpbin.org/post" }

Here is my java code using OkHttp client:

OkHttpClient client = new OkHttpClient();
private long lastnonce;

public void orderjson() {
String base_url = "http://www.bitmex.com";
String path = "/api/v1/order";
String json = "{"symbol":"XBTUSD","orderQty":50,"price":219.0}";
String response;
String verb = "POST";
lastnonce = System.currentTimeMillis();

//////// TEST encode like on website
//        String json = "";
//        String response;
//        String verb = "GET";
//        String path = "/api/v1/instrument?filter=%7B%22symbol%22%3A+%22XBTM15%22%7D";
//        lastnonce = 1429631577690L;
//         bitmex_secret="chNOOS4KvNXR_Xq4k4c9qsfoKWvnDecLATCRlcBwyKDYnWgO";

String signa = encode(bitmex_secret, verb + path + lastnonce + json);
try{
    response = post(base_url + path, json, signa);
    System.out.println(response);
}
catch (IOException ex){
    ex.printStackTrace();
}

}

String post(String url, String json, String signature) throws IOException {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).addHeader("api-key", bitmex_apikey)
.addHeader("api-nonce", lastnonce + "").addHeader("api-signature", signature).build();

Response response = client.newCall(request).execute();
return response.body().string();

}

public static String encode(String key, String data) {
try{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);

        return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
    }
    catch (InvalidKeyException ex){
        ex.printStackTrace();
    }
    catch (NoSuchAlgorithmException ex){
        ex.printStackTrace();
    }
    catch (UnsupportedEncodingException ex){
        ex.printStackTrace();
    }
    catch (IllegalStateException ex){
        ex.printStackTrace();
    }
    return "";
}

Websocket disconnects when subscribed to transact:*

If I subscribe to the transact:* table, I get disconnected after 1 minute. The websocket will then automatically reconnect and stay connected for one more minute, then it will disconnect again, throw an exception and exit.

Sample code:

const BitMEXClient = require('bitmex-realtime-api')

const client = new BitMEXClient({
    apiKeyID: 'yourtestnetkeyid',
    apiKeySecret: 'suchsecretmuchsecure',
    testnet: true,
})

client.addStream('*', 'transact', function (data, symbol, tableName) {
    console.log(`${tableName}:${symbol} - ${JSON.stringify(data)}`)
});

Output:

WebSocket [INFO]: Connected.    ReconnectingSocket.js:85
{"op":"subscribe","args":"transact:*"}    index.js:179
transact:* - []    index.js:10
transact:* - []    index.js:10
WebSocket [ERROR]: Websocket closed.    ReconnectingSocket.js:90
WebSocket [INFO]: Retry in 1000 ms    ReconnectingSocket.js:85
WebSocket [INFO]: Reconnecting...    ReconnectingSocket.js:85
WebSocket [INFO]: Connected.    ReconnectingSocket.js:85
{"op":"subscribe","args":"transact:*"}    index.js:179
transact:* - []    index.js:10
transact:* - []    index.js:10
WebSocket [ERROR]: Websocket closed.    ReconnectingSocket.js:90
WebSocket [INFO]: Retry in 1000 ms    ReconnectingSocket.js:85
WebSocket [INFO]: Reconnecting...    ReconnectingSocket.js:85
WebSocket [ERROR]: Unexpected response from server [400]: {"error":"Nonce is not increasing. This nonce: 1513803028187, last nonce: 1513803028187"}    ReconnectingSocket.js:90
WebSocket [INFO]: The WebSocket will terminate. Please manually reconnect.    ReconnectingSocket.js:85
WebSocket [ERROR]: Closing Websocket    ReconnectingSocket.js:90

Python server error

I followed the installation instructions for the Python server on Ubuntu 16.04

When I run python3 app.py I get the following error:

Failed to add operation for GET /api/v1/position Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/connexion/api.py", line 237, in add_paths self.add_operation(method, path, endpoint, path_parameters) File "/usr/local/lib/python3.5/dist-packages/connexion/api.py", line 189, in add_operation resolver=self.resolver) File "/usr/local/lib/python3.5/dist-packages/connexion/operation.py", line 179, in __init__ resolution = resolver.resolve(self) File "/usr/local/lib/python3.5/dist-packages/connexion/resolver.py", line 39, in resolve return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id) File "/usr/local/lib/python3.5/dist-packages/connexion/resolver.py", line 65, in resolve_function_from_operation_id raise ResolverError(msg, sys.exc_info()) connexion.exceptions.ResolverError: <ResolverError: Cannot resolve operationId "Position.get"!>

Trying the server code in Ubuntu 13.10 with both Python 2 and 3 gives similar errors.

Any ideas?

urlparse

Hi there,
in the python-swaggerpy the syntax is python3 but in the BitMEXAPIKeyAuthenticator.py there is
'import urlparse' that works on python2 only.

cheers

The program stucked after 'Connected to WS.'

Hi, I used exactly the same main trying to connect to the websocket using endpoint="wss://www.bitmex.com/realtime"

It went through Authentication and successfully connected to WebSocket; however, the program stucked at

if api_key:
self.__wait_for_account()

part. Can anyone tell me what I did wrong here? I tried to copy the whole link to a browser and it says "Upgrade Required"

Please help, thank you very much

How in the world do you use the generated Swagger clients?

Hey guys, love BitMEX but am having a bear of a time figuring out how to use this Swagger-generated typescript-fetch API client. For starters, where in the world do I enter my API key?

Any steps in the right direction would be greatly appreciated at this point.

Thanks!

Python 2 `ImportError: No module named parse`

Please update the imports in /BitMEXAPIKeyAuthenticator.py and change line 57 to parsedURL = urlparse(url) to assure that there is no ImportError: No module named parse when importing bitmex in python 2. The following code works for python 2 and 3.

try:
    from urllib.parse import urlparse
except ImportError:
     from urlparse import urlparse

For a problem description see: Stackoverflow

Or since you are using six:

from six.moves.urllib.parse import urlparse

Python Official API Connector doesn't work at all

Swaggerpy is unmaintained and doesn't support Python 3. I believe we should use Bravado (https://github.com/Yelp/bravado), which is a maintained fork.

The URL in the client definition is dead:

bitMEX = SwaggerClient(
    "https://testnet.bitmex.com/api/explorer/resources",
    http_client=http_client)

I've tried my own version (w/ Bravado):
client = SwaggerClient.from_url('https://www.bitmex.com/api/explorer/swagger.json')
but this fails Swagger spec validation.

It does seem to load the resources correctly though if I force it:

client = SwaggerClient.from_url('https://www.bitmex.com/api/explorer/swagger.json',
                                config={'validate_swagger_spec': False)

I still get errors though when I try to make requests, even if I turn off all (other) validations (as per Bravado docs).

client = SwaggerClient.from_url('https://www.bitmex.com/api/explorer/swagger.json',
                                config={'validate_swagger_spec': False, 'validate_responses':False, 'also_return_response':True, 'use_models': False})

client.Quote.Quote_get(symbol='XBTH17').result()

Is there any chance we can get an up-to-date example of this working with Python?

addStream(symbol, callback) without table doesn't receive data

The README says the tableName is optional and the code uses a '*' if no tableName is given. But if you don't pass one, you get this error as data in the callback (not as a proper error):

Error: Unknown table for BitMEX subscription: *. Available tables are announcement,connected,chat,publicNotifications,instrument,settlement,funding,insurance,liquidation,orderBookL2,orderBook10,quote,trade,quoteBin1m,quoteBin5m,quoteBin1h,quoteBin1d,tradeBin1m,tradeBin5m,tradeBin1h,tradeBin1d,privateNotifications,account,wallet,affiliate,margin,position,transact,order,execution.

client.addStream('XBTUSD', data => {
  console.log(data);
});

AttributeError in config

Traceback (most recent call last): File "\bitmex2.py", line 8, in <module> swagger_client.configuration.api_key['api-key'] = 'XXXXX' AttributeError: module 'swagger_client.configuration' has no attribute 'api_key'

Anyone any idea why it is not accepting this?

Unable to connect to endpoints

Suddenly unable to connect to endpoints on testnet. Was working fine until now.
Getting this below:

File "build\bdist.win32\egg\bravado\http_future.py", line 78, in result
self.response_callbacks)
File "build\bdist.win32\egg\bravado\http_future.py", line 131, in unmarshal_response
raise_on_expected(incoming_response)
File "build\bdist.win32\egg\bravado\http_future.py", line 154, in raise_on_expected
swagger_result=http_response.swagger_result)
HTTPBadRequest: 400 Bad Request: {u'error': {u'message': u'This request has expired - expires is in the past. Current time: 1505170580', u'name': u'HTTPError'

disconnect

hi ,
How to reconnect when lost connection?

Please republish node.js websocket connector to npm

I see there are some bugfixes in the git repository for the node.js ws connector (bitmex-realtime-api).

Specifically I need the expanded const noSymbolTables from the repo.

The published package only has

const noSymbolTables = BitMEXClient.noSymbolTables = [
  'margin',
  'chat'
];

Could you republish when you get a round tuit?

Error for private streams

This is for the api-connectors/official-ws/nodejs/ client.
I'm having a problem using the private streams, see code below (modified example).
The error I get is:

User requested an account-locked subscription but no authorization was provided.

Note that public streams works fine, and the api keys are correct.

var request = require('request');
var crypto = require('crypto');

const BitMEXClient = require('bitmex-realtime-api');
// See 'options' reference below
const client = new BitMEXClient({ testnet: true, apiKeyId: 'KEY-ID', apiKeySecret: 'KEY-SECRET' });

// handle errors here. If no 'error' callback is attached. errors will crash the client.
client.on('error', console.error);
client.on('open', () => console.log('Connection opened.'));
client.on('close', () => console.log('Connection closed.'));
client.on('initialize', () => console.log('Client initialized, data is flowing.'));

client.addStream("XBTU17", 'order', function(data, symbol, tableName) {
    console.log('order data: ', data);
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.