Giter VIP home page Giter VIP logo

coinbase-pro-node's Introduction

Coinbase Pro CircleCI npm version

Note: The gdax package is deprecated and might have to be removed from NPM. Please migrate to the coinbase-pro package to ensure future compatibility.

The official Node.js library for Coinbase's Pro API.

Features

  • Easy functionality to use in programmatic trading
  • A customizable, websocket-synced Order Book implementation
  • API clients with convenient methods for every API endpoint
  • Abstracted interfaces – don't worry about HMAC signing or JSON formatting; the library does it for you

Installation

npm install coinbase-pro

You can learn about the API responses of each endpoint by reading our documentation.

Quick Start

The Coinbase Pro API has both public and private endpoints. If you're only interested in the public endpoints, you should use a PublicClient.

const CoinbasePro = require('coinbase-pro');
const publicClient = new CoinbasePro.PublicClient();

All methods, unless otherwise specified, can be used with either a promise or callback API.

Using Promises

publicClient
  .getProducts()
  .then(data => {
    // work with data
  })
  .catch(error => {
    // handle the error
  });

The promise API can be used as expected in async functions in ES2017+ environments:

async function yourFunction() {
  try {
    const products = await publicClient.getProducts();
  } catch (error) {
    /* ... */
  }
}

Using Callbacks

Your callback should accept three arguments:

  • error: contains an error message (string), or null if no error was encountered
  • response: a generic HTTP response abstraction created by the request library
  • data: contains data returned by the Coinbase Pro API, or undefined if an error was encountered
publicClient.getProducts((error, response, data) => {
  if (error) {
    // handle the error
  } else {
    // work with data
  }
});

NOTE: if you supply a callback, no promise will be returned. This is to prevent potential UnhandledPromiseRejectionWarnings, which will cause future versions of Node to terminate.

const myCallback = (err, response, data) => {
  /* ... */
};

const result = publicClient.getProducts(myCallback);

result.then(() => {
  /* ... */
}); // TypeError: Cannot read property 'then' of undefined

Optional Parameters

Some methods accept optional parameters, e.g.

publicClient.getProductOrderBook('BTC-USD', { level: 3 }).then(book => {
  /* ... */
});

To use optional parameters with callbacks, supply the options as the first parameter(s) and the callback as the last parameter:

publicClient.getProductOrderBook(
  'ETH-USD',
  { level: 3 },
  (error, response, book) => {
    /* ... */
  }
);

The Public API Client

const publicClient = new CoinbasePro.PublicClient(endpoint);
  • productID optional - defaults to 'BTC-USD' if not specified.
  • endpoint optional - defaults to 'https://api.pro.coinbase.com' if not specified.

Public API Methods

publicClient.getProducts(callback);
// Get the order book at the default level of detail.
publicClient.getProductOrderBook('BTC-USD', callback);

// Get the order book at a specific level of detail.
publicClient.getProductOrderBook('LTC-USD', { level: 3 }, callback);
publicClient.getProductTicker('ETH-USD', callback);
publicClient.getProductTrades('BTC-USD', callback);

// To make paginated requests, include page parameters
publicClient.getProductTrades('BTC-USD', { after: 1000 }, callback);

Wraps around getProductTrades, fetches all trades with IDs >= tradesFrom and <= tradesTo. Handles pagination and rate limits.

const trades = publicClient.getProductTradeStream('BTC-USD', 8408000, 8409000);

// tradesTo can also be a function
const trades = publicClient.getProductTradeStream(
  'BTC-USD',
  8408000,
  trade => Date.parse(trade.time) >= 1463068e6
);
publicClient.getProductHistoricRates('BTC-USD', callback);

// To include extra parameters:
publicClient.getProductHistoricRates(
  'BTC-USD',
  { granularity: 3600 },
  callback
);
publicClient.getProduct24HrStats('BTC-USD', callback);
publicClient.getCurrencies(callback);
publicClient.getTime(callback);

The Authenticated API Client

The private exchange API endpoints require you to authenticate with a Coinbase Pro API key. You can create a new API key in your exchange account's settings. You can also specify the API URI (defaults to https://api.pro.coinbase.com).

const key = 'your_api_key';
const secret = 'your_b64_secret';
const passphrase = 'your_passphrase';

const apiURI = 'https://api.pro.coinbase.com';
const sandboxURI = 'https://api-public.sandbox.pro.coinbase.com';

const authedClient = new CoinbasePro.AuthenticatedClient(
  key,
  secret,
  passphrase,
  apiURI
);

Like PublicClient, all API methods can be used with either callbacks or will return promises.

AuthenticatedClient inherits all of the API methods from PublicClient, so if you're hitting both public and private API endpoints you only need to create a single client.

Private API Methods

authedClient.getCoinbaseAccounts(callback);
authedClient.getPaymentMethods(callback);
authedClient.getAccounts(callback);
const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
authedClient.getAccount(accountID, callback);
const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
authedClient.getAccountHistory(accountID, callback);

// For pagination, you can include extra page arguments
authedClient.getAccountHistory(accountID, { before: 3000 }, callback);
const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
authedClient.getAccountTransfers(accountID, callback);

// For pagination, you can include extra page arguments
authedClient.getAccountTransfers(accountID, { before: 3000 }, callback);
const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
authedClient.getAccountHolds(accountID, callback);

