Skip to content

R

Important

All these source codes are only examples used for testing. We don't provide any guarantee or responsibility about it. Use these examples at your own risk.

Generate source code instantly

Select your desired programming language via our web interface to automatically retrieve code:

MTsocketAPI source code

Example 1: Get EURUSD price

getprices.r
library(httr)

url <- "http://127.0.0.1:81/v1/quote"

queryString <- list(symbol = "EURUSD")

response <- VERB("GET", url, query = queryString, content_type("application/octet-stream"), accept("application/json"))

content(response, "text")
  1. Install dependencies:

    sudo apt update
    sudo apt install r-base
    
  2. Install the httr package:

    sudo R -e 'install.packages("httr", repos="https://cloud.r-project.org")'
    
  3. Run the Script:

    Rscript getquote.r
    

Example 2: Send buy order

sendorder.r
library(httr)

url <- "http://127.0.0.1:81/v1/order"

queryString <- list(
  symbol = "EURUSD",
  volume = "0.01",
  type = "ORDER_TYPE_BUY"
)

payload <- ""

response <- VERB("POST", url, body = payload, query = queryString, content_type("application/json"), accept("application/json"))

content(response, "text")
  1. Install dependencies:

    sudo apt update
    sudo apt install r-base
    
  2. Install the httr package:

    sudo R -e 'install.packages("httr", repos="https://cloud.r-project.org")'
    
  3. Run the Script:

    Rscript sendorder.r
    

Example 3: Stream EURUSD price using websockets

streamprices.r
library(httr)
library(websocket)

# ---- HTTP POST ----
url <- "http://127.0.0.1:81/v1/track/prices"
queryString <- list(symbols = "EURUSD")
payload <- ""
response <- httr::VERB("POST", url, body = payload, query = queryString, 
                      httr::content_type("application/json"), httr::accept("application/json"))
print(httr::content(response, "text"))

# ---- WebSocket ----
ws_url <- "ws://127.0.0.1:81"
ws <- websocket::WebSocket$new(ws_url)

# Events
ws$onMessage(function(event) {
  cat("Received data:", event$data, "\n")
})

ws$onOpen(function(event) {
  cat("Connected to WebSocket server\n")
})

ws$onClose(function(event) {
  cat("Connection closed\n")
  httpuv::stopAllServers()
})

ws$onError(function(event) {
  cat("Error:", event$message, "\n")
})

# Loop
cat("Listening for messages... (Press Ctrl+C to exit)\n")
while(TRUE) {
  httpuv::service()
  Sys.sleep(0.1)
}
  1. Install dependencies:

    sudo apt update
    sudo apt install r-base
    
  2. Install the required packages:

    sudo R -e 'install.packages(c("httr", "websockets", "httpuv"), repos="https://cloud.r-project.org")'
    
  3. Run the Script:

    Rscript streamprices.r