connecting to Open API via javascript

Created at 12 Oct 2023, 08:00
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
AN

anthoniahenry4

Joined 09.10.2023

connecting to Open API via javascript
12 Oct 2023, 08:00


trying to connect to ctrader backend via javascript but I always end up getting a payload of 51 after making a connection via the WebSocket and also with no output 

here is my code sample 

 

const websocketUrl = 'wss://demo.ctraderapi.com:5036';

const symbol = {};

const accessToken = 'C-CDZRJpSXL5Y9Ss0chy7c2-poyaXRMi1WkZzPSjJcY'; // Assuming you have the symbol information


 

const socket = new WebSocket(websocketUrl);



 

// Function to send ProtoOAGetTrendbarsReq

function sendTrendbarRequest(period, accountId, symbolId, days) {

    console.log('Sending ProtoOAGetTrendbarsReq...');


 

    const request = {

        messageType: 'ProtoOAGetTrendbarsReq',

        payloadType: /* Specify the payloadType for ProtoOAGetTrendbarsReq */2100,

        payload: {

            clientId: "7311_icgJginJfRSoKOnkEKnv9NFhwIukhbTN2rNV2ki7VyTiITH0fP",

            clientSecret: "j1oFzqNoCEKKWTSKWLBBUrlAM3MJdJfCgJPikfRPMGxTmvdMAC",

        },

        ctidTraderAccountId: "C-CDZRJpSXL5Y9Ss0chy7c2-poyaXRMi1WkZzPSjJcY",

        symbolId: symbolId,

        period: "H1",

        fromTimestamp: new Date(Date.now() - days * 24 * 60 * 60 * 1000).getTime(), // FromTimestamp in milliseconds

        toTimestamp: Date.now(), // ToTimestamp in milliseconds

    };


 

    console.log(`FromTimestamp: ${request.fromTimestamp} | ToTimestamp: ${request.toTimestamp}`);


 

    socket.send(JSON.stringify(request));

}


 

// Function to process received ProtoOAGetTrendbarsRes

function onHistoricalTrendbarsReceived(message) {

    const trendbars = message.trendbars;


 

    const data = [];


 

    trendbars.forEach(trendbar => {

        data.push({

            low: getPriceFromRelative(symbol, trendbar.low),

            high: getPriceFromRelative(symbol, trendbar.low + trendbar.deltaHigh),

            open: getPriceFromRelative(symbol, trendbar.low + trendbar.deltaOpen),

            close: getPriceFromRelative(symbol, trendbar.low + trendbar.deltaClose),

        });

    });


 

    console.log(message);

    // Handle the processed data as needed

    console.log('Historical Trendbars:', data);

}


 

// Function to get price from relative

function getPriceFromRelative(symbol, relative) {

    return Math.round(relative / 100000.0 * Math.pow(10, symbol.digits)) / Math.pow(10, symbol.digits);

}


 

// WebSocket event listeners

socket.onopen = () => {

    // Authentication logic if needed


 

    // Send ProtoOAGetTrendbarsReq

    sendTrendbarRequest(/* specify parameters */);

};


 

socket.onmessage = (event) => {

    const message = JSON.parse(event.data);


 

    // Handle different message types

    switch (message.messageType) {

        case 'ProtoOAGetTrendbarsRes':

            onHistoricalTrendbarsReceived(message);

            break;

        // Add cases for other message types as needed

    }

    if (message.payloadType) {

        switch (message.payloadType) {

            case 2101:

                console.log('Received message with payloadType 2101:', message);

                // Handle the specific message type (replace this with your logic)

                break;

            // Add cases for other payload types as needed

            default:

                console.warn('Unhandled payloadType:', message.payloadType);

        }

    } else {

        console.error('Invalid message format:', message);

    }

    console.log(event);

};


 

socket.onclose = (event) => {

    console.log(`WebSocket closed: ${event.code} - ${event.reason}`);

};


 

socket.onerror = (error) => {

    console.error('WebSocket error:', error);

};


 


@anthoniahenry4