// For pagination, you can include extra page arguments
authedClient.getAccountHolds(accountID, { before: 3000 }, callback);
// Buy 1 BTC @ 100 USD
const buyParams = {
  price: '100.00', // USD
  size: '1', // BTC
  product_id: 'BTC-USD',
};
authedClient.buy(buyParams, callback);

// Sell 1 BTC @ 110 USD
const sellParams = {
  price: '110.00', // USD
  size: '1', // BTC
  product_id: 'BTC-USD',
};
authedClient.sell(sellParams, callback);
// Buy 1 LTC @ 75 USD
const params = {
  side: 'buy',
  price: '75.00', // USD
  size: '1', // LTC
  product_id: 'LTC-USD',
};
authedClient.placeOrder(params, callback);
const orderID = 'd50ec984-77a8-460a-b958-66f114b0de9b';
authedClient.cancelOrder(orderID, callback);
// Cancels "open" orders
authedClient.cancelOrders(callback);
// `cancelOrders` may require you to make the request multiple times until
// all of the "open" orders are deleted.

// `cancelAllOrders` will handle making these requests for you asynchronously.
// Also, you can add a `product_id` param to only delete orders of that product.

// The data will be an array of the order IDs of all orders which were cancelled
authedClient.cancelAllOrders({ product_id: 'BTC-USD' }, callback);
authedClient.getOrders(callback);
// For pagination, you can include extra page arguments
// Get all orders of 'open' status
authedClient.getOrders({ after: 3000, status: 'open' }, callback);
const orderID = 'd50ec984-77a8-460a-b958-66f114b0de9b';
authedClient.getOrder(orderID, callback);
const params = {
  product_id: 'LTC-USD',
};
authedClient.getFills(params, callback);
// For pagination, you can include extra page arguments
authedClient.getFills({ before: 3000 }, callback);
authedClient.getFundings({}, callback);
const params = {
  amount: '2000.00',
  currency: 'USD',
};
authedClient.repay(params, callback);
const params =
  'margin_profile_id': '45fa9e3b-00ba-4631-b907-8a98cbdf21be',
  'type': 'deposit',
  'currency': 'USD',
  'amount': 2
};
authedClient.marginTransfer(params, callback);
const params = {
  repay_only: false,
};
authedClient.closePosition(params, callback);
const params = {
  from: 'USD',
  to: 'USDC',
  amount: '100',
};
authedClient.convert(params, callback);
// Deposit to your Exchange USD account from your Coinbase USD account.
const depositParamsUSD = {
  amount: '100.00',
  currency: 'USD',
  coinbase_account_id: '60680c98bfe96c2601f27e9c', // USD Coinbase Account ID
};
authedClient.deposit(depositParamsUSD, callback);

// Withdraw from your Exchange USD account to your Coinbase USD account.
const withdrawParamsUSD = {
  amount: '100.00',
  currency: 'USD',
  coinbase_account_id: '60680c98bfe96c2601f27e9c', // USD Coinbase Account ID
};
authedClient.withdraw(withdrawParamsUSD, callback);

// Deposit to your Exchange BTC account from your Coinbase BTC account.
const depositParamsBTC = {
  amount: '2.0',
  currency: 'BTC',
  coinbase_account_id: '536a541fa9393bb3c7000023', // BTC Coinbase Account ID
};
authedClient.deposit(depositParamsBTC, callback);

// Withdraw from your Exchange BTC account to your Coinbase BTC account.
const withdrawParamsBTC = {
  amount: '2.0',
  currency: 'BTC',
  coinbase_account_id: '536a541fa9393bb3c7000023', // BTC Coinbase Account ID
};
authedClient.withdraw(withdrawParamsBTC, callback);

// Fetch a deposit address from your Exchange BTC account.
const depositAddressParams = {
  currency: 'BTC',
};
authedClient.depositCrypto(depositAddressParams, callback);

// Withdraw from your Exchange BTC account to another BTC address.
const withdrawAddressParams = {
  amount: 10.0,
  currency: 'BTC',
  crypto_address: '15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy',
};
authedClient.withdrawCrypto(withdrawAddressParams, callback);
// Schedule Deposit to your Exchange USD account from a configured payment method.
const depositPaymentParamsUSD = {
  amount: '100.00',
  currency: 'USD',
  payment_method_id: 'bc6d7162-d984-5ffa-963c-a493b1c1370b', // ach_bank_account
};
authedClient.depositPayment(depositPaymentParamsUSD, callback);
// Withdraw from your Exchange USD account to a configured payment method.
const withdrawPaymentParamsUSD = {
  amount: '100.00',
  currency: 'USD',
  payment_method_id: 'bc6d7162-d984-5ffa-963c-a493b1c1370b', // ach_bank_account
};
authedClient.withdrawPayment(withdrawPaymentParamsUSD, callback);
// Get your 30 day trailing volumes
authedClient.getTrailingVolume(callback);

Websocket Client

The WebsocketClient allows you to connect and listen to the exchange websocket messages.

const websocket = new CoinbasePro.WebsocketClient(['BTC-USD', 'ETH-USD']);

websocket.on('message', data => {
  /* work with data */
});
websocket.on('error', err => {
  /* handle error */
});
websocket.on('close', () => {
  /* ... */
});

The client will automatically subscribe to the heartbeat channel. By default, the full channel will be subscribed to unless other channels are requested.

