Skip to content

Commit

Permalink
chore(): expand example and some cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagosiebler committed Sep 26, 2024
1 parent 08d5a68 commit 4e41ae8
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 120 deletions.
121 changes: 55 additions & 66 deletions examples/CBExchange/WebSockets/publicWs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { WebsocketClient, WsTopicRequest } from '../../../src/index.js';

async function start() {
Expand Down Expand Up @@ -46,32 +47,27 @@ async function start() {
/**
* 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:
* - 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('heartbeats', 'exchangeMarketData');
// client.subscribe('futures_balance_summary', 'exchangeMarketData');
// client.subscribe('status', 'exchangeMarketData');

/**
* Or send a more structured object with parameters, e.g. if parameters are required
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tickerSubscribeRequst: 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(tickerSubscribeRequst, 'exchangeMarketData');
// 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
Expand Down Expand Up @@ -102,52 +98,45 @@ async function start() {
// // client.subscribe([level2SubscribeRequest, anotherRequest, etc], 'advTradeMarketData');

/**
* Other adv trade public websocket topics:
* Other Coinbase Exchange public websocket topics:
*/
// client.subscribe(
// [
// {
// topic: 'heartbeats',
// },
// {
// topic: 'candles',
// payload: {
// product_ids: ['ETH-USD'],
// },
// },
// {
// topic: 'market_trades',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// {
// topic: 'status',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// {
// topic: 'ticker',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// {
// topic: 'ticker_batch',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// {
// topic: 'level2',
// payload: {
// product_ids: ['ETH-USD', 'BTC-USD'],
// },
// },
// ],
// 'exchangeMarketData',
// );
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);
}
Expand Down
54 changes: 3 additions & 51 deletions src/WebsocketClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,55 +63,6 @@ export const PUBLIC_WS_KEYS: WsKey[] = [
type WsTopic = string;

export class WebsocketClient extends BaseWebsocketClient<WsKey> {
// private RESTClientCache: Record<WsMarket, CBAdvancedTradeClient | undefined> =
// {
// advancedTrade: undefined,
// exchange: undefined,
// international: undefined,
// prime: undefined,
// };

// private getRESTClient(wsKey: WsKey): undefined {
// switch (wsKey) {
// case WS_KEY_MAP.advTradeMarketData:
// case WS_KEY_MAP.advTradeUserData:
// case WS_KEY_MAP.exchangeMarketData:
// case WS_KEY_MAP.exchangeDirectMarketData:
// case WS_KEY_MAP.internationalMarketData:
// case WS_KEY_MAP.primeMarketData: {
// break;
// }
// default: {
// throw neverGuard(wsKey, `Unhandled WsKey: "${wsKey}"`);
// }
// }
// // if (wsKey === 'spotPublicV1' || wsKey === 'spotPrivateV1') {
// // const clientType = 'advancedTrade';
// // if (this.RESTClientCache[clientType]) {
// // return this.RESTClientCache[clientType];
// // }

// // this.RESTClientCache[clientType] = new CBAdvancedTradeClient({
// // apiKey: this.options.apiKey,
// // apiSecret: this.options.apiSecret,
// // });
// // return this.RESTClientCache[clientType];
// // }

// // const clientType = 'advancedTrade';
// // if (this.RESTClientCache[clientType]) {
// // return this.RESTClientCache[clientType];
// // }

// // this.RESTClientCache[clientType] = new CBAdvancedTradeClient({
// // apiKey: this.options.apiKey,
// // apiSecret: this.options.apiSecret,
// // });
// // return this.RESTClientCache[clientType];

// // throw neverGuard(wsKey, `Unhandled WsKey: "${wsKey}"`);
// }

/**
* Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
*/
Expand Down Expand Up @@ -295,13 +246,13 @@ export class WebsocketClient extends BaseWebsocketClient<WsKey> {
const parsed = JSON.parse(event.data);

const responseEvents = ['subscriptions'];
// const connectionReadyEvents = [''];

// E.g. {"type":"error","message":"rate limit exceeded","wsKey":"advTradeMarketData"}
if (isCBAdvancedTradeErrorEvent(parsed)) {
return [{ eventType: 'exception', event: parsed }];
}

// Parse advanced trade events
// Parse Advanced Trade WS events (update & response)
if (isCBAdvancedTradeWSEvent(parsed)) {
const eventType = parsed.channel;

Expand All @@ -326,6 +277,7 @@ export class WebsocketClient extends BaseWebsocketClient<WsKey> {
}
}

// Parse CB Exchange WS events
if (isCBExchangeWSEvent(parsed, wsKey)) {
const eventType = parsed.type;

Expand Down
7 changes: 4 additions & 3 deletions src/lib/websocket/typeGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ export function isCBAdvancedTradeWSEvent(
}

/**
* Type guard that checks whether this event is/extends CBExchangeBaseEvent,
* used for incoming events from ther server
* Type guard that checks whether this event is/extends CBExchangeBaseEvent
*/
export function isCBExchangeWSEvent(
event: unknown,
Expand All @@ -40,7 +39,9 @@ export function isCBExchangeWSEvent(
);
}

// {"type":"error","message":"rate limit exceeded","wsKey":"advTradeMarketData"}
/**
* Type guard for error-type response events seen for the Advnaced Trade WS channel
*/
export function isCBAdvancedTradeErrorEvent(
event: unknown,
): event is CBAdvancedTradeErrorEvent {
Expand Down

0 comments on commit 4e41ae8

Please sign in to comment.