Check website status
Follow these simple steps to look into general settings like call limits, currency information, supported languages and more using the Deriv API:
- Import the API module: Load the
DerivAPIBasic
module to interact with the Deriv API. - Setup WebSocket: Establish a WebSocket connection using the
app_id
for authentication. - Initialize the API: Create an instance of
DerivAPIBasic
using the WebSocket connection. - Handle API response: Define
websiteStatusResponse
to process the response, handle errors, and log website status. - Request website status: Define
getWebsiteStatus
to send a request to the API for website status when called. - Button event listener: Attach an event listener to a button to trigger the website status request with a click.
// Import the DerivAPIBasic module from a CDN to interact with Deriv's API
import DerivAPIBasic from 'https://cdn.skypack.dev/@deriv/deriv-api';
// Set the app ID for API authentication. Use 1089 for testing or replace it with your app's ID.
const app_id = 1089;
// Create a WebSocket connection to the Deriv server using the app_id for authentication
const connection = new WebSocket(`wss://ws.derivws.com/websockets/v3?app_id=${app_id}`);
// Initialize the API using the WebSocket connection
const api = new DerivAPIBasic({ connection });
// This function handles the API response for website status
const websiteStatusResponse = async (res) => {
// Parse the response data from the WebSocket message
const data = JSON.parse(res.data);
// If there is an error in the response, log the error message and disconnect
if (data.error !== undefined) {
console.log('Error : ', data.error?.message);
connection.removeEventListener('message', websiteStatusResponse, false); // Stop listening for messages
await api.disconnect(); // Disconnect from the API
}
// If the message type is 'website_status', log the website status
if (data.msg_type === 'website_status') {
console.log(data.website_status);
}
// Remove the event listener once the status is received
connection.removeEventListener('message', websiteStatusResponse, false);
};
// This function requests the website status from the API
const getWebsiteStatus = async () => {
connection.addEventListener('message', websiteStatusResponse); // Add an event listener for incoming WebSocket messages
await api.websiteStatus(); // Send the 'websiteStatus' request to the API
};
// Add a click event listener to the button to trigger the website status request
const website_status_button = document.querySelector('#websiteStatus');
website_status_button.addEventListener('click', getWebsiteStatus);
import java.net.URI;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import com.google.gson.Gson;
public class DerivAPIClient {
private static final int app_id = 1089; // Use 1089 for testing or replace with your app_id
private WebSocket webSocket;
private DerivAPIBasic api;
// Constructor to initialize WebSocket connection and Deriv API
public DerivAPIClient() {
try {
// Create a WebSocket connection to the Deriv server using the app_id
webSocket = WebSocket.newBuilder(new URI("wss://ws.derivws.com/websockets/v3?app_id=" + app_id), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("WebSocket opened");
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
handleWebsiteStatusResponse(data.toString());
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error: " + error.getMessage());
}
}).build();
api = new DerivAPIBasic(webSocket);
} catch (Exception e) {
e.printStackTrace();
}
}
// Method to handle API response
private void handleWebsiteStatusResponse(String response) {
Gson gson = new Gson();
ApiResponse data = gson.fromJson(response, ApiResponse.class);
// Check for errors in the response
if (data.error != null) {
System.out.println("Error: " + data.error.message);
webSocket.abort(); // Disconnect from WebSocket
}
// Log the website status if the message type is 'website_status'
if ("website_status".equals(data.msg_type)) {
System.out.println("Website Status: " + data.website_status);
}
}
// Method to request website status
public void getWebsiteStatus() {
api.requestWebsiteStatus();
}
// Main method to add a click event listener and request website status
public static void main(String[] args) {
DerivAPIClient client = new DerivAPIClient();
// Simulate button click to request website status
client.getWebsiteStatus();
}
}
// DerivAPIBasic class to handle API interaction
class DerivAPIBasic {
private WebSocket webSocket;
public DerivAPIBasic(WebSocket webSocket) {
this.webSocket = webSocket;
}
// Method to send a websiteStatus request
public void requestWebsiteStatus() {
String request = "{\"website_status\":1}";
webSocket.sendText(request, true);
}
}
// Class to represent API response structure
class ApiResponse {
public ErrorResponse error;
public String msg_type;
public String website_status;
}
// Class to represent error in response
class ErrorResponse {
public String message;
}
use strict;
use warnings;
use IO::Socket::SSL;
use Protocol::WebSocket::Client;
use JSON;
use AnyEvent;
my $app_id = 1089; # Use 1089 for testing or replace it with your app_id
my $url = "wss://ws.derivws.com/websockets/v3?app_id=$app_id";
my $cv = AnyEvent->condvar; # Event loop controller
# Create a WebSocket connection
my $client = Protocol::WebSocket::Client->new(url => $url);
# Callback for when WebSocket connection is established
$client->on(
connect => sub {
my ($client) = @_;
print "WebSocket connection opened\n";
# Send the request for website status
$client->send(encode_json({ website_status => 1 }));
}
);
# Callback for handling messages (responses from the WebSocket)
$client->on(
read => sub {
my ($client, $message) = @_;
handle_website_status_response($message);
}
);
# Callback for WebSocket errors
$client->on(
error => sub {
my ($client, $error) = @_;
print "Error: $error\n";
$client->disconnect;
}
);
# Connect to the WebSocket server
$client->connect;
# Function to handle the API response for website status
sub handle_website_status_response {
my ($response) = @_;
# Decode the JSON response
my $data = decode_json($response);
# If there is an error, print it and disconnect
if (exists $data->{error}) {
print "Error: $data->{error}->{message}\n";
$client->disconnect;
}
# Print the website status if the message type is 'website_status'
if ($data->{msg_type} eq 'website_status') {
print "Website Status: $data->{website_status}\n";
}
# Disconnect the client after receiving the status
$client->disconnect;
$cv->send; # End the event loop
}
# Start the event loop
$cv->recv;
<?php
require 'vendor/autoload.php';
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
use Ratchet\Client\WebSocket;
use GuzzleHttp\Client as HttpClient;
$loop = Factory::create();
$connector = new Connector($loop);
// Define the app ID
$app_id = 1089; // Use 1089 for testing or replace with your app_id
// WebSocket connection URL to the Deriv server
$ws_url = "wss://ws.derivws.com/websockets/v3?app_id=" . $app_id;
$connector($ws_url)->then(function (WebSocket $conn) use ($loop) {
echo "Connected to WebSocket\n";
// Function to handle the WebSocket messages
$conn->on('message', function ($msg) use ($conn, $loop) {
// Parse the JSON response
$response = json_decode($msg, true);
// Check if there is an error in the response
if (isset($response['error'])) {
echo "Error: " . $response['error']['message'] . "\n";
$conn->close(); // Close the connection on error
$loop->stop(); // Stop the event loop
return;
}
// If the message type is 'website_status', print the website status
if ($response['msg_type'] === 'website_status') {
echo "Website Status: " . print_r($response['website_status'], true) . "\n";
}
// Close the connection once we receive the response
$conn->close();
$loop->stop(); // Stop the event loop
});
// Send the request for website status once the connection is open
$conn->send(json_encode(['website_status' => 1]));
}, function ($e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop(); // Stop the event loop on failure
});
// Run the event loop
$loop->run();
import asyncio
import websockets
import json
# Define the app ID for API authentication
app_id = 1089 # Use 1089 for testing or replace with your app_id
# WebSocket connection URL to the Deriv server
ws_url = f"wss://ws.derivws.com/websockets/v3?app_id={app_id}"
# Function to handle API response
async def handle_website_status(websocket):
try:
# Receive the response from the WebSocket
response = await websocket.recv()
# Parse the JSON response
data = json.loads(response)
# Check for any error in the response
if 'error' in data:
print(f"Error: {data['error']['message']}")
return
# If the message type is 'website_status', print the website status
if data.get('msg_type') == 'website_status':
print("Website Status:", data.get('website_status'))
except websockets.exceptions.ConnectionClosed as e:
print(f"Connection closed with error: {e}")
# Function to request website status from the API
async def get_website_status():
# Connect to the WebSocket server
async with websockets.connect(ws_url) as websocket:
# Send a request for website status
request = json.dumps({"website_status": 1})
await websocket.send(request)
# Handle the response
await handle_website_status(websocket)
# Main function to run the asyncio event loop
async def main():
await get_website_status()
# Start the event loop
if __name__ == "__main__":
asyncio.run(main())
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::net::TcpStream;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use url::Url;
#[derive(Debug, Deserialize)]
struct ErrorResponse {
message: String,
}
#[derive(Debug, Deserialize)]
struct ApiResponse {
#[serde(rename = "msg_type")]
msg_type: String,
#[serde(rename = "website_status")]
website_status: Option<WebsiteStatus>,
error: Option<ErrorResponse>,
}
#[derive(Debug, Deserialize)]
struct WebsiteStatus {
site_status: String, // You can add more fields based on the actual API response.
}
// Function to handle the WebSocket response
async fn handle_website_status(msg: Message) {
if let Ok(text) = msg.to_text() {
// Parse the JSON response
let response: ApiResponse = match serde_json::from_str(text) {
Ok(res) => res,
Err(e) => {
println!("Failed to parse response: {}", e);
return;
}
};
// Check if there is an error in the response
if let Some(error) = response.error {
println!("Error: {}", error.message);
return;
}
// If the message type is 'website_status', print the website status
if response.msg_type == "website_status" {
if let Some(status) = response.website_status {
println!("Website Status: {:?}", status);
}
}
}
}
// Function to request website status from the API
async fn get_website_status(ws_url: &str) -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse(ws_url)?;
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
println!("WebSocket connected");
let (mut write, mut read) = ws_stream.split();
// Send a request for website status
let request = json!({
"website_status": 1
});
write
.send(Message::Text(request.to_string()))
.await
.expect("Failed to send request");
// Handle the response
while let Some(msg) = read.next().await {
match msg {
Ok(msg) => handle_website_status(msg).await,
Err(e) => {
println!("Error receiving message: {}", e);
break;
}
}
}
Ok(())
}
#[tokio::main]
async fn main() {
let app_id = 1089; // Replace with your app_id or leave as 1089 for testing.
let ws_url = format!("wss://ws.derivws.com/websockets/v3?app_id={}", app_id);
if let Err(e) = get_website_status(&ws_url).await {
println!("Error: {}", e);
}
}
import Foundation
// Define the structure for API response and errors
struct ErrorResponse: Codable {
let message: String
}
struct ApiResponse: Codable {
let msg_type: String
let website_status: WebsiteStatus?
let error: ErrorResponse?
}
struct WebsiteStatus: Codable {
let site_status: String // You can add more fields based on the actual API response.
}
// Define the app ID for API authentication
let appID = 1089 // Use 1089 for testing or replace with your app ID
let wsURL = "wss://ws.derivws.com/websockets/v3?app_id=\(appID)"
// Function to handle API response
func handleWebsiteStatusResponse(data: Data) {
let decoder = JSONDecoder()
do {
// Decode the JSON response
let response = try decoder.decode(ApiResponse.self, from: data)
// Check for errors
if let error = response.error {
print("Error: \(error.message)")
return
}
// If the message type is 'website_status', print the website status
if response.msg_type == "website_status", let websiteStatus = response.website_status {
print("Website Status: \(websiteStatus.site_status)")
}
} catch {
print("Failed to decode response: \(error)")
}
}
// Function to request website status from the API
func getWebsiteStatus() {
guard let url = URL(string: wsURL) else { return }
// Create a WebSocket task
let task = URLSession.shared.webSocketTask(with: url)
// Start the WebSocket connection
task.resume()
// Send a request for website status
let request = ["website_status": 1]
do {
let requestData = try JSONSerialization.data(withJSONObject: request)
let message = URLSessionWebSocketTask.Message.data(requestData)
task.send(message) { error in
if let error = error {
print("Failed to send message: \(error)")
}
}
} catch {
print("Failed to serialize request: \(error)")
}
// Receive the response from the WebSocket
task.receive { result in
switch result {
case .failure(let error):
print("Failed to receive message: \(error)")
case .success(let message):
switch message {
case .data(let data):
handleWebsiteStatusResponse(data: data)
case .string(let text):
if let data = text.data(using: .utf8) {
handleWebsiteStatusResponse(data: data)
}
@unknown default:
break
}
}
task.cancel(with: .goingAway, reason: nil) // Close the connection after receiving the response
}
}
// Run the WebSocket request
getWebsiteStatus()
// Keep the program running to allow the async operation to complete
RunLoop.main.run()
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/gorilla/websocket"
)
// Define the structure for API response and errors
type ErrorResponse struct {
Message string `json:"message"`
}
type WebsiteStatus struct {
SiteStatus string `json:"site_status"`
}
type ApiResponse struct {
MsgType string `json:"msg_type"`
WebsiteStatus *WebsiteStatus `json:"website_status,omitempty"`
Error *ErrorResponse `json:"error,omitempty"`
}
// Function to handle the WebSocket response
func handleWebsiteStatusResponse(message []byte) {
var response ApiResponse
if err := json.Unmarshal(message, &response); err != nil {
log.Printf("Error parsing response: %v\n", err)
return
}
// Check if there's an error in the response
if response.Error != nil {
log.Printf("Error: %s\n", response.Error.Message)
return
}
// If the message type is 'website_status', print the website status
if response.MsgType == "website_status" && response.WebsiteStatus != nil {
fmt.Printf("Website Status: %s\n", response.WebsiteStatus.SiteStatus)
}
}
// Function to request website status from the API
func getWebsiteStatus() {
appID := 1089 // Use 1089 for testing or replace with your app ID
wsURL := fmt.Sprintf("wss://ws.derivws.com/websockets/v3?app_id=%d", appID)
// Connect to the WebSocket server
c, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
log.Fatalf("Failed to connect to WebSocket: %v\n", err)
}
defer c.Close()
// Send a request for website status
request := map[string]int{"website_status": 1}
if err := c.WriteJSON(request); err != nil {
log.Fatalf("Failed to send request: %v\n", err)
}
// Wait to receive a message from the WebSocket
_, message, err := c.ReadMessage()
if err != nil {
log.Fatalf("Error reading message: %v\n", err)
}
// Handle the received message
handleWebsiteStatusResponse(message)
// Close the WebSocket connection
c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
}
func main() {
// Call the function to get website status
getWebsiteStatus()
// Sleep for a few seconds to keep the program alive for WebSocket responses
time.Sleep(2 * time.Second)
os.Exit(0)
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
class Program
{
// Define the structure for API response and errors
public class ErrorResponse
{
public string message { get; set; }
}
public class WebsiteStatus
{
public string site_status { get; set; }
}
public class ApiResponse
{
public string msg_type { get; set; }
public WebsiteStatus website_status { get; set; }
public ErrorResponse error { get; set; }
}
// Function to handle the WebSocket response
static void HandleWebsiteStatusResponse(string jsonResponse)
{
// Deserialize the JSON response into the ApiResponse object
var response = JsonSerializer.Deserialize<ApiResponse>(jsonResponse);
// Check for errors in the response
if (response.error != null)
{
Console.WriteLine("Error: " + response.error.message);
return;
}
// If the message type is 'website_status', print the website status
if (response.msg_type == "website_status" && response.website_status != null)
{
Console.WriteLine("Website Status: " + response.website_status.site_status);
}
}
// Function to request website status from the API
static async Task GetWebsiteStatusAsync()
{
int appID = 1089; // Use 1089 for testing or replace with your app ID
string wsUrl = $"wss://ws.derivws.com/websockets/v3?app_id={appID}";
using (ClientWebSocket ws = new ClientWebSocket())
{
Uri serverUri = new Uri(wsUrl);
await ws.ConnectAsync(serverUri, CancellationToken.None);
Console.WriteLine("Connected to WebSocket");
// Send a request for website status
var request = new { website_status = 1 };
string requestJson = JsonSerializer.Serialize(request);
byte[] requestBytes = Encoding.UTF8.GetBytes(requestJson);
await ws.SendAsync(new ArraySegment<byte>(requestBytes), WebSocketMessageType.Text, true, CancellationToken.None);
// Receive the response
var buffer = new byte[1024];
WebSocketReceiveResult result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// Convert the received buffer to string
string jsonResponse = Encoding.UTF8.GetString(buffer, 0, result.Count);
// Handle the received message
HandleWebsiteStatusResponse(jsonResponse);
// Close the WebSocket connection
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
}
}
static async Task Main(string[] args)
{
await GetWebsiteStatusAsync();
}
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libwebsockets.h>
#include <jansson.h> // For JSON parsing
#define EXAMPLE_RX_BUFFER_BYTES (1024)
// WebSocket context and connection info
static struct lws *websocket = NULL;
static struct lws_context *context = NULL;
// Function to handle received messages
static void handle_website_status_response(const char *response) {
json_t *root;
json_error_t error;
// Parse the JSON response
root = json_loads(response, 0, &error);
if (!root) {
printf("Error parsing JSON: %s\n", error.text);
return;
}
// Check if the response contains an error
json_t *error_obj = json_object_get(root, "error");
if (error_obj) {
const char *error_message = json_string_value(json_object_get(error_obj, "message"));
printf("Error: %s\n", error_message);
json_decref(root);
return;
}
// If the message type is "website_status", print the website status
const char *msg_type = json_string_value(json_object_get(root, "msg_type"));
if (strcmp(msg_type, "website_status") == 0) {
json_t *website_status = json_object_get(root, "website_status");
if (website_status) {
const char *site_status = json_string_value(json_object_get(website_status, "site_status"));
printf("Website Status: %s\n", site_status);
}
}
json_decref(root);
}
// WebSocket callback function to handle events
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("WebSocket connection established\n");
// Send a request for website status
char message[128];
sprintf(message, "{\"website_status\": 1}");
lws_write(wsi, (unsigned char *)message, strlen(message), LWS_WRITE_TEXT);
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
// Handle the received message
printf("Received message: %.*s\n", (int)len, (char *)in);
handle_website_status_response((const char *)in);
break;
case LWS_CALLBACK_CLIENT_CLOSED:
printf("WebSocket connection closed\n");
break;
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
printf("WebSocket connection error\n");
break;
default:
break;
}
return 0;
}
// WebSocket protocol structure
static struct lws_protocols protocols[] = {
{
"example-protocol",
callback_websocket,
0,
EXAMPLE_RX_BUFFER_BYTES,
},
{ NULL, NULL, 0, 0 } // Terminator for protocol list
};
int main(void) {
struct lws_context_creation_info context_info;
struct lws_client_connect_info client_info;
int app_id = 1089; // Replace with your app ID
memset(&context_info, 0, sizeof(context_info));
memset(&client_info, 0, sizeof(client_info));
// Set up the WebSocket context
context_info.port = CONTEXT_PORT_NO_LISTEN;
context_info.protocols = protocols;
context = lws_create_context(&context_info);
if (!context) {
fprintf(stderr, "Failed to create WebSocket context\n");
return -1;
}
// Set up the WebSocket connection info
client_info.context = context;
client_info.address = "ws.derivws.com";
client_info.port = 443;
client_info.path = "/websockets/v3";
client_info.host = client_info.address;
client_info.origin = client_info.address;
client_info.protocol = protocols[0].name;
client_info.ssl_connection = LCCSCF_USE_SSL;
client_info.pwsi = &websocket;
char url[256];
snprintf(url, sizeof(url), "/websockets/v3?app_id=%d", app_id);
client_info.path = url;
// Connect to the WebSocket server
websocket = lws_client_connect_via_info(&client_info);
if (!websocket) {
fprintf(stderr, "Failed to establish WebSocket connection\n");
lws_context_destroy(context);
return -1;
}
// Run the WebSocket event loop
while (lws_service(context, 1000) >= 0) {
// This will keep running until the WebSocket closes
}
// Clean up
lws_context_destroy(context);
return 0;
}
Updated 10 days ago