const websocket = new CoinbasePro.WebsocketClient(
  ['BTC-USD', 'ETH-USD'],
  'wss://ws-feed-public.sandbox.pro.coinbase.com',
  {
    key: 'suchkey',
    secret: 'suchsecret',
    passphrase: 'muchpassphrase',
  },
  { channels: ['full', 'level2'] }
);

Optionally, change subscriptions at runtime:

websocket.unsubscribe({ channels: ['full'] });

websocket.subscribe({ product_ids: ['LTC-USD'], channels: ['ticker', 'user'] });

websocket.subscribe({
  channels: [
    {
      name: 'user',
      product_ids: ['ETH-USD'],
    },
  ],
});

websocket.unsubscribe({
  channels: [
    {
      name: 'user',
      product_ids: ['LTC-USD'],
    },
    {
      name: 'user',
      product_ids: ['ETH-USD'],
    },
  ],
});

The following events can be emitted from the WebsocketClient:

  • open
  • message
  • close
  • error

Orderbook

Orderbook is a data structure that can be used to store a local copy of the orderbook.

const orderbook = new CoinbasePro.Orderbook();

The orderbook has the following methods:

  • state(book)
  • get(orderId)
  • add(order)
  • remove(orderId)
  • match(match)
  • change(change)

Orderbook Sync

OrderbookSync creates a local mirror of the orderbook on Coinbase Pro using Orderbook and WebsocketClient as described here.

const orderbookSync = new CoinbasePro.OrderbookSync(['BTC-USD', 'ETH-USD']);
console.log(orderbookSync.books['ETH-USD'].state());

Testing

npm test

# test for known vulnerabilities in packages
npm install -g nsp
nsp check --output summary

coinbase-pro-node's People

Contributors

a--hoang avatar adityamertia avatar alexmarkley avatar amejiarosario avatar aneyzberg avatar aricallen avatar awitherow avatar blair avatar cilphex avatar cjs77 avatar codyaray avatar dereksan avatar eddiew avatar fb55 avatar givanse avatar gsee avatar kenfehling avatar lawrencegs avatar lisbakke avatar maksim-s avatar mihar avatar mjesuele avatar passabilities avatar pooleja avatar rigtorp avatar rmm5t avatar sds avatar sh6khan avatar stridentbean avatar wilwade 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

coinbase-pro-node's Issues

OrderbookSync Assertion Error: `order.id` and `match.maker_order_id` not equal

Hey hey. I'm using OrderbookSync and in the latest code from master I'm getting this error shortly after the websocket connects (leaving some of my logging in here for context):

Opening connection and loading order book...
Book loaded.
Best Ask: 173.99 ⬇︎
Best Bid: 173.98 ⬇︎

Book loaded.

/Users/matt/dev/arby/node_modules/gdax/lib/orderbook.js:137
    assert.equal(order.id, match.maker_order_id);
           ^
AssertionError: 'c4e57d1d-7cd5-4286-bac3-11ee67fe7618' == '5f2367bb-070e-4838-bbcc-b163ff4e127e'
    at Orderbook.prototype.match (/Users/matt/dev/arby/node_modules/gdax/lib/orderbook.js:137:12)
    at OrderbookSync.prototype.processMessage (/Users/matt/dev/arby/node_modules/gdax/lib/orderbook_sync.js:128:14)
    at OrderbookSync.prototype.onMessage (/Users/matt/dev/arby/node_modules/gdax/lib/orderbook_sync.js:51:12)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:194:7)
    at Receiver._receiver.onmessage (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/WebSocket.js:146:54)
    at Receiver.dataMessage (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/Receiver.js:389:14)
    at Receiver.getData (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/Receiver.js:330:12)
    at Receiver.startLoop (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/Receiver.js:165:16)
    at Receiver.add (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/Receiver.js:139:10)
    at TLSSocket._ultron.on (/Users/matt/dev/arby/node_modules/gdax/node_modules/ws/lib/WebSocket.js:142:22)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at TLSSocket.Readable.push (_stream_readable.js:136:10)
    at TLSWrap.onread (net.js:560:20)

Any help would be appreciated. Thanks!

cb-access-key is not allowed by Access-Control-Allow-Headers

I'm trying to use the library from the browser and I see this:

Fetch API cannot load https://api.gdax.com/accounts. Request header field cb-access-key is not allowed by Access-Control-Allow-Headers in preflight response.

From this forum thread it is suggested that what might be happening is that the message is not signed.

However the library does it.

var sig = signRequest(auth, method, relativeURI, opts);

The only way to solve for this is to have the backend add the headers to the preflight response. Is it something that could happen?

Parameters not being respected by the library

I've tried to get the candles using the library, but it does not respect the data passed on the optional parameters, I've tried many combinations of the object, and I cannot get it to work. I always get a response back that is standard, as if no parameters are being passed.

I see from this line of code https://github.com/coinbase/gdax-node/blob/381b7282825f6df658cf937f7b2edd45016632b6/lib/clients/public.js#L77 that it's passing the parameters in the header, I don't know if gdax API understands this, but it seems to not see them.

Here's what I'm doing:

        const pc = new gdax.PublicClient(args.market);
        let start = moment().subtract(1, 'days');
        const end = moment().toISOString();
        let granularity = 3600;

        pc.getProductHistoricRates(
          { start: start.toISOString(), end: moment(end).toISOString(), granularity },
          (err, response, data) => {
            console.log(start.toISOString(), end);
            const items = data.map(item => ({
              time: new Date(item[0] * 1000),
              low: item[1],
              high: item[2],
              open: item[3],
              close: item[4],
              volume: item[5]
            }));

            return items;
          }
        );

