Skip to main content

Establishing a Connection

In order to contact the API server, we need to open a socket connection to an endpoint.

note

We are using the endpoint deisgnated for live accounts and JSON messaging.

const ws = new WebSocket('wss://live.ctraderapi.com:5036');

ws.onopen = function () {
console.log('connected to server');
};

ws.onclose = function () {
console.log('connection closed');
};

Why Connection Closes Automatically

If you ran previous code examples, you'll notice that the script runs sucessfully and prints the following:

connected to server
connection closed

So it seems that the connection is opened at first, but then after some time passes, it gets closed automatically.

Let's adjust the code to measure the time between the events happening. We want to measure the time taken between following events:

  • from when script is first run, until connection is opened
  • from when connection is opened, until it's closed
const ws = new WebSocket('wss://live.ctraderapi.com:5036');
const round = (n, dp) => +n.toFixed(dp);

let t = Date.now();

ws.onopen = function () {
console.log('connected to server');
console.log(
'it took',
round((Date.now() - t) / 1000, 1),
'secs to open the connection',
);
t = Date.now();
};

ws.onclose = function () {
console.log('connection closed');
const secsPassed = round((Date.now() - t) / 1000, 1);
console.log(
'connection stayed open for',
secsPassed,
'seconds before it was closed',
);
};

Results from running the code:

connected to server
it took 0.8 seconds to open the connection
connection closed
connection stayed open for 29.8 seconds before it was closed

As the results show, the connection gets closed after being open for 30 seconds. It is actually the server that closes the connection.

When the server notices that a client that was previously connected, hasn't been sending any messages for awhile, it decides to close the connection to that client. The time a client spends being connected to the server, but not sending any messages to it, is also called the idle time. One of the reasons for this server's behaviour is to save its resources.

Later, when we learn about Exchanging Messages with the server, we will see how the server counts the idle time of a connected client from the last message that the client sent to it.

We will also learn a special way of preventing this from happening in Keeping Connection Open.