Skip to content

Commit

Permalink
Merge pull request #42 from tiagosiebler/wsContinued
Browse files Browse the repository at this point in the history
CB Exchange websocket support
  • Loading branch information
tiagosiebler authored Sep 26, 2024
2 parents 4b493e3 + 4e41ae8 commit 3a78b8a
Show file tree
Hide file tree
Showing 8 changed files with 574 additions and 151 deletions.
145 changes: 145 additions & 0 deletions examples/CBExchange/WebSockets/publicWs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { WebsocketClient, WsTopicRequest } from '../../../src/index.js';

async function start() {
/**
* All websockets are available via the unified WebsocketClient.
*
* Below are examples specific to websockets in this product group.
*/
const client = new WebsocketClient();

client.on('open', (data) => {
console.log('open: ', data?.wsKey);
});

// Data received
client.on('update', (data) => {
console.info(new Date(), 'data received: ', JSON.stringify(data));
});

// Something happened, attempting to reconenct
client.on('reconnect', (data) => {
console.log('reconnect: ', data);
});

// Reconnect successful
client.on('reconnected', (data) => {
console.log('reconnected: ', data);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
console.error('close: ', data);
});

// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
client.on('response', (data) => {
console.info('response: ', JSON.stringify(data, null, 2));
// throw new Error('res?');
});

client.on('exception', (data) => {
console.error('exception: ', data);
});

try {
/**
* Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
*
* - You can subscribe to topics one at a time or many one one request.
* - Topics can be sent as simple strings, if no parameters are required.
* - Coinbase Market Data is the traditional feed which is available without authentication.
* - To use this feed, use 'exchangeMarketData' as the wsKey for each subscription command:
*/
// client.subscribe('status', 'exchangeMarketData');

/**
* Or send a more structured object with parameters, e.g. if parameters are required
*/
// const tickerSubscribeRequest: WsTopicRequest = {
// topic: 'ticker',
// /**
// * Anything in the payload will be merged into the subscribe "request",
// * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
// */
// payload: {
// product_ids: ['ETH-USD', 'ETH-EUR'],
// },
// };
// client.subscribe(tickerSubscribeRequest, 'exchangeMarketData');

/**
* Subscribe to the "heartbeat" topic for a few symbols
*/
// client.subscribe(
// {
// topic: 'heartbeat',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// 'exchangeMarketData',
// );

// client.subscribe(
// {
// topic: 'level2',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// 'exchangeMarketData',
// );

// /**
// * Or, send an array of structured objects with parameters, if you wanted to send multiple in one request
// */
// // client.subscribe([level2SubscribeRequest, anotherRequest, etc], 'advTradeMarketData');

/**
* Other Coinbase Exchange public websocket topics:
*/
client.subscribe(
[
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#heartbeat-channel
{
topic: 'heartbeat',
payload: {
product_ids: ['ETH-EUR'],
},
},
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#status-channel
'status',
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#auction-channel
{
topic: 'auctionfeed',
payload: {
product_ids: ['LTC-USD'],
},
},
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#matches-channel
{
topic: 'matches',
payload: {
product_ids: ['BTC-USD'],
},
},
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#rfq-matches-channel
{
topic: 'rfq_matches',
payload: {
// Optional:
// product_ids: ['ETH-USD', 'BTC-USD'],
},
},
// TODO: @jerko add other PUBLIC channels here as example
],
'exchangeMarketData',
);
} catch (e) {
console.error(`Subscribe exception: `, e);
}
}

start();
36 changes: 36 additions & 0 deletions examples/CBExchange/cb-exchange-private.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { CBExchangeClient } from '../../src/index.js';
// import { CBExchangeClient } from 'coinbase-api';

// Initialize the client, you can pass in api keys here if you have them but they are not required for public endpoints
const client = new CBExchangeClient({
apiKey: 'yourAPIKeyHere',
apiSecret: 'yourAPISecretHere',
//This is the passphrase you provided when creating this API key. NOT your account password.
apiPassphrase: 'yourAPIPassPhraseHere',

// Optional, connect to sandbox instead: https://public-sandbox.exchange.coinbase.com/apikeys
// useSandbox: true,
});

async function privateExchangeCalls() {
try {
const orders = await client.getOrders();
console.log('Orders: ', orders);

const order = await client.getOrder({
order_id: '0c892cb3-2824-4662-8be3-99c8e879f606',
market_type: 'market',
});
console.log('Order: ', order);

const cancelOrderResult = await client.cancelOrder({
order_id: '0c892cb3-2824-4662-8be3-99c8e879f606',
product_id: 'BTC-GBP',
});
console.log('cancelOrder result: ', cancelOrderResult);
} catch (e) {
console.error('Error: ', e);
}
}

privateExchangeCalls();
Loading

0 comments on commit 3a78b8a

Please sign in to comment.