WebsocketClient RangeError

Using Node v6.6.0 on Mac OSX - 2.3GHz i7 w. 16gb RAM
Usually happens within the first 10 seconds.

/path/to/project/node_modules/ws/lib/Receiver.js:382
    default: srcBuffer.copy(dstBuffer, dstOffset, 0, length); break;
                       ^

RangeError: out of range index
at RangeError (native)
at fastCopy (/path/to/project/node_modules/ws/lib/Receiver.js:382:24)
at Receiver.add (/path/to/project/node_modules/ws/lib/Receiver.js:82:3)
at TLSSocket.firstHandler (/path/to/project/node_modules/ws/lib/WebSocket.js:775:22)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
at TLSWrap.onread (net.js:543:20)

Also getting:

SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at WebsocketClient.prototype.onMessage (/path/to/project/node_modules/gdax/lib/clients/websocket.js:68:31)

Promise example returns error

Hello everyone,

why is the call of the following most basic example (highlighted in the readme) giving an "must supply a callback" error?

async function yourFunction() {
  try {
    const products = await publicClient.getProducts();
  } catch(error) {
    /* ... */
  }
}

yourFunction(); 

Tried in Node 8.3.0 which supports async/await.

Regards,
Michael

Canceling all orders does not cancel stop order

When I call cancelOrders (or cancelAllOrders) from an AuthenticatedClient, it returns 0 cancelled orders even though I have one active buy-stop order on the BTC-EUR product.
Calling cancelOrder with the correct orderID works fine, although from time-to-time also this method fails with the status code: 400.

promise implementation does not seem to work

Despite the documented promise-approach I am getting the follow error:

wip/node_modules/gdax/lib/clients/public.js:57
throw "Must supply a callback."

index.js

const Gdax = require('gdax');
const publicClient = new Gdax.PublicClient();

publicClient
  .getProducts()
  .then(data => {
      // work with data
  })
  .catch(error => {
     // handle the error
  });

OrderbookSync throws error in a callback

OrderbookSync throws an error inside the callback cb, see e.g. the line:

throw 'Failed to load orderbook: ' + err;

in lib/orderbook_sync.js. This error is thrown, for instance, when there is no internet connection.
It is not easy to catch this kind of error in a client application. One option how to fix this problem would be to emit the error (instead of throwing it), e.g.:

self.emit('error', 'Failed to load orderbook: ' + err);
return;

OrderbookSync fails on startup

Hi there,

I'm getting an error that I don't think is just me with OrderbookSync: it throws an error when it's initialized, saying "TypeError: self.connect is not a function"

at Object.WebsocketClient (/node_modules/gdax/lib/clients/websocket.js:22:8)
at Object.OrderbookSync (/node_modules/gdax/lib/orderbook_sync.js:22:19)

Proposal: Switch to level 2 book

