项目作者: coinbase

项目描述 :
DEPRECATED — The official Node.js library for Coinbase Pro
高级语言: JavaScript
项目地址: git://github.com/coinbase/coinbase-pro-node.git
创建时间: 2016-07-18T22:02:53Z
项目社区:https://github.com/coinbase/coinbase-pro-node

开源协议:Apache License 2.0

下载


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

  1. 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.

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

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

Using Promises

  1. publicClient
  2. .getProducts()
  3. .then(data => {
  4. // work with data
  5. })
  6. .catch(error => {
  7. // handle the error
  8. });

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

  1. async function yourFunction() {
  2. try {
  3. const products = await publicClient.getProducts();
  4. } catch (error) {
  5. /* ... */
  6. }
  7. }

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
  1. publicClient.getProducts((error, response, data) => {
  2. if (error) {
  3. // handle the error
  4. } else {
  5. // work with data
  6. }
  7. });

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.

  1. const myCallback = (err, response, data) => {
  2. /* ... */
  3. };
  4. const result = publicClient.getProducts(myCallback);
  5. result.then(() => {
  6. /* ... */
  7. }); // TypeError: Cannot read property 'then' of undefined

Optional Parameters

Some methods accept optional parameters, e.g.

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

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

  1. publicClient.getProductOrderBook(
  2. 'ETH-USD',
  3. { level: 3 },
  4. (error, response, book) => {
  5. /* ... */
  6. }
  7. );

The Public API Client

  1. 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

  1. publicClient.getProducts(callback);
  1. // Get the order book at the default level of detail.
  2. publicClient.getProductOrderBook('BTC-USD', callback);
  3. // Get the order book at a specific level of detail.
  4. publicClient.getProductOrderBook('LTC-USD', { level: 3 }, callback);
  1. publicClient.getProductTicker('ETH-USD', callback);
  1. publicClient.getProductTrades('BTC-USD', callback);
  2. // To make paginated requests, include page parameters
  3. publicClient.getProductTrades('BTC-USD', { after: 1000 }, callback);

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

  1. const trades = publicClient.getProductTradeStream('BTC-USD', 8408000, 8409000);
  2. // tradesTo can also be a function
  3. const trades = publicClient.getProductTradeStream(
  4. 'BTC-USD',
  5. 8408000,
  6. trade => Date.parse(trade.time) >= 1463068e6
  7. );
  1. publicClient.getProductHistoricRates('BTC-USD', callback);
  2. // To include extra parameters:
  3. publicClient.getProductHistoricRates(
  4. 'BTC-USD',
  5. { granularity: 3600 },
  6. callback
  7. );
  1. publicClient.getProduct24HrStats('BTC-USD', callback);
  1. publicClient.getCurrencies(callback);
  1. 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).

  1. const key = 'your_api_key';
  2. const secret = 'your_b64_secret';
  3. const passphrase = 'your_passphrase';
  4. const apiURI = 'https://api.pro.coinbase.com';
  5. const sandboxURI = 'https://api-public.sandbox.pro.coinbase.com';
  6. const authedClient = new CoinbasePro.AuthenticatedClient(
  7. key,
  8. secret,
  9. passphrase,
  10. apiURI
  11. );

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

  1. authedClient.getCoinbaseAccounts(callback);
  1. authedClient.getPaymentMethods(callback);
  1. authedClient.getAccounts(callback);
  1. const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
  2. authedClient.getAccount(accountID, callback);
  1. const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
  2. authedClient.getAccountHistory(accountID, callback);
  3. // For pagination, you can include extra page arguments
  4. authedClient.getAccountHistory(accountID, { before: 3000 }, callback);
  1. const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
  2. authedClient.getAccountTransfers(accountID, callback);
  3. // For pagination, you can include extra page arguments
  4. authedClient.getAccountTransfers(accountID, { before: 3000 }, callback);
  1. const accountID = '7d0f7d8e-dd34-4d9c-a846-06f431c381ba';
  2. authedClient.getAccountHolds(accountID, callback);
  3. // For pagination, you can include extra page arguments
  4. authedClient.getAccountHolds(accountID, { before: 3000 }, callback);
  1. // Buy 1 BTC @ 100 USD
  2. const buyParams = {
  3. price: '100.00', // USD
  4. size: '1', // BTC
  5. product_id: 'BTC-USD',
  6. };
  7. authedClient.buy(buyParams, callback);
  8. // Sell 1 BTC @ 110 USD
  9. const sellParams = {
  10. price: '110.00', // USD
  11. size: '1', // BTC
  12. product_id: 'BTC-USD',
  13. };
  14. authedClient.sell(sellParams, callback);
  1. // Buy 1 LTC @ 75 USD
  2. const params = {
  3. side: 'buy',
  4. price: '75.00', // USD
  5. size: '1', // LTC
  6. product_id: 'LTC-USD',
  7. };
  8. authedClient.placeOrder(params, callback);
  1. const orderID = 'd50ec984-77a8-460a-b958-66f114b0de9b';
  2. authedClient.cancelOrder(orderID, callback);
  1. // Cancels "open" orders
  2. authedClient.cancelOrders(callback);
  1. // `cancelOrders` may require you to make the request multiple times until
  2. // all of the "open" orders are deleted.
  3. // `cancelAllOrders` will handle making these requests for you asynchronously.
  4. // Also, you can add a `product_id` param to only delete orders of that product.
  5. // The data will be an array of the order IDs of all orders which were cancelled
  6. authedClient.cancelAllOrders({ product_id: 'BTC-USD' }, callback);
  1. authedClient.getOrders(callback);
  2. // For pagination, you can include extra page arguments
  3. // Get all orders of 'open' status
  4. authedClient.getOrders({ after: 3000, status: 'open' }, callback);
  1. const orderID = 'd50ec984-77a8-460a-b958-66f114b0de9b';
  2. authedClient.getOrder(orderID, callback);
  1. const params = {
  2. product_id: 'LTC-USD',
  3. };
  4. authedClient.getFills(params, callback);
  5. // For pagination, you can include extra page arguments
  6. authedClient.getFills({ before: 3000 }, callback);
  1. authedClient.getFundings({}, callback);
  1. const params = {
  2. amount: '2000.00',
  3. currency: 'USD',
  4. };
  5. authedClient.repay(params, callback);
  1. const params =
  2. 'margin_profile_id': '45fa9e3b-00ba-4631-b907-8a98cbdf21be',
  3. 'type': 'deposit',
  4. 'currency': 'USD',
  5. 'amount': 2
  6. };
  7. authedClient.marginTransfer(params, callback);
  1. const params = {
  2. repay_only: false,
  3. };
  4. authedClient.closePosition(params, callback);
  1. const params = {
  2. from: 'USD',
  3. to: 'USDC',
  4. amount: '100',
  5. };
  6. authedClient.convert(params, callback);
  1. // Deposit to your Exchange USD account from your Coinbase USD account.
  2. const depositParamsUSD = {
  3. amount: '100.00',
  4. currency: 'USD',
  5. coinbase_account_id: '60680c98bfe96c2601f27e9c', // USD Coinbase Account ID
  6. };
  7. authedClient.deposit(depositParamsUSD, callback);
  8. // Withdraw from your Exchange USD account to your Coinbase USD account.
  9. const withdrawParamsUSD = {
  10. amount: '100.00',
  11. currency: 'USD',
  12. coinbase_account_id: '60680c98bfe96c2601f27e9c', // USD Coinbase Account ID
  13. };
  14. authedClient.withdraw(withdrawParamsUSD, callback);
  15. // Deposit to your Exchange BTC account from your Coinbase BTC account.
  16. const depositParamsBTC = {
  17. amount: '2.0',
  18. currency: 'BTC',
  19. coinbase_account_id: '536a541fa9393bb3c7000023', // BTC Coinbase Account ID
  20. };
  21. authedClient.deposit(depositParamsBTC, callback);
  22. // Withdraw from your Exchange BTC account to your Coinbase BTC account.
  23. const withdrawParamsBTC = {
  24. amount: '2.0',
  25. currency: 'BTC',
  26. coinbase_account_id: '536a541fa9393bb3c7000023', // BTC Coinbase Account ID
  27. };
  28. authedClient.withdraw(withdrawParamsBTC, callback);
  29. // Fetch a deposit address from your Exchange BTC account.
  30. const depositAddressParams = {
  31. currency: 'BTC',
  32. };
  33. authedClient.depositCrypto(depositAddressParams, callback);
  34. // Withdraw from your Exchange BTC account to another BTC address.
  35. const withdrawAddressParams = {
  36. amount: 10.0,
  37. currency: 'BTC',
  38. crypto_address: '15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy',
  39. };
  40. authedClient.withdrawCrypto(withdrawAddressParams, callback);
  1. // Schedule Deposit to your Exchange USD account from a configured payment method.
  2. const depositPaymentParamsUSD = {
  3. amount: '100.00',
  4. currency: 'USD',
  5. payment_method_id: 'bc6d7162-d984-5ffa-963c-a493b1c1370b', // ach_bank_account
  6. };
  7. authedClient.depositPayment(depositPaymentParamsUSD, callback);
  1. // Withdraw from your Exchange USD account to a configured payment method.
  2. const withdrawPaymentParamsUSD = {
  3. amount: '100.00',
  4. currency: 'USD',
  5. payment_method_id: 'bc6d7162-d984-5ffa-963c-a493b1c1370b', // ach_bank_account
  6. };
  7. authedClient.withdrawPayment(withdrawPaymentParamsUSD, callback);
  1. // Get your 30 day trailing volumes
  2. authedClient.getTrailingVolume(callback);

