Examples
Your Streaming API Key is included in all the sample codes when logged in. So you can use any example right away. Only you can see this key.
Websocket Example
import websocket
import time
try:
import thread
except ImportError:
import _thread as thread
f = open("webSocketTester.log", "a")
def on_message(ws, message):
print(message)
f.write(message + "\n" )
f.flush()
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
ws.send("{\"userKey\":\"user_api_key\", \"symbol\":\"GBPUSD\"}")
thread.start_new_thread(run, ())
if __name__ == "__main__":
ws = websocket.WebSocketApp("wss://marketdata.tradermade.com/feedadv",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
require_once("vendor/autoload.php");
$client = new WebSocket\Client("wss://marketdata.tradermade.com/feedadv");
$message = $client->receive();
echo $message;
$client->text("{\"userKey\":\"user_api_key\", \"symbol\":\"GBPUSD,EURUSD\"}");
while(true){
$message = $client->receive();
if(strcmp($message,"connected") !== 0){
$decoded_json = json_decode($message);
echo $decoded_json->symbol, " ", $decoded_json->ts, " ", $decoded_json->bid, " ", $decoded_json->ask, "\n";
}
}
library(websocket)
library(jsonlite)
{
ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
ws$onMessage(function(event) {
d <- event$data
if (d != "Connected"){
json = fromJSON(d)
cat(" Symbol ", json$symbol, json$ts, json$bid, json$ask, json$mid)
}
})
ws$onOpen(function(event) {
ws$send("{\"userKey\":\"user_api_key\", \"symbol\":\"GBPUSD,EURUSD\"}")
})
}
// +build ignore
package main
import (
"flag"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
func main() {
flag.Parse()
log.SetFlags(0)
messageOut := make(chan string)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "wss", Host: "marketdata.tradermade.com", Path: "/feedadv",}
log.Printf("connecting to %s", u.String())
c, resp, err := websocket.DefaultDialer.Dial(u.String(), nil);
if err != nil {
log.Printf("handshake failed with status %d", resp.StatusCode)
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
if string(message) == "Connected"{
log.Printf("Send Sub Details: %s", message)
messageOut <- "{\"userKey\":\"user_api_key\", \"symbol\":\"EURUSD\"}"
}
}
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case m := <-messageOut:
log.Printf("Send Message %s", m)
err := c.WriteMessage(websocket.TextMessage, []byte(m))
if err != nil {
log.Println("write:", err)
return
}
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Websocket.Client;
namespace TraderMadeWebSocketTest
{
class Program
{
private string streaming_API_Key = "user_api_key";
static void Main(string[] args)
{
Program prg = new Program();
prg.Initialize();
}
private void Initialize()
{
Console.CursorVisible = false;
try
{
var exitEvent = new ManualResetEvent(false);
var url = new Uri("wss://marketdata.tradermade.com/feedadv");
using (var client = new WebsocketClient(url))
{
client.ReconnectTimeout = TimeSpan.FromSeconds(30);
client.ReconnectionHappened.Subscribe(info =>
{
Console.WriteLine("Reconnection happened, type: " + info.Type);
});
client.MessageReceived.Subscribe(msg =>
{
Console.WriteLine("Message received: " + msg);
if (msg.ToString().ToLower() == "connected")
{
string data = "{\"userKey\":\"" + user_api_key + "\", \"symbol\":\"EURUSD,GBPUSD,USDJPY\"}";
client.Send(data);
}
});
client.Start();
//Task.Run(() => client.Send("{ message }"));
exitEvent.WaitOne();
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.ToString());
}
Console.ReadKey();
}
}
}
const WebSocket = require ('ws');
var reconnectInterval = 1000 * 10
var ws;
var connect = function(){
const ws = new WebSocket ('wss://marketdata.tradermade.com/feedadv');
ws.on('open', function open() {
ws.send("{\"userKey\":\"user_api_key\", \"symbol\":\"GBPUSD\"}");
});
ws.on('close', function() {
console.log('socket close : will reconnect in ' + reconnectInterval );
setTimeout(connect, reconnectInterval)
});
ws.on('message', function incoming(data) {
console.log(data);
});
};
connect();
package client;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
public class ClientCaller {
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(100);
WebSocket ws = HttpClient
.newHttpClient()
.newWebSocketBuilder()
.buildAsync(URI.create("wss://marketdata.tradermade.com/feedadv"), new WebSocketClient(latch))
.join();
// ws.sendText("Hello!", true);
latch.await();
}
private static class WebSocketClient implements WebSocket.Listener {
private final CountDownLatch latch;
public WebSocketClient(CountDownLatch latch) { this.latch = latch; }
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
WebSocket.Listener.super.onOpen(webSocket);
webSocket.sendText("{\"userKey\":\"user_api_key\", \"symbol\":\"GBPUSD\"}", true);
}
@Override
public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) {
System.out.println("onText received " + data);
latch.countDown();
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Bad day! " + webSocket.toString());
WebSocket.Listener.super.onError(webSocket, error);
}
}
}
SocketIO Example
import socketio
# standard Python
sio = socketio.Client()
@sio.event
def connect():
print("I'm connected!")
sio.emit('login', {'userKey': 'user_api_key'})
@sio.event
def connect_error():
print("The connection failed!")
@sio.event
def message(data):
print('I received a message!')
@sio.on('handshake')
def on_message(data):
print('HandShake', data)
sio.emit('symbolSub', {'symbol': 'USDJPY'})
sio.emit('symbolSub', {'symbol': 'GBPUSD'})
sio.emit('symbolSub', {'symbol': 'EURUSD'})
@sio.on('price')
def on_message(data):
print('Price Data ', data)
sio.connect('https://marketdata.tradermade.com')
// using the ElephantIO library
// composer require elephantio/elephant.io
<?php
require_once 'vendor/autoload.php';
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
// Create Socket.IO client
$client = new Client(new Version2X('https://marketdata.tradermade.com'));
try {
// Connect to server
$client->initialize();
echo "I'm connected!\n";
// Send login message
$client->emit('login', ['userKey' => 'user_api_key']);
// Listen for events in a loop
while (true) {
// Read incoming messages
$message = $client->read();
if ($message) {
$eventName = $message['name'] ?? '';
$data = $message['args'][0] ?? [];
switch ($eventName) {
case 'connect':
echo "Connected successfully!\n";
break;
case 'connect_error':
echo "The connection failed!\n";
break;
case 'message':
echo "I received a message!\n";
print_r($data);
break;
case 'handshake':
echo "HandShake: ";
print_r($data);
// Subscribe to symbols
$client->emit('symbolSub', ['symbol' => 'USDJPY']);
$client->emit('symbolSub', ['symbol' => 'GBPUSD']);
$client->emit('symbolSub', ['symbol' => 'EURUSD']);
break;
case 'price':
echo "Price Data: ";
print_r($data);
break;
default:
if ($eventName) {
echo "Received event '$eventName': ";
print_r($data);
}
break;
}
}
// Small delay to prevent excessive CPU usage
usleep(100000); // 0.1 seconds
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
} finally {
// Close connection
$client->close();
}
?>
# Install required packages if not already installed
# install.packages(c("websocket", "jsonlite", "httr"))
library(websocket)
library(jsonlite)
library(httr)
# Socket.IO client implementation in R
create_socketio_client <- function(url) {
# Get Socket.IO session info
session_url <- paste0(url, "/socket.io/?EIO=4&transport=polling")
response <- GET(session_url)
if (status_code(response) == 200) {
content_text <- content(response, "text")
# Parse the session ID (simplified parsing)
session_id <- gsub(".*\"sid\":\"([^\"]+)\".*", "\\1", content_text)
cat("Session ID:", session_id, "\n")
} else {
stop("Failed to get session ID")
}
# Create WebSocket URL
ws_url <- paste0(gsub("^http", "ws", url), "/socket.io/?EIO=4&transport=websocket&sid=", session_id)
# WebSocket connection
ws <- WebSocket$new(ws_url)
# Connection handlers
ws$onOpen(function(event) {
cat("I'm connected!\n")
# Send Socket.IO connect packet
ws$send("40")
# Send login message
login_data <- list(userKey = "user_api_key")
login_message <- paste0('42["login",', toJSON(login_data, auto_unbox = TRUE), ']')
ws$send(login_message)
})
ws$onClose(function(event) {
cat("The connection closed!\n")
})
ws$onError(function(event) {
cat("The connection failed!\n")
cat("Error:", event$message, "\n")
})
ws$onMessage(function(event) {
message <- event$data
cat("Received:", message, "\n")
# Parse Socket.IO message format
if (grepl("^42", message)) {
json_data <- substring(message, 3)
tryCatch({
data <- fromJSON(json_data)
if (length(data) >= 2 && is.character(data[1])) {
event_name <- data[[1]]
payload <- if (length(data) > 1) data[[2]] else list()
# Handle different events
switch(event_name,
"handshake" = {
cat("HandShake:\n")
print(payload)
# Subscribe to symbols
symbol_sub <- function(symbol) {
sub_data <- list(symbol = symbol)
sub_message <- paste0('42["symbolSub",', toJSON(sub_data, auto_unbox = TRUE), ']')
ws$send(sub_message)
}
symbol_sub("USDJPY")
symbol_sub("GBPUSD")
symbol_sub("EURUSD")
},
"price" = {
cat("Price Data:\n")
print(payload)
},
"message" = {
cat("I received a message!\n")
print(payload)
},
{
cat("Event '", event_name, "':\n")
print(payload)
}
)
}
}, error = function(e) {
cat("Error parsing message:", e$message, "\n")
})
}
})
return(ws)
}
# Main execution
tryCatch({
# Create and connect to Socket.IO server
client <- create_socketio_client("https://marketdata.tradermade.com")
# Keep the connection alive
cat("Connecting to server...\n")
# Run for a specified time or until interrupted
# You can adjust the sleep time or use a different approach
for (i in 1:3600) { # Run for 1 hour (3600 seconds)
Sys.sleep(1)
# Process any pending messages (websocket handles this automatically)
# Break if connection is closed
if (client$readyState() != 1) {
cat("Connection lost, exiting...\n")
break
}
}
}, error = function(e) {
cat("Error:", e$message, "\n")
}, finally = {
# Clean up
if (exists("client") && !is.null(client)) {
client$close()
}
})
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
socketio "github.com/zhouhui8915/go-socket.io-client"
)
// LoginData represents the login message structure
type LoginData struct {
UserKey string `json:"userKey"`
}
// SymbolData represents the symbol subscription structure
type SymbolData struct {
Symbol string `json:"symbol"`
}
func main() {
// Create Socket.IO client options
opts := &socketio.Options{
Transport: "websocket",
Query: make(map[string]string),
}
// Connect to the Socket.IO server
client, err := socketio.NewClient("https://marketdata.tradermade.com", opts)
if err != nil {
log.Fatal("Failed to create client:", err)
}
// Handle connection event
client.On("connect", func() {
fmt.Println("I'm connected!")
// Send login message
loginData := LoginData{UserKey: "user_api_key"}
client.Emit("login", loginData)
})
// Handle connection error
client.On("connect_error", func() {
fmt.Println("The connection failed!")
})
// Handle disconnection
client.On("disconnect", func() {
fmt.Println("Disconnected from server")
})
// Handle generic message event
client.On("message", func(data interface{}) {
fmt.Println("I received a message!")
fmt.Printf("Message: %+v\n", data)
})
// Handle handshake event
client.On("handshake", func(data interface{}) {
fmt.Printf("HandShake: %+v\n", data)
// Subscribe to symbols
symbols := []string{"USDJPY", "GBPUSD", "EURUSD"}
for _, symbol := range symbols {
symbolData := SymbolData{Symbol: symbol}
client.Emit("symbolSub", symbolData)
fmt.Printf("Subscribed to: %s\n", symbol)
}
})
// Handle price data event
client.On("price", func(data interface{}) {
fmt.Printf("Price Data: %+v\n", data)
// If you need to parse the data as JSON
if jsonData, err := json.MarshalIndent(data, "", " "); err == nil {
fmt.Printf("Price JSON: %s\n", string(jsonData))
}
})
// Handle any other events
client.On("error", func(err error) {
fmt.Printf("Socket error: %v\n", err)
})
// Connect to the server
if err := client.Connect(); err != nil {
log.Fatal("Failed to connect:", err)
}
// Set up graceful shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// Keep the connection alive
fmt.Println("Client running... Press Ctrl+C to exit")
// Run until interrupted
select {
case <-c:
fmt.Println("\nShutting down gracefully...")
client.Close()
os.Exit(0)
}
}
using System;
using System.Threading.Tasks;
using System.Threading;
using SocketIOClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SocketIOClientApp
{
// Data models for JSON serialization
public class LoginData
{
[JsonProperty("userKey")]
public string UserKey { get; set; }
}
public class SymbolData
{
[JsonProperty("symbol")]
public string Symbol { get; set; }
}
class Program
{
private static SocketIO client;
private static CancellationTokenSource cancellationTokenSource;
static async Task Main(string[] args)
{
cancellationTokenSource = new CancellationTokenSource();
// Handle Ctrl+C gracefully
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
cancellationTokenSource.Cancel();
};
try
{
await RunSocketIOClient();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
await CleanupAsync();
}
}
static async Task RunSocketIOClient()
{
// Create Socket.IO client
client = new SocketIO("https://marketdata.tradermade.com");
// Set up event handlers
SetupEventHandlers();
try
{
// Connect to the server
Console.WriteLine("Connecting to server...");
await client.ConnectAsync();
// Keep the application running
Console.WriteLine("Client running... Press Ctrl+C to exit");
await WaitForCancellation();
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
}
}
static void SetupEventHandlers()
{
// Handle successful connection
client.OnConnected += async (sender, e) =>
{
Console.WriteLine("I'm connected!");
// Send login message
var loginData = new LoginData { UserKey = "user_api_key" };
await client.EmitAsync("login", loginData);
};
// Handle connection errors
client.OnError += (sender, e) =>
{
Console.WriteLine("The connection failed!");
Console.WriteLine($"Error: {e}");
};
// Handle disconnection
client.OnDisconnected += (sender, e) =>
{
Console.WriteLine("Disconnected from server");
Console.WriteLine($"Reason: {e}");
};
// Handle reconnection
client.OnReconnected += (sender, e) =>
{
Console.WriteLine($"Reconnected! Attempt: {e}");
};
// Handle generic message event
client.On("message", response =>
{
Console.WriteLine("I received a message!");
Console.WriteLine($"Message: {response}");
});
// Handle handshake event
client.On("handshake", async response =>
{
Console.WriteLine($"HandShake: {response}");
// Subscribe to symbols
string[] symbols = { "USDJPY", "GBPUSD", "EURUSD" };
foreach (string symbol in symbols)
{
var symbolData = new SymbolData { Symbol = symbol };
await client.EmitAsync("symbolSub", symbolData);
Console.WriteLine($"Subscribed to: {symbol}");
}
});
// Handle price data event
client.On("price", response =>
{
Console.WriteLine("Price Data:");
try
{
// Pretty print the JSON response
if (response.GetValue() is JToken jsonData)
{
string formattedJson = jsonData.ToString(Formatting.Indented);
Console.WriteLine(formattedJson);
}
else
{
Console.WriteLine(response);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing price data: {ex.Message}");
Console.WriteLine($"Raw data: {response}");
}
});
// Handle any other events (optional)
client.OnAny((eventName, response) =>
{
// Only log events we haven't specifically handled
if (eventName != "message" && eventName != "handshake" && eventName != "price")
{
Console.WriteLine($"Event '{eventName}': {response}");
}
});
}
static async Task WaitForCancellation()
{
try
{
await Task.Delay(-1, cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
Console.WriteLine("\nShutdown requested...");
}
}
static async Task CleanupAsync()
{
if (client != null)
{
Console.WriteLine("Closing connection...");
await client.DisconnectAsync();
client.Dispose();
}
cancellationTokenSource?.Dispose();
Console.WriteLine("Cleanup completed.");
}
}
}
var io = require('socket.io-client');
var socket = io.connect('https://marketdata.tradermade.com', {reconnect: true});
var connected = false;
socket.on('connect', function () {
console.log('Connected! Please CTRL+C and restart if you see this messsage more than twice');
console.log("disconnecting and reconnecting can take upto a minute and multiple attempts")
console.log(".......")
socket.emit('login', {userKey: "user_api_key"});
});
socket.on('disconnect', function (msg) {
console.log(msg);
});
socket.on('handshake', function (msg) {
console.log(msg);
connected = true;
socket.emit("symbolSub", {symbol: "GBPUSD"});
socket.emit("symbolSub", {symbol: "EURUSD"});
});
socket.on('subResponse', function (msg) {
console.log(msg)
});
socket.on('message', function (msg) {
console.log(msg)
});
socket.on('price', function (message){
var data = message.split(" ")
console.log(data[0] + " " + data[1] + " " + data[2] + " " + data[3] + " " + parseDate(data[4]))
});
function parseDate(dateString){
var reggie = /(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
return dateObject
}
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import org.json.JSONObject;
import org.json.JSONException;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
public class SocketIOClient {
private Socket socket;
private final CountDownLatch latch = new CountDownLatch(1);
private volatile boolean running = true;
public static void main(String[] args) {
SocketIOClient client = new SocketIOClient();
// Handle shutdown gracefully
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("\nShutting down gracefully...");
client.shutdown();
}));
try {
client.start();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
public void start() throws URISyntaxException {
// Configure Socket.IO options
IO.Options options = IO.Options.builder()
.setTransports(new String[]{"websocket"})
.build();
// Create Socket.IO connection
socket = IO.socket("https://marketdata.tradermade.com", options);
setupEventHandlers();
System.out.println("Connecting to server...");
socket.connect();
// Keep the application running
System.out.println("Client running... Press Ctrl+C to exit");
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void setupEventHandlers() {
// Handle successful connection
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("I'm connected!");
// Send login message
try {
JSONObject loginData = new JSONObject();
loginData.put("userKey", "user_api_key");
socket.emit("login", loginData);
} catch (JSONException e) {
System.err.println("Error creating login data: " + e.getMessage());
}
}
});
// Handle connection errors
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("The connection failed!");
if (args.length > 0) {
System.err.println("Error details: " + args[0]);
}
}
});
// Handle disconnection
socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("Disconnected from server");
if (args.length > 0) {
System.out.println("Reason: " + args[0]);
}
}
});
// Handle generic message event
socket.on("message", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("I received a message!");
for (Object arg : args) {
System.out.println("Message: " + arg);
}
}
});
// Handle handshake event
socket.on("handshake", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("HandShake received");
for (Object arg : args) {
System.out.println("HandShake data: " + arg);
}
// Subscribe to symbols
subscribeToSymbols();
}
});
// Handle price data event
socket.on("price", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("Price Data received:");
for (Object arg : args) {
System.out.println("Price: " + arg);
// Try to parse as JSON for better formatting
try {
if (arg instanceof JSONObject) {
JSONObject priceData = (JSONObject) arg;
System.out.println("Formatted price data: " + priceData.toString(2));
}
} catch (JSONException e) {
System.err.println("Error formatting price data: " + e.getMessage());
}
}
}
});
// Handle reconnection
socket.on(Socket.EVENT_RECONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("Reconnected to server");
if (args.length > 0) {
System.out.println("Attempt number: " + args[0]);
}
}
});
}
private void subscribeToSymbols() {
String[] symbols = {"USDJPY", "GBPUSD", "EURUSD"};
for (String symbol : symbols) {
try {
JSONObject symbolData = new JSONObject();
symbolData.put("symbol", symbol);
socket.emit("symbolSub", symbolData);
System.out.println("Subscribed to: " + symbol);
} catch (JSONException e) {
System.err.println("Error subscribing to " + symbol + ": " + e.getMessage());
}
}
}
public void shutdown() {
running = false;
if (socket != null) {
socket.disconnect();
socket.close();
}
latch.countDown();
System.out.println("Cleanup completed.");
}
}