Guides

WebSockets

General information

Base endpoint

To connect to Deriv's WebSocket APIs, you'll need to use the following base endpoint:

wss://ws.derivws.com/websockets/v3?app_id={app_id}

Make sure to replace {app_id} with the unique ID of the application you registered.

Rate limits

The rate limits for API requests can change over time. To find out the current limit, you can make a website_status/server status call and check the api_call_limits field. This ensures you always have the most up-to-date information.

Session validity

Your WebSocket session will time out after 2 minutes of inactivity. If there are no requests or responses during this time, the server will close the connection. To prevent this, send requests periodically to keep the connection alive.

For example, you can send a ping request or another simple call like time at regular intervals.

Create WebSocket

To get started with WebSockets, you must first create a new WebSocket instance. Here’s how you can do it:

Create a WebSocket instance

Use the WebSocket constructor to create a new instance:

🚧

Warning:

Make sure to replace {app_id} with the unique ID of the application you have registered. You can find it in the Manage Applications tab.

let socket = new WebSocket('wss://ws.derivws.com/websockets/v3?app_id={app_id}');

📘

Important: Secure vs. Unsecured Connections

wss:// establishes a secure WebSocket connection (encrypted and protected).
ws:// establishes an unsecured WebSocket connection (not encrypted).

Events

WebSocket communication revolves around 4 key events. Understanding these key events will help you manage the connection effectively.

OnOpen

What it does: This event is triggered when the connection to the server is successfully established.
What to know: Once this event fires, the WebSocket’s readyState property becomes 1 indicating the connection is open and ready for communication. The readyState can have several values. For more information, check out the MDN WebSocket readyState documentation.

socket.onopen = function (e) {
  console.log('[open] Connection established');
  console.log('Sending to server');
  const sendMessage = JSON.stringify({ ping: 1 });
  socket.send(sendMessage);
};

OnMessage

What it does: Fires whenever a message is received from the server.
Usage: Use this event to capture and handle incoming data from the server.

socket.onmessage = function (event) {
  console.log(`[message] Data received from server: ${event.data}`);
};

OnClose

What it does: Triggers when the WebSocket connection is closed by the client, server, or due to a connection failure.
Additional details: If you close the connection using the Close() method, you can provide a code and message to explain the reason. The server will typically send back the same code and message.

socket.onclose = function (event) {
  if (event.wasClean) {
    console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    // e.g. server process killed or network down
    // event.code is usually 1006 in this case
    console.log('[close] Connection died');
  }
};

OnError

What It does: Triggers when an error occurs with the WebSocket connection.
Handling errors: Use this event to detect and handle errors, ensuring your application can respond or retry as needed.

socket.onerror = function (error) {
  console.log(`[error] ${error.message}`);
};

Methods

Here’s a quick rundown of the essential methods you'll use with WebSockets:

Open

How it works: Call Open() to start the connection process with the server.
Non-blocking call: After OnOpen is triggered, you can begin sending messages. The call doesn’t block your script, and you can continue executing other code while waiting for the connection.

Send

Purpose: The Send method transmits data to the server. It supports several data formats, including strings and byte arrays (byte[]).
Handling large messages: For messages larger than 32,767 bytes, the WebSocket automatically splits them into fragments, managing the transmission of each part sequentially.

Close

When to use: Once you’ve finished all communication, call Close() to terminate the connection.
Graceful shutdown: This ensures the connection closes properly, freeing up resources and signalling to the server that communication has ended. Once a WebSocket is closed, it cannot be reused; you’ll need to create a new instance for future connections.

🚧

You cannot reuse a closed WebSocket instance, you have to create and set up a new one.

const app_id = app_id; // Replace with your app_id .
const socket = new WebSocket(`wss://ws.derivws.com/websockets/v3?app_id=${app_id}`); // Create a new WebSocket connection using the app_id

// Event handler for when the WebSocket connection is opened
socket.onopen = function (e) {
  console.log('[open] Connection established'); // Log connection establishment
  console.log('Sending to server');

  const sendMessage = JSON.stringify({ ping: 1 }); // Create a ping message in JSON format
  socket.send(sendMessage); // Send the ping message to the server
};

// Event handler for when a message is received from the server
socket.onmessage = function (event) {
  console.log(`[message] Data received from server: ${event.data}`); // Log the message received from the server
};

