Authentication
First put the credentials we acquired in a file named
credentials.json
for example.
{
"accountId": 12345678,
"clientId": "",
"clientSecret": "",
"accessToken": "",
"refreshToken": ""
}
Application and Account Authentication
const {
clientId,
clientSecret,
accountId: ctidTraderAccountId,
accessToken,
} = require('./credentials.json');
const ws = new WebSocket('wss://live.ctraderapi.com:5036');
// util functions
const { log } = console;
const sleep = (secs) => new Promise((r) => setTimeout(r, secs * 1000));
const CHECK_INTERVAL_SECS = 1;
let fullyAuthenticated = false;
ws.onopen = function () {
log('connected to server');
ws.send(
JSON.stringify({
payloadType: 2100,
payload: { clientId, clientSecret },
}),
);
log('requested application authentication');
};
ws.onmessage = function (e) {
const serverMsg = JSON.parse(e.data);
if (serverMsg.payloadType === 2142) {
log('server responded with error:', serverMsg.payLoad);
return;
}
if (serverMsg.payloadType === 2101) {
log('application authentication completed');
ws.send(
JSON.stringify({
payloadType: 2102,
payload: { ctidTraderAccountId, accessToken },
}),
);
log('requested account authenthication');
}
if (serverMsg.payloadType === 2103) {
log('account authentication completed');
fullyAuthenticated = true;
}
};
ws.onclose = function ({ code, reason, wasClean }) {
log('connection closed', { code, reason, wasClean });
};
(async () => {
while (true) {
await sleep(0);
if (ws.readyState !== WebSocket.OPEN) continue;
if (!fullyAuthenticated) continue;
log('fully authenticated and ready for more communication with the server');
await sleep(CHECK_INTERVAL_SECS);
}
})();
Results from running the code:
connected to server
requested application authentication
application authentication completed
requested account authenthication
account authentication completed
fully authenticated and ready for more communication with the server
fully authenticated and ready for more communication with the server
fully authenticated and ready for more communication with the server
fully authenticated and ready for more communication with the server
...