We recently switched the website (https://www.gdax.com) to a level 2 book (only price levels, no specific orders). This vastly reduced the bandwidth requirements for clients and allows us to send the entire book when initially subscribing. It also means clients do not need to take care of potentially dropped messages on the full feed.

The goal of this issue is to get some feedback on whether this switch would be an option for this library as well. Most trading bots probably aren't interested in the exact orders — perhaps to get an idea of the execution order (as this is FIFO), but even that should be rare.

Please leave a comment if you have any concerns!

WS - SyntaxError: Unexpected end of JSON input

First reported here:
https://community.coinbase.com/t/unexpected-end-of-json-input-error-with-gdax-library-for-node-js/12382

undefined:1
{"type":"done","order_type":"limit","side":"sell","sequence":1411617737,"order_id":"7741a72e-0635-4fd9-a8ca-d9d3afd65fa6","reason":"canceled","product_id":"BTC-USD","time":"2016-08-23T00:24:17.125397Z","price":"585.26","remaining_size":"0.97"


SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at prototype.onMessage (myproject/node_modules/gdax/lib/clients/websocket.js:68:31)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (myproject/node_modules/ws/lib/WebSocket.js:798:10)

Websocket error

When following documentation to start websocket with gdax get his error:

TypeError: must start with number, buffer, array or string

previous coinbase-exchange module doesn't have this error so i'm downgrading back to that.

Uncaught TypeError: punycode.toASCII is not a function version 0.4.2 package not working.

gdax version ^0.4.2

url.js:295 Uncaught TypeError: punycode.toASCII is not a function
    at Url.parse (url.js:295)
    at Object.urlParse [as parse] (url.js:106)
    at Request.init (request.js:238)
    at new Request (request.js:129)
    at request (index.js:55)
    at PublicClient.prototype.request (public.js:64)
    at apply (index.js:72)
    at PublicClient.wrapper [as get] (index.js:415)
    at PublicClient.prototype.getProductTicker (public.js:92)
    at src.js:72
Url.parse @ url.js:295
urlParse @ url.js:106
Request.init @ request.js:238
Request @ request.js:129
request @ index.js:55
prototype.request @ public.js:64
apply @ index.js:72
wrapper @ index.js:415
prototype.getProductTicker @ public.js:92

Anyone else experiencing this on 0.4.2 of this library?

npm install fails

At some point before the name change, npm install began to fail due to a breaking changes in its dependencies. The error message is:

[email protected] install A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws
(node-gyp rebuild 2> builderror.log) || (exit 0)

A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws>if not defined npm_config_node_gyp (node "C:\Users\deste\Apps\nodejs\node_modules\npm\bin\node-gyp-bin....\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
bufferutil.cc
a:\archives\source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan_implementation_12_inl.h(172): error C2660: 'v8::Signature::New': function does not take 4 arguments [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(167): error C2995: 'v8::Local _NanEnsureLocal(v8::Local)': function template has already been defined [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(160): note: see declaration of '_NanEnsureLocal'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C3083: 'smalloc': the symbol to the left of a '::' must be a type [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C2039: 'FreeCallback': is not a member of 'node' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_object_wrap.h(8): note: see declaration of 'node'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C2061: syntax error: identifier 'FreeCallback' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(504): error C2065: 'callback': undeclared identifier [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(504): error C2065: 'hint': undeclared identifier [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(511): error C2665: 'node::Buffer::New': none of the 4 overloads could convert all the argument types [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(43): note: could be 'v8::MaybeLocalv8::Object node::Buffer::New(v8::Isolate *,char *,size_t)'
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(31): note: or 'v8::MaybeLocalv8::Object node::Buffer::New(v8::Isolate *,v8::Localv8::String,node::encoding)'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(511): note: while trying to match the argument list '(v8::Isolate *, const char *, uint32_t)'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(515): error C2440: 'return': cannot convert from 'v8::MaybeLocalv8::Object' to 'v8::Localv8::Object' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(515): note: No constructor could take the source type, or constructor overload resolution was ambiguous
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(522): error C2039: 'Use': is not a member of 'node::Buffer' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(8): note: see declaration of 'node::Buffer'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(522): error C3861: 'Use': identifier not found [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\bufferutil.vcxproj]
validation.cc
a:\archives\source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan_implementation_12_inl.h(172): error C2660: 'v8::Signature::New': function does not take 4 arguments [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(167): error C2995: 'v8::Local _NanEnsureLocal(v8::Local)': function template has already been defined [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(160): note: see declaration of '_NanEnsureLocal'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C3083: 'smalloc': the symbol to the left of a '::' must be a type [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C2039: 'FreeCallback': is not a member of 'node' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_object_wrap.h(8): note: see declaration of 'node'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(500): error C2061: syntax error: identifier 'FreeCallback' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(504): error C2065: 'callback': undeclared identifier [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(504): error C2065: 'hint': undeclared identifier [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(511): error C2665: 'node::Buffer::New': none of the 4 overloads could convert all the argument types [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(43): note: could be 'v8::MaybeLocalv8::Object node::Buffer::New(v8::Isolate *,char *,size_t)'
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(31): note: or 'v8::MaybeLocalv8::Object node::Buffer::New(v8::Isolate *,v8::Localv8::String,node::encoding)'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(511): note: while trying to match the argument list '(v8::Isolate *, const char *, uint32_t)'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(515): error C2440: 'return': cannot convert from 'v8::MaybeLocalv8::Object' to 'v8::Localv8::Object' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(515): note: No constructor could take the source type, or constructor overload resolution was ambiguous
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(522): error C2039: 'Use': is not a member of 'node::Buffer' [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
C:\Users\deste.node-gyp\4.4.0\include\node\node_buffer.h(8): note: see declaration of 'node::Buffer'
A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\node_modules\nan\nan.h(522): error C3861: 'Use': identifier not found [A:\Archives\Source\current\destenson\coinbase--gdax-node\node_modules\ws\build\validation.vcxproj]
npm WARN deprecated [email protected]: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated [email protected]: lodash@<3.0.0 is no longer maintained. Upgrade to lodash@^4.0.0.
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
[email protected] node_modules\async

[email protected] node_modules\num
└── [email protected]

[email protected] node_modules\bintrees

[email protected] node_modules\lodash.partial
├── [email protected]
├── [email protected]
└── [email protected] ([email protected])

[email protected] node_modules\lodash.assign
├── [email protected] ([email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected])

[email protected] node_modules\lodash.foreach
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected] ([email protected])

[email protected] node_modules\request
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected])

[email protected] node_modules\mocha
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected])

[email protected] node_modules\nock
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
└── [email protected] ([email protected], [email protected], [email protected])

[email protected] node_modules\ws
├── [email protected]
├── [email protected]
└── [email protected]

Project roadmap?

Hi All,

In diving into this library's code, I have accumulated several questions about its design and many ideas for future features.

Is there some larger project roadmap? Even just to release v1.0… I would love to open issues to ask questions and discuss and work on features, but I don't want to spam anyone or start working on things that significantly diverge from what the maintainers intend to support.

Thanks! 😄

Long-running WebSocket connection stops sending data

I have the following code listening for trade matches:

webSocket.on('message', data => {
  if (data.type === 'match') {
    // Trade occurred
    console.log(`${data.side} ${data.size} ${data.product_id} @ ${data.price} @ ${data.time}`);
});

After a variable amount of time (typically a few hours), the socket stops receiving any messages. I have not seen any errors.

Any idea what might be going on? The setup is as followes:

const Gdax = require('gdax');

const products = {
  'BTC-USD': { vol: 0 },
  'ETH-USD': { vol: 0 },
  'LTC-USD': { vol: 0 },
  'BTC-EUR': { vol: 0 },
  'ETH-EUR': { vol: 0 },
  'LTC-EUR': { vol: 0 },
  'BTC-GBP': { vol: 0 },
  'ETH-GBP': { vol: 0 },
  'ETH-BTC': { vol: 0 },
};
const webSocket = new Gdax.WebsocketClient(Object.keys(products));

Version 0.4.3 orderbook isn't kept updated

I've created two test repos, one with 0.4.2 and one with 0.4.3 (master). They each print out the top bid and ask every few seconds.

0.4.2 repo
0.4.3 repo

I recorded results for each started at approximately the same time, not exactly so the values are slightly different, but the main finding is that after about a minute the 0.4.3 version begins to get stale on one side of the order book (in this instance the ask side, not sure if that's always the case).

0.4.2

2963.87 2962.96
2963.91 2962.94
2963.94 2963.86
2963.94 2963.28
2963.86 2959.02
2964.97 2961.73
2964.98 2964.21
2964.96 2964.2
2964.94 2964.16
2965.6 2964.61

0.4.3

2963.9 2962.51
2963.88 2962.51
2963.9 2963.79
2963.9 2963.79
2963.88 2962.51
2963.9 2962.51
2963.9 2964.21
2963.9 2964.2
2963.9 2964.16
2963.9 2964.55

How to pass options/parameters to API methods

This is possibly a dumb question but I don't understand how to pass options to the API methods. For example, in publicClient.getProduct24HrStats((err, res, data) => { }), where do I specify that I want the stats on Ethereum, not Bitcoin? Is this possible?

Filled orders receive no price

I am using the websocket api and subscribing to various products like BTC-USD and receiving lots of orders that come back as filled, but don't return a price. Is there a reason for this?
screen shot 2017-06-22 at 9 02 48 pm

Error: getaddrinfo ENOTFOUND api.gdax.com api.gdax.com:443

I am not sure which method is doing this, but the error handling functionality of gdax-node does not seem to be working much at all if these errors are not being passed to the err prop in the callback. They are slipping into the data prop and not working with the way I am using promises to resolve and reject all the functions this project has to offer.

punycode.toASCII is not a function

src.js:75 TypeError: punycode.toASCII is not a function
    at Url.parse (url.js:295)
    at Object.urlParse [as parse] (url.js:106)
    at Request.init (request.js:239)
    at new Request (request.js:130)
    at request (index.js:54)
    at Promise (public.js:79)
    at Promise (<anonymous>)
    at PublicClient.request (public.js:78)
    at PublicClient.get (public.js:12)
    at PublicClient.getProductTicker (public.js:108)

It appears that the version of the request.js url.js package is using a version of punycode that does not work.

I am using npm version 5.4.0, maybe this is the problem? What recommended versions do you suggest for use in this project?

I am using the coinbase/gdax-node install version, and also experienced this when installing from npm on version ^0.4.2

WebsocketClient fails

code:

new Gdax.WebsocketClient();

output:

{ type: 'done',
  order_type: 'limit',
  side: 'sell',
  sequence: 1286880417,
  order_id: '59719169-ac79-4e55-99c7-64ea487d6ed7',
  reason: 'canceled',
  product_id: 'BTC-USD',
  time: '2016-07-24T21:59:50.613571Z',
  price: '662.48',
  remaining_size: '0.29' }
undefined:1
{"type":"done","order_type":"limit","side":"sell","sequence":1286880418,"order_id":"5160f16e-264b-4e24-8adf-ca988b6c4d26","reason":"canceled","product_id":"BTC-USD","time":"2016-07-24T21:59:50.63179Z","price":"662.39","remaining_size":"0.43"



SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at prototype.onMessage (/mnt/c/Users/John Jelinek/Documents/gdax/node_modules/gdax/lib/clients/websocket.js:68:31)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (/mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/WebSocket.js:798:10)
    at /mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/Receiver.js:473:18
    at /mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/Receiver.js:357:7
    at /mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/PerMessageDeflate.js:217:5
    at afterWrite (_stream_writable.js:361:3)
    at onwrite (_stream_writable.js:352:7)

I can't seem to swallow this error.

needs to be upgraded to 0.4.3 on npm ASAP

I have huge problem of using OrderbookSync when I follow the docs on github
After going back to check the source code, I saw a huge difference between the code on github and the one I installed via npm.

If the documentation is for version 0.4.3, then we should publish this version to npm

OrderbookSync does not reconnect when socket connection is lost

When the socket connection is lost, OrderbookSync ends up in a stale state (it does not attempt to re-connect and thus also stops updating the underlying orderbook).

I have "solved" this issue in my app by re-connecting the orderbook whenever the last update is older than few minutes. However, it would be better if this was fixed in the master branch.

OrderbookSync RangeError

code:

var Gdax = require('gdax');
var orderbookSync = new Gdax.OrderbookSync('ETH-USD')

then just wait a little and ...

RangeError: out of range index
    at RangeError (native)
    at fastCopy (/mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/Receiver.js:382:24)
    at Receiver.add (/mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/Receiver.js:82:3)
    at TLSSocket.firstHandler (/mnt/c/Users/John Jelinek/Documents/gdax/node_modules/ws/lib/WebSocket.js:775:22)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:177:18)
    at TLSSocket.Readable.push (_stream_readable.js:135:10)
    at TLSWrap.onread (net.js:542:20)

TypeError: Cannot read property 'isValidUTF8' of undefined (Websocket)

Hi, I'm creating a very simple socket client to listen to Gdax server, but I always get this problem.

The code:

import request from 'request-promise';
import config from 'config';
import Gdax from 'gdax';

// get all assets pairs
const opts = {
  url: `${config.exchanges.gdax.api}/products`,
  headers: {
    'User-Agent': 'myapp'
  },
  json: true
};

request(opts)
  .then(data => data.map(d => d.id))
  .then((assets) => {
    const websocket = new Gdax.WebsocketClient(assets);
    websocket.on('message', (data) => {
      console.log(data);
    });
  })
  .catch((err) => {
    console.log(err.message);
  });

The error:

/Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:532
            if (!Validation.isValidUTF8(messageBuffer)) {
                           ^

TypeError: Cannot read property 'isValidUTF8' of undefined
    at Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:532:28
    at Receiver.applyExtensions (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:371:5)
    at Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:508:14
    at Receiver.flush (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:347:3)
    at Receiver.finish (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:541:12)
    at Receiver.expectHandler (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:499:31)
    at Receiver.add (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/Receiver.js:103:24)
    at TLSSocket.realHandler (Projects/exchanges/node_modules/gdax/node_modules/ws/lib/WebSocket.js:825:20)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at TLSSocket.Readable.push (_stream_readable.js:136:10)
    at TLSWrap.onread (net.js:561:20)
[nodemon] app crashed - waiting for file changes before starting...

After some searching, some people with the same issue said is something about the ws module version and is incompatibility with utf-8-validate. I've tried everything with every version and nothing.

Thank you!

"Size" parameter always required for Market orders

According to https://docs.gdax.com/#place-a-new-order:

MARKET ORDER PARAMETERS

Param   Description
size    [optional]* Desired amount in BTC
funds   [optional]* Desired amount of quote currency to use

* One of size or funds is _required.

So, the following should work to place an order:

var buyParams = {
    'funds': 1, // USD,
    'currency': 'BTC',
    'type': 'market',
};
authedClient.buy(buyParams, callback);

Anyway, it looks like size is always required rather than just one of size or funds.

WebsocketClient error

Executing the code below (example from the readme)

const Gdax = require("gdax");
var websocket = new Gdax.WebsocketClient(['BTC-USD']);
websocket.on('message', function(data) { console.log(data); });

fails with

/myproject/node_modules/gdax/node_modules/ws/lib/Sender.js:206
      bufferUtil.mask(data, mask, outputBuffer, dataOffset, dataLength);
                ^

TypeError: Cannot read property 'mask' of undefined
    at Sender.frameAndSend (/myproject/node_modules/gdax/node_modules/ws/lib/Sender.js:206:17)
    at /myproject/node_modules/gdax/node_modules/ws/lib/Sender.js:126:12
    at /myproject/node_modules/gdax/node_modules/ws/lib/PerMessageDeflate.js:313:5
    at afterWrite (_stream_writable.js:430:3)
    at onwrite (_stream_writable.js:421:7)
    at afterTransform (_stream_transform.js:102:3)
    at TransformState.afterTransform (_stream_transform.js:75:12)
    at Zlib.callback (zlib.js:485:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! collector@1.0.0 start: `node ./src/scripts/start.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the collector@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
x

Using node v8.1.1.

Add support for promises

Are there currently any plans to add promise support in the API clients? It would be very nice for those who like to write promise-style rather than use callbacks.

To use an example from the README, the following code:

var callback = function(err, response, data) {
  // your code here.
};

authedClient.getOrders({'after': 3000}, callback);

…could instead be used as:

authedClient.getOrders({'after': 3000})
  .then(result => {
    let { data, response } = result; // Still expose underlying response object?
    /* do stuff with data */
  })
  .catch(err => { /* handle error */ });

Furthermore, returning a promise would also allow for use with async/await, e.g.

async function myFunction() {
  try {
    let { data, response } = await authedClient.getOrders({'after': 3000});
    /* do stuff with data */
  } catch (err) { /* handle error */ }
}

From an implementation perspective, I think it would be totally possible for the same functions to support callbacks and promises at the same time, without making any breaking changes. For example, existing functions could run callbacks as normal if provided and return a promise if no callback is provided. Or, as the current API call functions don't return anything, they could just always return a promise (but still execute a callback if provided).

I haven't been able to find any documentation about minimum versions of Node that this project must/wants to support, but with PR #40 starting to overhaul and ES6-ify things, I'm guessing that using native ES6 promises would be fine platform-support-wise.

I also haven't seen any contributing guidelines, but I'd be happy to pitch in and help implement this if it's something more people would like.

OrderbookSync returns stale data

Hi, when creating OrderbookSync as follows:

this._orderbookSync = new Gdax.OrderbookSync(
      productIds, apiURI, websocketURI, this._authClient);

And then reading the bid / ask prices as follows:

let state = this._orderbookSync.books[productId].state();
let bid = state.bids[0].price;
let ask = state.asks[0].price;

What happens is that bid or ask prices stop being updated (after some time) and become stale (inconsistent with what I see on https://www.gdax.com/trade/). This happens randomly, but often enough, that I have to re-create OrderbookSync almost every minute. Is there a bug? (It used to work fine before).

I have used ETH-EUR product.

how can i avoid fees? the fees eating the MM bot!

I am using following code for Orders. But Gdax is taking the fees on any orders. How can I avoid the fees? How can I put the limit order?

const OrderParams = {
  'price': price,  
  'size': ordersize,   
  'product_id': Pair ,
};

authedClient.buy(OrderParams, (error, response, data) => {
				if (error){
					console.log(error);
					return false; 
				}
				else {
					res.send(response.body);
					const d  = response.body; 
					return true;
			}

authedClient.sell(OrderParams, (error, response, data) => {
				if (error){
					console.log(error);
					console.log(response.body);
				}
				else {

					res.send(response.body);
					return true;
				}

Can't add product-id to getProductTicker()

How can I specify a different product-id? I mean something like this is not working now.

publicClient.getProductTicker('BTC-EUR', function(err, response, data) {
	console.log(err);
	console.log(data);
});

Publish current version to npm

There is a critical fix to #3 that is needed for anyone running node v6.3+ already committed into this repository. Please publish this fix to npm so that we can benefit from it!

Why not to expose placeOrder function?

I think it's good to make public placeOrder and just set side as sell or buy

  _placeOrder(params, callback) {
    let requiredParams = ['side', 'product_id'];
    // ....
    return this.post(['orders'], { body: params }, callback);
  }

  buy(params, callback) {
    params.side = 'buy';
    return this._placeOrder(params, callback);
  }

  sell(params, callback) {
    params.side = 'sell';
    return this._placeOrder(params, callback);
  }

In the meantime, I have to do something like placeOrder in my code to work around it...

function setOrder(params) {
  params.product_id = params.product_id || 'BTC-USD';
  debug('executing GDAX order: %o', params);
  
  if(params.side === 'buy') {
    return authedClient().buy(params);
  } else if (params.side === 'sell') {
    return authedClient().sell(params);
  } else {
    console.warn(`Invalid order side ${params.side}`);
  }
}

getAccounts 400, request timestamp expired

I have recently launched my server and whenever I run the authClient.getAccounts() command... here is what happens:

I get a 400 response, and the data property from the callback returns the following output:

{
    message: "request timestamp expired"
}

Why is the request timestamp expired when I am running a brand new instance of the server?

Why is a 400 response not returning an error?

b64secret - missunderstanding

Due to authenticate user, can i get some help?

const key = 'your_api_key';
const b64secret = 'your_b64_secret';
const passphrase = 'your_passphrase';

const apiURI = 'https://api.gdax.com';
const sandboxURI = 'https://api-public.sandbox.gdax.com';

const authedClient = new Gdax.AuthenticatedClient(key, b64secret, passphrase, apiURI);

Now i used b64secret as a string a got when i generated apiKey on gdex.
After calling methods on autherClient i get:
TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object. using API nodejs

How should i manage b64secret? What is it? Where can i get it?

Authenticated getProductOrderBook overridden

Is there a particular reason why the authenticated getProductOrderBook is overridden as function(args, productId, callback)? The change of arguments from the public version getProductOrderBook = function(args, callback) is not documented anywhere but the source.

Reliable way to get price updates?

I'm trying to figure out a way to get current price reliably. At the moment my approach is to use websocket and listen for match events where I get price from.

But if volume is low i.e. LTC-EUR pair, these matches happen very very rarely, sometimes even don't happen at all within 5 minute period. I was trying to go through gdax docs and this was recommended way to get price updates, but doesn't look too accurate fro me at the moment, hence this question to see if there is a better way.

getProductTrades swallows errors

You should implement the callback pattern, it makes a developers life a lot easier and i would argue it is good practice to do in a crazy untyped language like javascript.

a callback should be of the form:
function callback(error,result) { }

If my understanding is correct:
The first callback argument is null or undefined;
The second argument contains the callback results.
On the other hand, if an error occurred:
the first argument contains an error object, an instance of the JavaScript Error class (or sub-class) that describes the error;
the second argument will be undefined.

Your getProductTrades function at least, is returning null for the error parameter regardless of a success of failure. So what is even it's use and why is it mentioned as part of your specific callback?

API Rate Limiting

(Inspired by @awitherow's question)

Right now it seems that the only method that has any notion of API rate limiting is PublicClient.fetchTrades.

I think it would be a good idea to somehow abstract rate limiting lower down closer to the actual http/request calls so that all of the clients' methods can use it transparently.

Looking at docs.gdax.com/#rate-limits, it says that

When a rate limit is exceeded, a status of 429 Too Many Requests will be returned.

REST API

PUBLIC ENDPOINTS
We throttle public endpoints by IP: 3 requests per second, up to 6 requests per second in bursts.
ENDPOINTS
We throttle private endpoints by user ID: 5 requests per second, up to 10 requests per second in bursts.

Knowing these limits, and with a single internal handler of rate limiting, we could theoretically keep track of the requests going out and preemptively hold them (maybe even in a queue) if it would be expected to return a 429 anyways. That way, we wouldn't have to wait an entire RTT to find out that we hit a limit, potentially having tried to fire off more in the meantime.

Sidenote: I'm not sure what GDAX defines as "bursts", I haven't found anything about it elsewhere in the docs.

Error: socket hang up

I just recently started getting this, and I'm not sure what is causing it or how to handle it.
Do you know what is causing it o what the fix would be?

{ Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1124:19)
at TLSSocket.g (events.js:291:16)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9) code: 'ECONNRESET' }

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.