Search code examples
rapiwebapihttr

httr authentication login/password in "xtb" API


I need to authenticate and get prices using this api

I have no experience with api so my attempt to login gives an error

login <- "vikov98261@jesdoit.com"
pass <- "QazQaz123"

library(httr)
resp <- POST("xapi.xtb.com", 
             body=list(userId = login,
                       password = pass) )

Error in curl::curl_fetch_memory(url, handle = handle) : 
  Failed to connect to xapi.xtb.com port 80: Timed out

Can someone show me how to do it right. I would like an example of how the login request works. And also I would like an example of how to get the prices of any currency


Solution

  • Their API documentation uses WebSocket syntax, so I assume xapi.xtb.com may only be used by the clients. I, for once, only managed to get WebSocket to work.

    In order to make this work in r you would need a WebSocket client library for r, such as websocket. Once you have that:

    1. Define connection

    ws <- WebSocket$new("wss://ws.xtb.com/demo")
    

    2. Log in

    WebSocket clients work with events. The 'open' event is generated once the connection is established and the 'message' events are generated when messages are received. You need to write handlers for them to orchestrate the way you want to use the XTB API.

    The first event will be 'open', so use that to send the login command.

    ws$onOpen(function(event) {
      ws$send({
        "command":"login",
        "arguments": { 
           "userId":"1000",
           "password":"PASSWORD",
           "appId":"test",
           "appName":"test"
        }
      })
    })
    

    3. Your logic

    The response to your login command will trigger a 'message' event, the output of which you will need to handle in your code.

    ws$onMessage( <your-code-goes-here> )
    

    The easiest way would probably be to send new commands based on what is the structure of the received message, although it can get really complicated with many commands.

    4. Connect

    After all handles have been defined, don't forget to connect.

    ws$connect()