> For the complete documentation index, see [llms.txt](https://www.notbank.com/learn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.notbank.com/learn/api-reference/websocket-api.md).

# Websocket API

### Websocket Message Frame

When communicating with Notbank via Websocket, all API method calls must be wrapped in a JSON-formatted frame object. Responses from the server are similarly wrapped.&#x20;

```json
{
  "m": 0,
  "i": 0,
  "n": "function name",
  "o": "{\"a-field\": 123, \"another-field\":\"a-value\"}"
}
```

| Key                 | Value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| *m* message type    | <p><strong>integer</strong>. The type of the message. One of:<br>0 request<br>1 reply<br>2 subscribe-to event<br>3 event<br>4 unsubscribe-from event<br>5 error</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| *i* sequence number | <p><strong>long integer</strong>. The sequence number identifies an individual request or request-and-response pair, to your application.<br><br>The system requires a non-zero sequence number, but the numbering scheme you use is up to you. No arbitrary sequence numbering scheme is enforced by Notbank.<br><br><strong>Best Practices:</strong> A client-generated API call (of message types 0, 2, and 4) should:<br>Carry an even sequence number<br>Begin at the start of each user session<br>Be unique within each user session.<br>Begin with 2 (as in 2, 4, 6, 8)<br><br>Message types 1 (reply), 3 (event), and 5 (error) are generated by the server. These messages echo the sequence number of the message to which they respond. See the example, following.</p> |
| *n* function name   | **string**. The function name is the name of the function being called or that the server is responding to. The server echoes your call. See the example, following.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| *o* payload         | Payload is a JSON-formatted string containing the data being sent with the message. Payload may consist of request parameters (key-value pairs) or response parameters. Note that the keys must be in `PascalCase` format.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |

**Note:** You can send the key-value pairs inside the payload in any order. The server controls the order of its response.

#### Example 1

> Example 1

```javascript
var frame = {
  m: 0,
  i: 0,
  n: "function name",
  o: "{}",
};

var requestPayload = {
  parameter1: "value",
  parameter2: 0,
};

frame.o = JSON.stringify(requestPayload);
// Stringify escapes the payload's quotation marks automatically.
WS.Send(JSON.stringify(frame)); // WS.Send escapes the frame
```

When sending a request in the frame to the software using JavaScript, a call looks like Example 1.

#### Example 2

> Example 2

```javascript
var frame = JSON.parse(wsMessage);

if (frame.m == 1) {
  // message of type reply
  //This is a reply
  if (frame.n == "WebAuthenticateUser") {
    var LoginReply = JSON.parse(frame.o);
    if (loginReply.Authenticated) {
      var user = LoginReplay.User;
    }
  }
}
```

When receiving a frame from the software, use the frame to determine the context, and then unwrap the content, as in Example 2.

**Note:** If not using JSON Stringify, escape quotation marks.

### WebSocket connection and authentication using the Node library

When using the [Notbank Node](https://www.npmjs.com/package/notbank) library, in order to connect to Notbank WebSocket, you need to create an instance of NotbankClient, using the `createWebSocketClient()` factory method, and then call the `connect(hooks)` method to establish a connection to use `onOpen`, `onMessage`,`onClose` and `onError` hooks. Once the connection is established, you can authenticate using the `authenticate()` method.

```javascript
import Notbank from 'notbank'

const client = Notbank.NotbankClient.Factory.createWebsocketClient();
const hooks = {
  onOpen: async () => {
    await client.authenticate({
      ApiPublicKey: 'api_key',
      ApiSecretKey: 'api_secret',
      UserId: 'user_id',
    });
  },
  onMessage: (message) => {
    console.log('Received message:', message);
  },
  onClose: () => {
    console.log('Disconnected from Notbank WebSocket');
  },
  onError: (error) => {
    console.error('Error connecting to Notbank WebSocket:', error);
  }
}
await client.connect(hooks);
```

```java
import exchange.notbank.NotbankClient;

var futureNotbankClient = NotbankClient.Factory.createRestartingWebsocketClient(System.out::printLn);
var notbankClient = futureNotbankClient.get();

```

```python
connection = create_new_websocket_client_connection(
  lambda: print("on open"),
  lambda o1, o2: print("on close"),
  lambda err: print("error: " + str(err)),
  lambda msg: print("message in: " + msg),
  lambda msg: print("message out: "+msg),
  )
notbank_client = NotbankClient(connection)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://www.notbank.com/learn/api-reference/websocket-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
