• This repository has been archived on 20/Jan/2020
  • Stars
    star
    828
  • Rank 52,325 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED โ€” The official Node.js library for Coinbase Pro

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

More Repositories

1

terraform-landscape

Improve Terraform's plan output to be easier to read and understand
Ruby
1,546
star
2

coinbase-wallet-sdk

An open protocol that lets users connect their mobile wallets to your DApp
TypeScript
1,276
star
3

coinbase-pro-trading-toolkit

DEPRECATED โ€” The Coinbase Pro trading toolkit
TypeScript
856
star
4

kryptology

Go
838
star
5

build-onchain-apps

Accelerate your web3 creativity with the Build Onchain Apps Toolkit. โ›ต๏ธ
TypeScript
570
star
6

odin

Archived: Odin deployer to AWS for 12 Factor applications.
Go
540
star
7

coinbase-python

DEPRECATED โ€” Coinbase Python API
Python
511
star
8

assume-role

DEPRECATED โ€” assume-role: a CLI tool making it easy to assume IAM roles through an AWS Bastion account
Shell
424
star
9

geoengineer

DEPRECATED โ€” Infrastructure As Code
Ruby
403
star
10

coinbase-node

DEPRECATED โ€” The official Node.js library for the Coinbase API.
JavaScript
361
star
11

mesh-specifications

Specification files for the Rosetta Blockchain Standard
Shell
313
star
12

coinbase-php

DEPRECATED โ€” PHP wrapper for the Coinbase API
PHP
293
star
13

onchainkit

React components and TypeScript utilities for top-tier onchain apps.
TypeScript
287
star
14

cbpay-js

Coinbase Pay SDK
TypeScript
270
star
15

coinbase-ruby

DEPRECATED โ€” Ruby wrapper for the Coinbase API
Ruby
239
star
16

waas-sdk-react-native

Coinbase Wallet as a Service (WaaS) SDK for React Native. Enables MPC Operations for iOS and Android Devices.
TypeScript
222
star
17

step

step is a framework for building, testing and deploying AWS Step Functions and Lambda
Go
207
star
18

wallet-mobile-sdk

An open protocol for mobile web3 apps to interact with wallets
Kotlin
203
star
19

temporal-ruby

Ruby SDK for Temporal
Ruby
194
star
20

mesh-sdk-go

Rosetta Client Go SDK
Go
182
star
21

coinbase-ios-sdk

Integrate bitcoin into your iOS application with Coinbase
Swift
172
star
22

nft-dapp-starter-kit

Starter kit for developers who want to build an NFT minting site
TypeScript
153
star
23

coinbase-java

Coinbase API v1 library for Java
Java
146
star
24

coinbase-commerce-node

Coinbase Commerce Node
JavaScript
143
star
25

mesh-cli

CLI for the Rosetta API
Go
142
star
26

waas-client-library-go

Coinbase Wallet as a Service (WaaS) Client Library in Go.
Go
138
star
27

traffic_jam

DEPRECATED โ€” Ruby library for time-based rate limiting
Ruby
129
star
28

coinbase-commerce-php

Coinbase Commerce PHP
PHP
127
star
29

coinbase-exchange-ruby

DEPRECATED โ€” Official Ruby library for the GDAX API
Ruby
122
star
30

dexter

Forensics acquisition framework designed to be extensible and secure
Go
118
star
31

multisig-tool

DEPRECATED โ€” Multisig Vault recovery tool
JavaScript
110
star
32

mesh-bitcoin

Bitcoin Rosetta API Implementation
Go
104
star
33

smart-wallet

Solidity
103
star
34

mesh-ethereum

Ethereum Rosetta API Implementation
Go
98
star
35

coinbase-android-sdk

DEPRECATED โ€” Android SDK for Coinbase
Java
95
star
36

mongobetween

Go
93
star
37

fenrir

Archived: AWS SAM deployer to manage serverless projects.
Go
91
star
38

react-coinbase-commerce

Coinbase Commerce React
JavaScript
91
star
39

pwnbot

You call PwnBot in Slack on someone else's unlocked computer
JavaScript
89
star
40

digital-asset-policy-proposal

Digital Asset Policy Proposal: Safeguarding Americaโ€™s Financial Leadership
85
star
41

coinbase-commerce-python

Coinbase Commerce Python
Python
77
star
42

CBTabViewExample

TypeScript
69
star
43

coinbase-bitmonet-sdk

DEPRECATED โ€” Library to accept bitcoin payments in your Android App
Java
62
star
44

chainstorage

The File System For a Multi-Blockchain World
Go
61
star
45

self-service-iam

DEPRECATED โ€” Self Service AWS IAM Policies for dev at scale
JavaScript
58
star
46

coinbase-wordpress

DEPRECATED โ€” Coinbase plugin/widget for Wordpress
57
star
47

coinbase-commerce-woocommerce

Accept Bitcoin on your WooCommerce-powered website.
PHP
55
star
48

barbar

