WebSocket API client

You must provide constructor options that match either:

  • If you only need public subscriptions, all options are optional.
  • If you want to make authenticated subscriptions:
    • You must provide a valid WebSocketClientOptions.auth auth property in the constructor options which includes:
      • katanaperps.WebSocketClientAuthOptions.apiKey apiKey
      • katanaperps.WebSocketClientAuthOptions.apiSecret apiSecret
      • katanaperps.WebSocketClientAuthOptions.wallet wallet

Example

  import {
WebSocketClient,
SubscriptionNameAuthenticated,
SubscriptionNamePublic
} from '@katanaperps/katana-perps-sdk';

const webSocketClientPublicOnly = new WebSocketClient();

// or ... to enable both public and authenticated subscriptions:

const client = new WebSocketClient({
// Edit the values before for your environment
auth: {
apiKey: '1f7c4f52-4af7-4e1b-aa94-94fac8d931aa',
apiSecret: 'axuh3ywgg854aq7m73oy6gnnpj5ar9a67szuw5lclbz77zqu0j',
wallet: '0x...',
}
// sandbox: true,
// logger: console.log
});

client.onConnect(() => {
// [see onConnect docs for full example and information]
})

client.onDisconnect((code, reason) => {
// [see onDisconnect docs for full example and information]
})

client.onError(errorEvent => {
// [see onError docs for full example and information]
})