// Event handler for when the WebSocket connection is closed
socket.onclose = function (event) {
  if (event.wasClean) {
    console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`); // Log clean close with code and reason
  } else {
    // Handle the case where the connection was closed unexpectedly
    // e.g., server process killed or network down
    // event.code is usually 1006 in this case
    console.log('[close] Connection died'); // Log an abrupt close
  }
};

// Event handler for when an error occurs with the WebSocket connection
socket.onerror = function (error) {
  console.log(`[error] ${error.message}`); // Log the error that occurred
};
import asyncio
import websockets
import json

async def connect_to_websocket():
    app_id = app_id  # Replace with your app_id or leave as 1089 for testing.
    uri = f"wss://ws.derivws.com/websockets/v3?app_id={app_id}"  # WebSocket URI with the app_id
    
    try:
        # Establish a connection to the WebSocket server
        async with websockets.connect(uri) as websocket:
            print("[open] Connection established")  # Connection opened
            print("Sending to server")

            # Prepare the message to send (ping message in JSON format)
            send_message = json.dumps({"ping": 1})
            await websocket.send(send_message)  # Send the ping message to the server

            # Wait for a response from the server
            response = await websocket.recv()
            print(f"[message] Data received from server: {response}")  # Log the server's response

    except websockets.ConnectionClosedError as e:
        # Handle the scenario where the connection is closed
        if e.code == 1000:
            print(f"[close] Connection closed cleanly, code={e.code} reason={e.reason}")  # Clean close
        else:
            print("[close] Connection died")  # Abrupt close, likely due to network or server issues

    except Exception as e:
        # Handle any other exceptions that may occur
        print(f"[error] {str(e)}")  # Log any errors that occur

# Run the WebSocket client
# asyncio.get_event_loop().run_until_complete() starts the coroutine connect_to_websocket()
asyncio.get_event_loop().run_until_complete(connect_to_websocket())

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

public class WebSocketExample {

    public static void main(String[] args) {
        try {
            // Replace with your app_id.
            int app_id = app_id;
            String serverUri = "wss://ws.derivws.com/websockets/v3?app_id=" + app_id;

            // Initialize the WebSocket client
            WebSocketClient client = new WebSocketClient(new URI(serverUri)) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    System.out.println("[open] Connection established");
                    System.out.println("Sending to server");

                    // Create a ping message in JSON format
                    String sendMessage = "{\"ping\": 1}";
                    this.send(sendMessage); // Send the ping message to the server
                }

                @Override
                public void onMessage(String message) {
                    System.out.println("[message] Data received from server: " + message); // Log the received message
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    if (remote) {
                        System.out.println("[close] Connection closed by server, code=" + code + " reason=" + reason); // Remote close
                    } else {
                        System.out.println("[close] Connection closed by client, code=" + code + " reason=" + reason); // Client close
                    }
                }

                @Override
                public void onError(Exception ex) {
                    System.out.println("[error] " + ex.getMessage()); // Log any errors
                }
                
                @Override
                public void onMessage(ByteBuffer bytes) {
                    System.out.println("[message] ByteBuffer received from server"); // Handle binary message if necessary
                }
            };

            client.connect(); // Connect to the WebSocket server

        } catch (URISyntaxException e) {
            System.out.println("[error] Invalid URI: " + e.getMessage());
        }
    }
}
/*
To run this code, you need to add the java-websocket library to your project. 
If you are using Maven, add the following dependency to your pom.xml:
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.5.2</version>
</dependency>

If you are using Gradle, add this to your build.gradle:
gradle
Copy code
implementation 'org.java-websocket:Java-WebSocket:1.5.2'
*/

use strict;
use warnings;
use AnyEvent;
use AnyEvent::WebSocket::Client;
use JSON;

my $app_id = app_id; # Replace with your app_id.
my $uri = "wss://ws.derivws.com/websockets/v3?app_id=$app_id"; # WebSocket URI with the app_id

# Create a new WebSocket client
my $client = AnyEvent::WebSocket::Client->new;

# Connect to the WebSocket server
$client->connect($uri)->cb(sub {
    my $connection = eval { shift->recv };
    
    # Check if connection was successful
    if ($@) {
        warn "[error] $@\n"; # Log any errors
        return;
    }
    
    print "[open] Connection established\n";
    print "Sending to server\n";
    
    # Prepare the ping message in JSON format
    my $send_message = encode_json({ ping => 1 });
    $connection->send($send_message); # Send the ping message to the server
    
    # Event handler for when a message is received from the server
    $connection->on(each_message => sub {
        my ($connection, $message) = @_;
        print "[message] Data received from server: " . $message->body . "\n"; # Log the received message
    });
    
    # Event handler for when the WebSocket connection is closed
    $connection->on(finish => sub {
        print "[close] Connection closed\n"; # Log connection close
    });
});

# Start the AnyEvent loop
AnyEvent->condvar->recv;


#To run this code, you need to install the required Perl modules. 
#You can install them using CPAN:
#cpan AnyEvent AnyEvent::WebSocket::Client JSON
<?php

require 'vendor/autoload.php'; // Ensure you have the WebSocket\Client installed via Composer

use WebSocket\Client;

$app_id = app_id; // Replace with your app_id.
$uri = "wss://ws.derivws.com/websockets/v3?app_id=$app_id"; // WebSocket URI with the app_id

try {
    // Create a new WebSocket client
    $client = new Client($uri);

    echo "[open] Connection established\n";
    echo "Sending to server\n";

    // Prepare the ping message in JSON format
    $sendMessage = json_encode(["ping" => 1]);
    $client->send($sendMessage); // Send the ping message to the server

    // Receive message from the server
    $response = $client->receive();
    echo "[message] Data received from server: $response\n"; // Log the received message

} catch (\WebSocket\ConnectionException $e) {
    // Handle connection errors (e.g., if the WebSocket server is unreachable)
    echo "[error] Connection error: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    // Handle general exceptions
    echo "[error] " . $e->getMessage() . "\n";
}

?>
//Make sure you have Composer installed on your system. 
// If not, you can download it from getcomposer.org.

//To install the WebSocket\Client library, run:
//composer require textalk/websocket
use tokio::runtime::Runtime;
use tungstenite::{connect, Message};
use url::Url;

fn main() {
    // Create a runtime for asynchronous execution
    let rt = Runtime::new().unwrap();
    rt.block_on(async {
        let app_id = app_id; // Replace with your app_id.
        let url = format!("wss://ws.derivws.com/websockets/v3?app_id={}", app_id);

        // Connect to the WebSocket server
        let (mut socket, response) = connect(Url::parse(&url).unwrap()).expect("Can't connect");

        println!("[open] Connection established");

        // Prepare the ping message in JSON format
        let send_message = r#"{"ping": 1}"#;

        println!("Sending to server");
        socket.write_message(Message::Text(send_message.into())).unwrap(); // Send the ping message to the server

        // Receive message from the server
        let msg = socket.read_message().expect("Error reading message");
        println!("[message] Data received from server: {}", msg);

        // Close the connection cleanly
        socket.close(None).unwrap();
        println!("[close] Connection closed cleanly");
    });
}

import Foundation

// Function to create and handle WebSocket connection
func connectWebSocket() {
    let appID = app_id // Replace with your app_id.
    let url = URL(string: "wss://ws.derivws.com/websockets/v3?app_id=\(appID)")! // WebSocket URL with the app_id
    let request = URLRequest(url: url)
    
    // Create a WebSocket task
    let webSocketTask = URLSession.shared.webSocketTask(with: request)
    
    // Start the WebSocket connection
    webSocketTask.resume()
    print("[open] Connection established")
    
    // Function to send a ping message to the server
    let sendPingMessage = {
        let message = URLSessionWebSocketTask.Message.string("{\"ping\": 1}") // Prepare the ping message in JSON format
        webSocketTask.send(message) { error in
            if let error = error {
                print("[error] Failed to send message: \(error.localizedDescription)")
            } else {
                print("Sending to server")
            }
        }
    }
    
    // Send the ping message
    sendPingMessage()
    
    // Function to receive messages from the server
    func receiveMessage() {
        webSocketTask.receive { result in
            switch result {
            case .success(let message):
                switch message {
                case .string(let text):
                    print("[message] Data received from server: \(text)")
                case .data(let data):
                    print("[message] Data received from server: \(data)")
                @unknown default:
                    print("[message] Received unknown message type")
                }
                
                // Continue to receive messages
                receiveMessage()
                
            case .failure(let error):
                print("[error] Failed to receive message: \(error.localizedDescription)")
            }
        }
    }
    
    // Start receiving messages
    receiveMessage()
    
    // Close the WebSocket connection cleanly
    webSocketTask.cancel(with: .normalClosure, reason: nil)
    print("[close] Connection closed cleanly")
}

// Call the function to connect to the WebSocket
connectWebSocket()

// Keep the program running to wait for messages
RunLoop.main.run()

#include <libwebsockets.h>
#include <string.h>
#include <stdlib.h>

static int callback_websocket(struct lws *wsi, enum lws_callback_reasons reason, 
                              void *user, void *in, size_t len) {
    switch (reason) {
        case LWS_CALLBACK_CLIENT_ESTABLISHED:
            printf("[open] Connection established\n");
            const char *ping_message = "{\"ping\": 1}";
            lws_write(wsi, (unsigned char *)ping_message, strlen(ping_message), LWS_WRITE_TEXT);
            printf("Sending to server\n");
            break;

        case LWS_CALLBACK_CLIENT_RECEIVE:
            printf("[message] Data received from server: %.*s\n", (int)len, (char *)in);
            break;

        case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
            printf("[error] Connection error\n");
            break;

        case LWS_CALLBACK_CLIENT_CLOSED:
            printf("[close] Connection closed\n");
            break;

        default:
            break;
    }

    return 0;
}

int main(void) {
    struct lws_context_creation_info info;
    struct lws_client_connect_info ccinfo = {0};
    struct lws_context *context;
    struct lws *wsi;

    memset(&info, 0, sizeof(info));
    info.port = CONTEXT_PORT_NO_LISTEN;
    info.protocols = protocols;

    context = lws_create_context(&info);
    if (context == NULL) {
        fprintf(stderr, "[error] Failed to create context\n");
        return -1;
    }

    ccinfo.context = context;
    ccinfo.address = "ws.derivws.com";
    ccinfo.port = 443;
    ccinfo.path = "/websockets/v3?app_id=app_id"; // Replace with your app_id or leave as 1089 for testing
    ccinfo.host = lws_canonical_hostname(context);
    ccinfo.origin = "origin";
    ccinfo.protocol = protocols[0].name;
    ccinfo.ssl_connection = LCCSCF_USE_SSL;
    ccinfo.pwsi = &wsi;

    if (lws_client_connect_via_info(&ccinfo) == NULL) {
        fprintf(stderr, "[error] Failed to initiate connection\n");
        lws_context_destroy(context);
        return -1;
    }

    // Run the event loop
    while (lws_service(context, 1000) >= 0) {
        // Event loop
    }

    lws_context_destroy(context);

    return 0;
}

// List of supported protocols
static struct lws_protocols protocols[] = {
    {
        "example-protocol",
        callback_websocket,
        0,
        0,
    },
    { NULL, NULL, 0, 0 } // Terminator
};

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class WebSocketExample
{
    public static async Task Main(string[] args)
    {
        string app_id = "app_id"; // Replace with your app_id.
        string uri = $"wss://ws.derivws.com/websockets/v3?app_id={app_id}"; // WebSocket URI with the app_id

        using (ClientWebSocket webSocket = new ClientWebSocket())
        {
            try
            {
                // Connect to the WebSocket server
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                Console.WriteLine("[open] Connection established");
                
                // Send a ping message to the server
                string sendMessage = "{\"ping\": 1}"; // Prepare the ping message in JSON format
                ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(sendMessage));
                await webSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                Console.WriteLine("Sending to server");

                // Receive message from the server
                var buffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                string response = Encoding.UTF8.GetString(buffer, 0, result.Count);
                Console.WriteLine("[message] Data received from server: " + response);

                // Close the WebSocket connection cleanly
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close connection", CancellationToken.None);
                Console.WriteLine("[close] Connection closed cleanly");
            }
            catch (WebSocketException e)
            {
                Console.WriteLine("[error] WebSocket error: " + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("[error] " + e.Message);
            }
        }
    }
}

package main

import (
    "fmt"
    "log"
    "net/url"
    "os"
    "os/signal"
    "time"

    "github.com/gorilla/websocket"
)

func main() {
    // Define the WebSocket server URL
    appID := "app_id" // Replace with your app_id.
    serverURL := url.URL{Scheme: "wss", Host: "ws.derivws.com", Path: "/websockets/v3", RawQuery: "app_id=" + appID}
    fmt.Printf("Connecting to %s\n", serverURL.String())

    // Connect to the WebSocket server
    c, _, err := websocket.DefaultDialer.Dial(serverURL.String(), nil)
    if err != nil {
        log.Fatal("Dial error:", err)
    }
    defer c.Close()

    done := make(chan struct{})

    // Goroutine to handle receiving messages from the server
    go func() {
        defer close(done)
        for {
            _, message, err := c.ReadMessage()
            if err != nil {
                log.Println("Read error:", err)
                return
            }
            fmt.Printf("[message] Data received from server: %s\n", message)
        }
    }()

    // Send a ping message to the server
    pingMessage := `{"ping": 1}` // Prepare the ping message in JSON format
    err = c.WriteMessage(websocket.TextMessage, []byte(pingMessage))
    if err != nil {
        log.Println("Write error:", err)
        return
    }
    fmt.Println("Sending to server")

    // Set up signal handling to gracefully close the connection
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    // Loop to handle connection closure or interruptions
    for {
        select {
        case <-done:
            return
        case <-interrupt:
            fmt.Println("[close] Interrupt signal received. Closing connection.")
            // Close the WebSocket connection gracefully
            err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
            if err != nil {
                log.Println("Write close error:", err)
                return
            }
            select {
            case <-done:
            case <-time.After(time.Second):
            }
            return
        }
    }
}

By understanding these events and methods, you can efficiently handle WebSocket connections in your application.

WebSockets provide a robust solution for real-time communication, allowing you to maintain smooth, responsive and dynamic applications.

ℹ️

References

WebSocket APIs - MDN