@0xcmp/gdax 中文文档教程
GDAX
Coinbase 的 GDAX API 的官方 Node.js 库。
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 gdax
您可以通过阅读我们的了解每个端点的 API 响应 文档。
Quick Start
GDAX API 具有公共端点和私有端点。 如果你只对 公共端点,您应该使用 PublicClient
。
const Gdax = require('gdax');
const publicClient = new Gdax.PublicClient();
除非另有说明,否则所有方法都可以与 promise 或 回调接口。
Using Promises
publicClient
.getProducts()
.then(data => {
// work with data
})
.catch(error => {
// handle the error
});
promise API 可以在 ES2017+ 的 async
函数中按预期使用 环境:
async function yourFunction() {
try {
const products = await publicClient.getProducts();
} catch (error) {
/* ... */
}
}
Using Callbacks
您的回调应该接受两个参数:
error
: contains an error message (string
), ornull
if no was error encounteredresponse
: a generic HTTP response abstraction created by therequest
librarydata
: contains data returned by the GDAX API, orundefined
if an error was encountered
publicClient.getProducts((error, response, data) => {
if (error) {
// handle the error
} else {
// work with data
}
});
注意如果您提供回调,则不会返回任何承诺。 这是为了 防止潜在的 UnhandledPromiseRejectionWarning
,这将导致未来 要终止的 Node 版本。
const myCallback = (err, response, data) => {
/* ... */
};
const result = publicClient.getProducts(myCallback);
result.then(() => {
/* ... */
}); // TypeError: Cannot read property 'then' of undefined
Optional Parameters
一些方法接受可选参数,例如
publicClient.getProductOrderBook('BTC-USD', { level: 3 }).then(book => {
/* ... */
});
要将可选参数与回调一起使用,请提供选项作为第一个 参数和回调作为最后一个参数:
publicClient.getProductOrderBook(
'ETH-USD',
{ level: 3 },
(error, response, book) => {
/* ... */
}
);
The Public API Client
const publicClient = new Gdax.PublicClient(endpoint);
productID
optional - defaults to 'BTC-USD' if not specified.endpoint
optional - defaults to 'https://api.gdax.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);
环绕 getProductTrades
,获取 ID 为 >= tradesFrom
的所有交易,并且 <代码><=交易到。 处理分页和速率限制。
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
私人交易 API 端点需要您 使用 GDAX API 密钥进行身份验证。 您可以创建一个新的 API 密钥在您的 交换账户的设置。 您还可以指定 API URI(默认为 https://api.gdax.com
)。
const key = 'your_api_key';
const secret = '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,
secret,
passphrase,
apiURI
);
与 PublicClient
一样,所有 API 方法都可以与回调一起使用,也可以将 回报承诺。
AuthenticatedClient
继承了所有的 API 方法 PublicClient
,所以如果您同时访问公共和私有 API 端点,您 只需要创建一个客户端。
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.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);
authedClient.cancelOrders(callback);
// `cancelOrders` may require you to make the request multiple times until
// all of the 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);
authedClient.getFills(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);
// 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);
// Withdraw from your Exchange BTC account to another BTC address.
const withdrawAddressParams = {
amount: 10.0,
currency: 'BTC',
crypto_address: '15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy',
};
authedClient.withdrawCrypto(withdrawAddressParams, callback);
// Get your 30 day trailing volumes
authedClient.getTrailingVolume(callback);
Websocket Client
WebsocketClient
允许您连接并收听交换 网络套接字消息。
const websocket = new Gdax.WebsocketClient(['BTC-USD', 'ETH-USD']);
websocket.on('message', data => {
/* work with data */
});
websocket.on('error', err => {
/* handle error */
});
websocket.on('close', () => {
/* ... */
});
客户端会自动订阅heartbeat
频道。 经过 默认情况下,将订阅 full
频道,除非其他频道已订阅 要求。
const websocket = new Gdax.WebsocketClient(
['BTC-USD', 'ETH-USD'],
'https://api-public.sandbox.gdax.com',
{
key: 'suchkey',
secret: 'suchsecret',
passphrase: 'muchpassphrase',
},
{ channels: ['full', 'level2'] }
);
可选地,在运行时更改订阅:
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']
}]
});
可以从 WebsocketClient
发出以下事件:
open
message
close
error
Orderbook
Orderbook
是一种数据结构,可用于存储订单的本地副本 订单簿。
const orderbook = new Gdax.Orderbook();
orderbook有以下方法:
state(book)
get(orderId)
add(order)
remove(orderId)
match(match)
change(change)
Orderbook Sync
OrderbookSync
使用 GDAX 创建 orderbook 的本地镜像 Orderbook
和 WebsocketClient
描述 此处。
const orderbookSync = new Gdax.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
GDAX
The official Node.js library for Coinbase's GDAX 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 gdax
You can learn about the API responses of each endpoint by reading our documentation.
Quick Start
The GDAX API has both public and private endpoints. If you're only interested in the public endpoints, you should use a PublicClient
.
const Gdax = require('gdax');
const publicClient = new Gdax.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 two arguments:
error
: contains an error message (string
), ornull
if no was error encounteredresponse
: a generic HTTP response abstraction created by therequest
librarydata
: contains data returned by the GDAX API, orundefined
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 UnhandledPromiseRejectionWarning
s, 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 Gdax.PublicClient(endpoint);
productID
optional - defaults to 'BTC-USD' if not specified.endpoint
optional - defaults to 'https://api.gdax.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 GDAX 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.gdax.com
).
const key = 'your_api_key';
const secret = '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,
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.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);
authedClient.cancelOrders(callback);
// `cancelOrders` may require you to make the request multiple times until
// all of the 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);
authedClient.getFills(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);
// 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);
// Withdraw from your Exchange BTC account to another BTC address.
const withdrawAddressParams = {
amount: 10.0,
currency: 'BTC',
crypto_address: '15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy',
};
authedClient.withdrawCrypto(withdrawAddressParams, 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 Gdax.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 Gdax.WebsocketClient(
['BTC-USD', 'ETH-USD'],
'https://api-public.sandbox.gdax.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 Gdax.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 GDAX using Orderbook
and WebsocketClient
as described here.
const orderbookSync = new Gdax.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