Websocket Client

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

  1. const websocket = new CoinbasePro.WebsocketClient(['BTC-USD', 'ETH-USD']);
  2. websocket.on('message', data => {
  3. /* work with data */
  4. });
  5. websocket.on('error', err => {
  6. /* handle error */
  7. });
  8. websocket.on('close', () => {
  9. /* ... */
  10. });

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

  1. const websocket = new CoinbasePro.WebsocketClient(
  2. ['BTC-USD', 'ETH-USD'],
  3. 'wss://ws-feed-public.sandbox.pro.coinbase.com',
  4. {
  5. key: 'suchkey',
  6. secret: 'suchsecret',
  7. passphrase: 'muchpassphrase',
  8. },
  9. { channels: ['full', 'level2'] }
  10. );

Optionally, change subscriptions at runtime:

  1. websocket.unsubscribe({ channels: ['full'] });
  2. websocket.subscribe({ product_ids: ['LTC-USD'], channels: ['ticker', 'user'] });
  3. websocket.subscribe({
  4. channels: [
  5. {
  6. name: 'user',
  7. product_ids: ['ETH-USD'],
  8. },
  9. ],
  10. });
  11. websocket.unsubscribe({
  12. channels: [
  13. {
  14. name: 'user',
  15. product_ids: ['LTC-USD'],
  16. },
  17. {
  18. name: 'user',
  19. product_ids: ['ETH-USD'],
  20. },
  21. ],
  22. });

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.

  1. 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.

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

Testing

  1. npm test
  2. # test for known vulnerabilities in packages
  3. npm install -g nsp
  4. nsp check --output summary