client.onMessage(message => {
console.log('Receiving Message: ', message)
switch(message.type) {
case MessageEventType.subscriptions:
return handleSubscriptions(message.subscriptions);
case MessageEventType.error:
return handleAPIError(message.data);
case MessageEventType.candles:
return handleCandles(message.data);
default:
break;
})

await client.connect();

// subscribe as needed!

await client
.subscribePublic([
{
name: SubscriptionNamePublic.tickers,
markets: ['ETH-USD']
},
])
.subscribeAuthenticated([
{ name: SubscriptionNameAuthenticated.positions },
{ name: SubscriptionNameAuthenticated.orders },
]);


See

typedoc Reference Documentation

Accessors

Connection Management

  • Disconnect from the WebSocket if connected.

    • If terminate is true, the WebSocket will be disconnected immediately and this client will cease to work or connect.
      • All listeners will be cleared and all methods will throw errors once terminated.

    Parameters

    • Optional terminate: boolean

    Returns this

Event Handling

  • Subscribe a handler to all WebSocket disconnect events.

    • Calling multiple times will add multiple subscribers to the given event

    Parameters

    Returns this

    • this to allow chaining with other methods or requests.

    Example

     websocketClient.onConnect(() => {
    console.warn('WebSocket Connection Connects')
    })


    See

    typedoc Reference Documentation

  • Subscribe a handler to all WebSocket connection errors that may occur during your requests.

    • Note: These errors will be coming from the ws library itself and provide its ErrorEvent errors.
    • Errors coming from the Katana Perps WebSocket client will be present as a katanaperps.KatanaPerpsErrorEvent KatanaPerpsErrorEvent message to the onMessage handler.

    Parameters

    Returns this

    • this to allow chaining with other methods or requests.

    Example

     websocketClient.onError(errorEvent => {
    console.error('Connection Error on WebSocket: ', errorEvent.error)
    })


    See

    typedoc Reference Documentation

  • Subscribe a handler to all subscription responses.

    • Your handler will receive updates when available matching the KatanaPerpsMessageEvent interface.
    • Use the katanaperps.MessageEventType MessageEventType enum to get an enum defining all possible type values that can be received on the WebSocket message (see example).

    Parameters

    Returns this

    • this to allow chaining with other methods or requests.

    Example

     import { MessageEventType } from '@katanaperps/katana-perps-sdk';

    // ... client setup

    websocketClient.onMessage(message => {
    console.log('Receiving Message: ', message)
    switch(message.type) {
    case MessageEventType.subscriptions:
    return handleSubscriptions(message.subscriptions);
    case MessageEventType.error:
    return handleAPIError(message.data);
    case MessageEventType.candles:
    return handleCandles(message.data);
    default:
    break;
    }
    })


    See

Subscription Management

  • Creates new authenticated subscriptions based on the provided parameters.

    • Use the katanaperps.SubscriptionNameAuthenticated SubscriptionNameAuthenticated enum for IDE inline documentation and auto completion (see example)

    Subscription Update Events:

    • Receives a katanaperps.KatanaPerpsSubscriptionsListEvent KatanaPerpsSubscriptionsListEvent WebSocket response via the katanaperps.WebSocketClient.onMessage WebSocketClient.onMessage handler listing all active subscriptions.
    • Begins receiving katanaperps.KatanaPerpsSubscriptionEvent KatanaPerpsSubscriptionEvent's for all subscribed subscriptions via the katanaperps.WebSocketClient.onMessage WebSocketClient.onMessage handler.

    Parameters

    Returns this

    • this to allow chaining with other methods or requests.

    Throws

    This method will throw an error if you did not provide the katanaperps.WebSocketClientOptionsWithAPIKey.auth auth option to the constructor in order to handle authenticated subscriptions.


    Example

     import {
    WebSocketClient,
    SubscriptionNameAuthenticated,
    } from '@katanaperps/katana-perps-sdk';

    const client = new WebSocketClient({
    auth: {
    apiKey: '...',
    apiSecret: '...',
    wallet: '0x...'
    }
    })

    client.onMessage(message => {
    console.log('Received WebSocket Message: ', message)
    })

    await client.subscribeAuthenticated([
    { name: SubscriptionNameAuthenticated.positions },
    { name: SubscriptionNameAuthenticated.orders },
    ])


    See

  • This method allows subscribing to Katana Perps's public subscriptions.

    • Use the katanaperps.SubscriptionNamePublic SubscriptionNamePublic enum for IDE inline documentation and auto completion (see example)

    Subscription Update Events:

    • Receives a katanaperps.KatanaPerpsSubscriptionsListEvent KatanaPerpsSubscriptionsListEvent WebSocket response via the katanaperps.WebSocketClient.onMessage WebSocketClient.onMessage handler listing all active subscriptions.
    • Begins receiving katanaperps.KatanaPerpsSubscriptionEvent KatanaPerpsSubscriptionEvent's for all subscribed subscriptions via the katanaperps.WebSocketClient.onMessage WebSocketClient.onMessage handler.

    Parameters

    • subscriptions: KatanaPerpsSubscribeTypePublic[]

      An array of KatanaPerpsSubscribeTypePublic subscription objects.

    • Optional markets: string[]

      Optionally provide top-level markets.

      • Any subscriptions that require but do not define their own markets array will inherit this set of markets.
      • If a subscription in your subscriptions array defines its own KatanaPerpsSubscribeType.markets markets array, the top-level markets will not be inherited
    • Optional cid: string

      Optionally provide a cid property which will be returned in the response so that you can correlate the response to the request.

    Returns this

    • this to allow chaining with other methods or requests.

    Example

     import {
    WebSocketClient,
    SubscriptionNamePublic,
    CandleInterval
    } from '@katanaperps/katana-perps-sdk';

    const client = new WebSocketClient();

    await client.subscribePublic([
    // will inherit markets from the markets array
    { name: SubscriptionNamePublic.tickers },
    // overrides the top level markets array with its own
    {
    name: SubscriptionNamePublic.candles,
    interval: CandleInterval.ONE_MINUTE,
    // replaces the top-level markets when provided
    markets: ['ETH-USD', 'BTC-USD'],
    },
    ], ['ETH-USD'])


    See

  • List all active subscriptions


    Subscription Update Events:

    • Receives a katanaperps.KatanaPerpsSubscriptionsListEvent KatanaPerpsSubscriptionsListEvent WebSocket response via the katanaperps.WebSocketClient.onMessage WebSocketClient.onMessage handler listing all active subscriptions.

    Parameters

    • Optional cid: string

      Optionally provide a cid property which will be returned in the response so that you can correlate the response to the request.

    Returns this

    • this to allow chaining with other methods or requests.

Other

  • get terminated(): boolean
  • When a client is terminated, it will cease to function and a new WebSocketClient must be created to start a new connection.

    Returns boolean

  • WebSocket API client

    You must provide constructor options that match either:

    • If you only need public subscriptions, all options are optional.
    • If you want to make authenticated subscriptions:
      • You must provide a valid WebSocketClientOptions.auth auth property in the constructor options which includes:
        • katanaperps.WebSocketClientAuthOptions.apiKey apiKey
        • katanaperps.WebSocketClientAuthOptions.apiSecret apiSecret
        • katanaperps.WebSocketClientAuthOptions.wallet wallet

    Parameters

    Returns WebSocketClient

    Example

      import {
    WebSocketClient,
    SubscriptionNameAuthenticated,
    SubscriptionNamePublic
    } from '@katanaperps/katana-perps-sdk';

    const webSocketClientPublicOnly = new WebSocketClient();

    // or ... to enable both public and authenticated subscriptions:

    const client = new WebSocketClient({
    // Edit the values before for your environment
    auth: {
    apiKey: '1f7c4f52-4af7-4e1b-aa94-94fac8d931aa',
    apiSecret: 'axuh3ywgg854aq7m73oy6gnnpj5ar9a67szuw5lclbz77zqu0j',
    wallet: '0x...',
    }
    // sandbox: true,
    // logger: console.log
    });

    client.onConnect(() => {
    // [see onConnect docs for full example and information]
    })

    client.onDisconnect((code, reason) => {
    // [see onDisconnect docs for full example and information]
    })

    client.onError(errorEvent => {
    // [see onError docs for full example and information]
    })

    client.onMessage(message => {
    console.log('Receiving Message: ', message)
    switch(message.type) {
    case MessageEventType.subscriptions:
    return handleSubscriptions(message.subscriptions);
    case MessageEventType.error:
    return handleAPIError(message.data);
    case MessageEventType.candles:
    return handleCandles(message.data);
    default:
    break;
    })

    await client.connect();

    // subscribe as needed!

    await client
    .subscribePublic([
    {
    name: SubscriptionNamePublic.tickers,
    markets: ['ETH-USD']
    },
    ])
    .subscribeAuthenticated([
    { name: SubscriptionNameAuthenticated.positions },
    { name: SubscriptionNameAuthenticated.orders },
    ]);


    See

    typedoc Reference Documentation