DEPRECATED โ€” OSX crypto-currency price ticker
Swift
53
star
49

demeter

DEPRECATED โ€” Security Group Management For AWS
Ruby
52
star
50

verifications

๐Ÿ“œ "Coinbase Verifications" is a set of Coinbase-verified onchain attestations that enable access to apps and other onchain benefits.
Solidity
50
star
51

coinbase-exchange-node

DEPRECATED โ€” Use gdax-node
JavaScript
46
star
52

cadence-ruby

Ruby SDK for Cadence
Ruby
44
star
53

commerce-onchain-payment-protocol

Solidity
41
star
54

protoc-gen-rbi

Protobuf compiler plugin that generates Sorbet .rbi "Ruby Interface" files.
Go
38
star
55

coinbase-woocommerce

DEPRECATED โ€” Accept Bitcoin on your WooCommerce-powered website.
38
star
56

coinbase-advanced-py

The Advanced API Python SDK is a Python package that makes it easy to interact with the Coinbase Advanced API. The SDK handles authentication, HTTP connections, and provides helpful methods for interacting with the API.
Python
37
star
57

mesh-ecosystem

Repository of all open source Rosetta implementations and SDKs
33
star
58

master_lock

Inter-process locking library using Redis.
Ruby
31
star
59

coinbase-commerce-ruby

Coinbase Commerce Ruby Gem
Ruby
30
star
60

watchdog

DEPRECATED -- Github Bot for Datadog codification
Go
28
star
61

bittip

DEPRECATED โ€” Reddit tip bot
JavaScript
27
star
62

maxfuzz

DEPRECATED โ€” Containerized Cloud Fuzzing
C
26
star
63

cash-addr

Utility to convert between base58 and CashAddr BCH addresses.
Ruby
25
star
64

rules_ruby

Bazel Ruby Rules
Starlark
24
star
65

mesh-geth-sdk

go-ethereum based sdk for Rosetta API
Go
23
star
66

gtt-ui

DEPRECATED
JavaScript
22
star
67

btcexport

Export process for Bitcoin blockchain data to CSV
Go
22
star
68

bchd-explorer

Vue
21
star
69

redisbetween

Go
20
star
70

baseca

Go
18
star
71

coinbase-magento

DEPRECATED โ€” Accept Bitcoin on your Magento-powered website.
17
star
72

coinbase-commerce-whmcs

Coinbase Commerce module for WHMCS
PHP
16
star
73

coinbase-android-sdk-example

DEPRECATED โ€” Example android app leveraging the coinbase android sdk
Java
15
star
74

coinbase-nft-floor-price

Coinbase NFT floor price estimate model
Python
15
star
75

coinbase-spree

DEPRECATED โ€” Accept bitcoin payments on your Spree store with Coinbase.
15
star
76

service_variables

Service level variables backed by Redis - useful for service wide configuration.
Ruby
12
star
77

solidity-workshop

JavaScript
12
star
78

omniauth-coinbase

DEPRECATED โ€” Coinbase OAuth 2 Strategy for Omniauth
Ruby
12
star
79

coinbase-javascript-sdk

DEPRECATED
JavaScript
11
star
80

coinbase-commerce-prestashop

DEPRECATED โ€” Official Coinbase Commerce Prestashop Payment Module
PHP
11
star
81

wrapped-tokens-os

TypeScript
11
star
82

coinbase-cloud-sdk-js

TypeScript
11
star
83

step-asg-deployer

Deprecated, renamed and maintained at https://github.com/coinbase/odin
Go
10
star
84

eip-token-upgrade

Solidity
10
star
85

mkr-vote-proxy

Cold storage-friendly voting for MKR tokens
Solidity
10
star
86

salus

We would like to request that all contributors please clone a *fresh copy* of this repository since the September 21st maintenance.
HTML
9
star
87

chainsformer

Go
9
star
88

coinbase-magento2

DEPRECATED: Accept Bitcoin on your Magento2-powered website.
8
star
89

code-of-conduct

Code of conduct for open source projects managed by Coinbase
8
star
90

coinbase-commerce-opencart

DEPRECATED โ€” Coinbase Commerce Integration For Opencart
PHP
8
star
91

magic-spend

Solidity
8
star
92

chainnode

Go
7
star
93

waas-proxy-server

Go
7
star
94

client-analytics

TypeScript
7
star
95

node-process-lock

DEPRECATED โ€” Simple process locking using Redis.
JavaScript
7
star
96

coinbase-commerce-magento

DEPRECATED โ€” Coinbase Commerce Payment Gateway For Magento 2
PHP
7
star
97

coinbase-commerce-gravity-forms

DEPRECATED โ€” Official Coinbase Commerce Payment Gateway For Gravity Forms
PHP
7
star
98

paymaster-bundler-examples

7
star
99

coinbase-zencart

DEPRECATED โ€” Accept Bitcoin on your Zen Cart-powered website.
6
star
100

demeter-example

DEPRECATED โ€” Demeter
6
star