### Go WebSocket Client Setup and Execution Instructions Source: https://developers.deriv.com/docs/websockets Step-by-step instructions for setting up and running the Go WebSocket client, including installing the necessary Gorilla WebSocket package and executing the Go source file from the terminal. ```Shell Instructions: 1. Ensure you have Go installed on your machine. You can download it from https://golang.org/dl/. 2. Install the Gorilla WebSocket package by running: go get github.com/gorilla/websocket 3. Save this code to a file, e.g., websocket_client.go. 4. Open a terminal, navigate to the directory where you saved the file, and run: go run websocket_client.go Note: Replace "app_id=1089" in the URL with your actual app_id if necessary. ``` -------------------------------- ### C# .NET Project Setup and Run Source: https://developers.deriv.com/docs/websockets Instructions for setting up a new .NET console project, moving the C# WebSocket example file into it, adding the necessary `System.Net.WebSockets.Client` NuGet package, and finally running the application from the terminal. ```Bash dotnet new console -o WebSocketExampleApp ``` ```Bash mv WebSocketExample.cs WebSocketExampleApp/WebSocketExample.cs ``` ```Bash cd WebSocketExampleApp ``` ```Bash dotnet add package System.Net.WebSockets.Client --version 4.5.3 ``` ```Bash dotnet run ``` -------------------------------- ### Shell Commands for Deriv API Client Setup and Execution Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol These instructions guide the user through setting up the Python environment (referencing https://www.python.org/downloads/), installing the necessary `deriv_api` package, saving the script, and executing it from the command line to interact with the Deriv WebSocket API. ```Shell pip install deriv_api python contracts_for_symbol_client.py ``` -------------------------------- ### Instructions to Run C# WebSocket Example Source: https://developers.deriv.com/docs/keep-connection-live Step-by-step guide on how to compile and run the provided C# WebSocket client code locally using the .NET SDK, including dependency management and execution commands. ```text 1. Ensure you have .NET SDK installed. You can download it from https://dotnet.microsoft.com/download. 2. Save the code to a file named `WebSocketExample.cs`. 3. Open a terminal in the directory containing `WebSocketExample.cs`. 4. If using the .NET CLI, you can run the code with: - `dotnet new console -o WebSocketExample` (if creating a new project) - Move `WebSocketExample.cs` into the project directory `WebSocketExample`. - Navigate to the project directory: `cd WebSocketExample`. - Run `dotnet add package System.Net.WebSockets.Client` to add the WebSocket client dependency. - Run the code: `dotnet run`. 5. Alternatively, you can use an IDE like Visual Studio to create a console application, add the `System.Net.WebSockets.Client` package, and then run the application. 6. Replace `app_id=1089` in the URL with your actual app_id if needed. ``` -------------------------------- ### Instructions to Run Swift WebSocket Client Source: https://developers.deriv.com/docs/check-website-status A step-by-step guide for setting up and executing the provided Swift WebSocket client code. It covers prerequisites like Swift installation, file creation, terminal navigation, and command-line execution, along with notes on stopping the program and `app_id` replacement. ```text Instructions to run the code: 1. Ensure Swift is installed on your machine. You can use Xcode or install the Swift toolchain from https://swift.org/. 2. Create a new Swift file (e.g., `WebSocketClient.swift`) and paste the code above. 3. Open a terminal and navigate to the directory where the file is saved. 4. Run the code with the following command: swift WebSocketClient.swift 5. The program will connect to the Deriv WebSocket API, request the website status, and print the site's operational status and supported languages. 6. To stop the program, press `Ctrl+C` in the terminal. Note: Replace `app_id` with your actual app_id if required. ``` -------------------------------- ### Install Python Deriv API Library Source: https://developers.deriv.com/docs/keep-connection-live Command to install the `python-deriv-api` library, which is required to run the Python example script for connecting to the Deriv API. ```Shell pip install python-deriv-api ``` -------------------------------- ### Install cpanm (Perl Module Installer) Source: https://developers.deriv.com/docs/websockets If `cpanm` is not already installed, use `cpan` to install `App::cpanminus`. This tool simplifies the installation of other Perl modules. ```Shell cpan App::cpanminus ``` -------------------------------- ### Perl Module Installation and Script Execution Source: https://developers.deriv.com/docs/keep-connection-live These instructions guide the user through installing necessary Perl modules (AnyEvent, AnyEvent::WebSocket::Client, JSON, and App::cpanminus if cpanm is not present) using cpanm and then executing the main Perl script from the command line. They cover the essential prerequisites for running the provided WebSocket client. ```Shell cpanm AnyEvent AnyEvent::WebSocket::Client JSON cpan App::cpanminus perl connect.pl ``` -------------------------------- ### C WebSocket Client Build Instructions Source: https://developers.deriv.com/docs/websockets Provides commands for installing the `libwebsockets` development library on Ubuntu and macOS, followed by the GCC command to compile a C WebSocket client. It also shows how to run the compiled executable, linking necessary libraries like `libwebsockets`, `ssl`, `crypto`, and `m`. ```Bash sudo apt-get install libwebsockets-dev ``` ```Bash brew install libwebsockets ``` ```Bash gcc -o connect connect.c -lwebsockets -lssl -lcrypto -lm ``` ```Bash ./connect ``` -------------------------------- ### Example Deriv OAuth URL with Specific Affiliate Token (Type 2) Source: https://developers.deriv.com/docs/affiliates This example illustrates building the Deriv OAuth URL from another referral link format, where the affiliate token is directly part of the path. It shows how to correctly use this token and a default 'utm_campaign' for tracking. ```JSON https://oauth.deriv.com/oauth2/authorize?app_id=YOUR_APP_ID&affiliate_token=jqd7qq_iBB18zg8lBvFoLmNd7ZgqdRLk&utm_campaign=myaffiliates ``` -------------------------------- ### Go WebSocket Client for Deriv API Source: https://developers.deriv.com/docs/websockets A Go example using the `gorilla/websocket` library to connect to the Deriv WebSocket API. It demonstrates how to establish a connection, send a 'ping' message, and continuously receive messages from the server using a goroutine for concurrent handling. ```Go 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") } ``` -------------------------------- ### Install Required Perl Modules Source: https://developers.deriv.com/docs/websockets Use `cpanm` to install the necessary Perl modules: AnyEvent, AnyEvent::WebSocket::Client, and JSON. These modules are crucial for the script's functionality. ```Shell cpanm AnyEvent AnyEvent::WebSocket::Client JSON ``` -------------------------------- ### Start Copying Trades (Deriv API) Source: https://developers.deriv.com/docs/copy-trading Initiates the process of copying a specific trader's actions. This API call allows a user to become a copier and replicate the trades of a chosen trader. ```APIDOC API Call: copy_start Purpose: Begin copying a trader's actions. Reference: https://api.deriv.com/api-explorer#copy_start ``` -------------------------------- ### Example Deriv OAuth URL with Specific Affiliate Token (Type 1) Source: https://developers.deriv.com/docs/affiliates This example demonstrates constructing the Deriv OAuth URL using an affiliate token extracted from a specific referral link format (sidc parameter). It shows how to correctly embed the 'sidc' value as 'affiliate_token' and the 'utm_campaign'. ```JSON https://oauth.deriv.com/oauth2/authorize?app_id=YOUR_APP_ID&affiliate_token=FB58247C-6B33-4677-A6AD-168C2D72323C&utm_campaign=dynamicworks ``` -------------------------------- ### Copy Trading: Start API Source: https://developers.deriv.com/docs/trading-apis Starts copy trader bets. ```APIDOC API Name: Copy Trading: Start Description: Starts copy trader bets. Send: Yes Subscribe: No Scope: Trade ``` -------------------------------- ### Initiate WebSocket Connection (Python) Source: https://developers.deriv.com/docs/websockets This Python snippet shows the entry point for running an asynchronous WebSocket client using `asyncio.get_event_loop().run_until_complete()`. It's typically used to start a coroutine that handles the WebSocket connection lifecycle. This line assumes a `connect_to_websocket()` coroutine is defined elsewhere. ```python asyncio.get_event_loop().run_until_complete(connect_to_websocket()) ``` -------------------------------- ### Shell Commands for Deriv API Python Client Setup and Execution Source: https://developers.deriv.com/docs/check-website-status These commands provide step-by-step instructions for setting up the Python environment, installing the required `deriv_api` package, and executing the Python script to connect to the Deriv WebSocket API and retrieve website status. ```Shell pip install deriv_api python website_status_client.py ``` -------------------------------- ### Connect to Deriv WebSocket API (Java) Source: https://developers.deriv.com/docs/websockets This Java example demonstrates how to establish a WebSocket connection to the Deriv API using the `Java-WebSocket` library. It includes a complete client implementation with handlers for connection open, incoming string and binary messages, connection close, and errors. It also shows how to send a 'ping' message to the server. ```java 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()); } } } ``` -------------------------------- ### Perl WebSocket Client Setup and Contracts Request Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This Perl script demonstrates how to establish a WebSocket connection using AnyEvent::WebSocket::Client and send a 'contracts_for' request to the Deriv API. It includes setting up the WebSocket URL, initializing the client, and defining a function to send the JSON-encoded request. ```Perl #!/usr/bin/env perl use strict; use warnings; use v5.014; use AnyEvent; use AnyEvent::WebSocket::Client; use JSON; # WebSocket URL and app_id my $app_id = app_id; my $url = "wss://ws.derivws.com/websockets/v3?app_id=$app_id"; # Create WebSocket client and connection my $client = AnyEvent::WebSocket::Client->new; $| = 1; # Flush output immediately for real-time logging # Function to send a contracts for symbol request sub send_contracts_for_symbol { my $connection = shift; my $contracts_for_request = encode_json({ contracts_for => 'R_50', # Symbol for which contracts are requested currency => 'USD', # Set currency to USD landing_company => 'svg', # Landing company (e.g., svg) product_type => 'basic' # Product type is set to 'basic' }); $connection->send($contracts_for_request); say "[request] Contracts for symbol request sent."; } ``` -------------------------------- ### C# WebSocket Client for Deriv API Source: https://developers.deriv.com/docs/websockets A C# example demonstrating how to connect to the Deriv WebSocket API, send a 'ping' message, receive a response, and gracefully close the connection. It utilizes the `System.Net.WebSockets.Client` namespace for WebSocket communication. ```C# 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 bytesToSend = new ArraySegment(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(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); } } } } ``` -------------------------------- ### Example: OAuth URL with Affiliate/UTM from Referral Link (Type 2) Source: https://developers.deriv.com/docs/authentication Illustrates constructing the OAuth URL when the referral link is a tracking URL. Shows how to identify the affiliate token and a default UTM campaign, and integrate them into the OAuth URL. ```URL Referral Link: https://track.deriv.com/_jqd7qq_iBB18zg8lBvFoLmNd7ZgqdRLk/1/ Affiliate Token: jqd7qq_iBB18zg8lBvFoLmNd7ZgqdRLk UTM Campaign: myaffiliates OAuth URL: https://oauth.deriv.com/oauth2/authorize?app_id=YOUR_APP_ID&affiliate_token=jqd7qq_iBB18zg8lBvFoLmNd7ZgqdRLk&utm_campaign=myaffiliates ``` -------------------------------- ### Example: Redirected URL with User Session Tokens Source: https://developers.deriv.com/docs/authentication Illustrates the structure of the URL to which the user is redirected after successful login or signup, containing appended arguments with user session tokens (account ID, token, currency) for multiple accounts. ```URL https://[YOUR_WEBSITE_URL]/redirect/?acct1=cr799393& token1=a1-f7pnteezo4jzhpxclctizt27hyeot&cur1=usd& acct2=vrtc1859315& token2=a1clwe3vfuuus5kraceykdsoqm4snfq& cur2=usd ``` -------------------------------- ### Example: OAuth URL with Affiliate/UTM from Referral Link (Type 1) Source: https://developers.deriv.com/docs/authentication Demonstrates how to construct the OAuth URL when the referral link uses 'sidc' for affiliate token and 'utm_campaign' directly. Shows extraction of 'sidc' and 'utm_campaign' values and their integration into the OAuth URL. ```URL Referral Link: https://deriv.com/signup?sidc=FB58247C-6B33-4677-A6AD-168C2D72323C&utm_campaign=dynamicworks&utm_medium=affiliate&utm_source=CU00001 Affiliate Token (sidc): FB58247C-6B33-4677-A6AD-168C2D72323C UTM Campaign: dynamicworks OAuth URL: https://oauth.deriv.com/oauth2/authorize?app_id=YOUR_APP_ID&affiliate_token=FB58247C-6B33-4677-A6AD-168C2D72323C&utm_campaign=dynamicworks ``` -------------------------------- ### Initialize and Run libwebsockets Client in C Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This C `main` function initializes the `libwebsockets` context and client connection information. It sets up the framework for a WebSocket client application, including handling graceful shutdown via Ctrl+C. This function is the entry point for the client application. ```C int main(int argc, const char **argv) { struct lws_context_creation_info info; struct lws_client_connect_info i; // Handle Ctrl+C interrupt for graceful shutdown } ``` -------------------------------- ### Go WebSocket Client for Deriv API - Full Example Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol A complete Go program demonstrating how to establish a WebSocket connection to the Deriv API, send a `contracts_for` request, and continuously read and process incoming JSON responses. It covers connection management, request serialization, and structured response handling. ```Go package main import ( "context" "fmt" "log" "time" "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" ) const ( webSocketURL = "wss://ws.derivws.com/websockets/v3?app_id=app_id"//replace with your app_id readLimit = 65536 // Set a higher read limit, e.g., 64 KB ) type ContractsForRequest struct { ContractsFor string `json:"contracts_for"` Currency string `json:"currency"` LandingCompany string `json:"landing_company"` ProductType string `json:"product_type"` } func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Establish WebSocket connection conn, _, err := websocket.Dial(ctx, webSocketURL, nil) if err != nil { log.Fatalf("Failed to connect to WebSocket: %v", err) } defer conn.Close(websocket.StatusNormalClosure, "normal closure") fmt.Println("[status] WebSocket connection established.") // Set a higher read limit conn.SetReadLimit(readLimit) // Send contracts for symbol request err = sendContractsForSymbolRequest(ctx, conn) if err != nil { log.Fatalf("Failed to send contracts for symbol request: %v", err) } // Handle incoming messages handleResponses(ctx, conn) } func sendContractsForSymbolRequest(ctx context.Context, conn *websocket.Conn) error { contractsRequest := ContractsForRequest{ ContractsFor: "R_50", Currency: "USD", LandingCompany: "svg", ProductType: "basic", } fmt.Println("[request] Sending contracts for symbol request...") return wsjson.Write(ctx, conn, contractsRequest) } func handleResponses(ctx context.Context, conn *websocket.Conn) { for { var response map[string]interface{} err := wsjson.Read(ctx, conn, &response) if err != nil { log.Fatalf("Error reading message: %v", err) } msgType := response["msg_type"] if msgType == "contracts_for" { contracts := response["contracts_for"].(map[string]interface{})["available"].([]interface{}) fmt.Println("Contracts for Symbol (R_50):") for _, contract := range contracts { contractMap := contract.(map[string]interface{}) fmt.Printf(" - Contract Type: %v\n", contractMap["contract_type"]) fmt.Printf(" - Display Name: %v\n", contractMap["contract_display"]) fmt.Printf(" - Category: %v\n", contractMap["contract_category_display"]) fmt.Printf(" - Market: %v\n", contractMap["market"]) fmt.Printf(" - Submarket: %v\n", contractMap["submarket"]) fmt.Printf(" - Expiry Type: %v\n", contractMap["expiry_type"]) ``` -------------------------------- ### C WebSocket Client Initialization and Connection Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This C code snippet demonstrates how to initialize a libwebsockets context, connect to the Deriv WebSocket API, and manage the event loop. It uses `libwebsockets` for WebSocket communication. The example sets up signal handling for graceful termination and handles connection errors. Dependencies include `libwebsockets`, `jansson`, `ssl`, and `crypto`. ```C signal(SIGINT, sigint_handler); memset(&info, 0, sizeof info); memset(&i, 0, sizeof(i)); lwsl_user("Initializing Deriv WebSocket client...\n"); info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; info.fd_limit_per_thread = 1 + 1 + 1; context = lws_create_context(&info); if (!context) { lwsl_err("lws init failed\n"); return 1; } i.context = context; i.port = port; i.address = server_address; i.path = path; i.host = i.address; i.origin = i.address; i.ssl_connection = ssl_connection; i.protocol = pro; i.local_protocol_name = "lws-minimal-client"; if (!lws_client_connect_via_info(&i)) { lwsl_err("Failed to initiate connection\n"); return 1; } // Run the WebSocket client event loop while (!interrupted) lws_service(context, 0); lws_context_destroy(context); lwsl_user("WebSocket client terminated.\n"); return 0; } ``` ```bash sudo apt-get install libwebsockets-dev libjansson-dev ``` ```bash brew install libwebsockets jansson ``` ```bash gcc -o connect connect.c -lwebsockets -ljansson -lssl -lcrypto -lm ``` ```bash ./connect ``` -------------------------------- ### WebSocket Client Implementation for Data Subscription and Message Handling Source: https://developers.deriv.com/docs/keep-connection-live These code snippets demonstrate how to implement a WebSocket client in different programming languages to connect to a WebSocket API, send subscription requests (e.g., for proposals), receive and parse incoming JSON messages (including proposals, pings, and errors), and manage the connection lifecycle. Each example includes language-specific setup and dependency instructions within the provided text. ```Rust let receive_socket = Arc::clone(&socket); let receive_task = spawn(async move { let mut socket = receive_socket.lock().await; while let Some(Ok(msg)) = socket.next().await { match msg { Message::Text(text) => { let data: serde_json::Value = serde_json::from_str(&text).unwrap_or_else(|_| json!({})); if let Some(proposal) = data.get("proposal") { println!("Details: {}", proposal["longcode"]); println!("Ask Price: {}", proposal["display_value"]); println!("Payout: {}", proposal["payout"]); println!("Spot: {}", proposal["spot"]); } else if data.get("msg_type").unwrap_or(&json!("")) == "ping" { println!("[Ping] Ping response received."); } else if let Some(error) = data.get("error") { println!("[Error] {}", error["message"]); } } _ => {} } } }); // Await all tasks to complete let _ = tokio::try_join!(ping_task, send_task, receive_task); // Close the WebSocket connection let mut socket = socket.lock().await; socket.close(None).await.expect("Failed to close connection"); println!("[close] Connection closed."); } ``` ```PHP 1, "subscribe" => 1, "amount" => 10, "basis" => "payout", "contract_type" => "CALL", "currency" => "USD", "duration" => 1, "duration_unit" => "m", "symbol" => "R_100", "barrier" => "+0.1" ]); $client->send($proposal_request); echo "[sent] Proposal subscription sent.\n"; // Ping function to keep connection alive $ping_interval = 30; // in seconds $last_ping_time = time(); // Main loop to handle responses and send ping messages while (true) { // Check if it's time to send a ping if (time() - $last_ping_time >= $ping_interval) { $client->send(json_encode(["ping" => 1])); echo "[ping] Ping sent to keep connection alive.\n"; $last_ping_time = time(); } // Receive response from WebSocket $response = $client->receive(); $data = json_decode($response, true); if (isset($data["error"])) { echo "[error] " . $data["error"]["message"] . "\n"; break; } elseif ($data["msg_type"] === "proposal") { $proposal = $data["proposal"]; echo "[proposal] Details: {$proposal['longcode']}\n"; echo "[proposal] Ask Price: {$proposal['display_value']}\n"; echo "[proposal] Payout: {$proposal['payout']}\n"; echo "[proposal] Spot: {$proposal['spot']}\n"; } elseif ($data["msg_type"] === "ping") { echo "[ping] Ping response received.\n"; } // Sleep briefly to prevent continuous loop usleep(500000); // 500ms } // Close the WebSocket connection $client->close(); echo "[close] WebSocket connection closed.\n"; } catch (Exception $e) { echo "[error] " . $e->getMessage() . "\n"; } ``` ```Go package main import ( "context" "fmt" "log" "time" "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" ) // Define constants const ( ``` -------------------------------- ### Establish WebSocket Connection (Swift) Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This Swift snippet shows how to initiate a WebSocket connection to the Deriv API using `URLSessionWebSocketTask`. It defines a global variable `webSocketTask` to maintain the connection and a function `connectWebSocket` to set up the URL, create a `URLRequest`, and resume the WebSocket task. This provides a foundational setup for further WebSocket interactions. ```Swift import Foundation // Make webSocketTask a global variable to keep the connection open var webSocketTask: URLSessionWebSocketTask? // 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) // Initialize webSocketTask with URLSession webSocketTask = URLSession.shared.webSocketTask(with: request) // Start the WebSocket connection webSocketTask?.resume() } ``` -------------------------------- ### Start WebSocket Signal Processing in JavaScript Source: https://developers.deriv.com/docs/keep-connection-live The `checkSignal()` function initiates the WebSocket signal processing. It calls `proposal()` to subscribe to market data, `ping()` to start sending ping messages, and sets up an event listener on the `connection` object to process incoming messages using the `wsResponse()` function. ```JavaScript const checkSignal = () => { proposal(); ping(); connection.addEventListener('message', wsResponse); }; ``` -------------------------------- ### C libwebsockets Client Initialization Source: https://developers.deriv.com/docs/keep-connection-live Basic setup for a WebSocket client using the `libwebsockets` library in C. It defines context, connection parameters like server address, port, SSL usage, and path with app ID. ```C #include #include #include #include // Set up WebSocket context and connection details static struct lws_context *context; static int interrupted = 0, port = 443, ssl_connection = LCCSCF_USE_SSL; static const char *server_address = "ws.derivws.com"; static const char *path = "/websockets/v3?app_id=app_id";//replace with your app_id static const char *pro = "lws-minimal-client"; ``` -------------------------------- ### Establish and Manage WebSocket Connection Source: https://developers.deriv.com/docs/websockets This code snippet demonstrates how to establish a WebSocket connection to a server, send messages (e.g., a ping), receive responses, and handle connection events such as opening, closing, and errors. It illustrates the fundamental steps for interactive communication over WebSockets, including resource cleanup. ```JavaScript 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 { 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 }; /* Instructions to run this code: 1. Ensure Node.js is installed on your machine. You can download it from https://nodejs.org/. 2. Install the `ws` WebSocket library by running: npm install ws 3. Save this code to a file, e.g., `websocket_client.js`. 4. Open a terminal and navigate to the directory where you saved the file. 5. Run the code using the following command: node websocket_client.js Ensure that the `app_id` in the URL is replaced with your own if needed. */ ``` ```Python import asyncio import websockets import json async def connect_to_websocket(): app_id = app_id # Replace with your app_id 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 ``` -------------------------------- ### Java WebSocket Initial Request and Ping Setup Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This Java code snippet demonstrates how to send an initial 'contracts_for' request to the Deriv WebSocket API and set up a recurring ping message to keep the connection alive. This is typically placed within the 'onOpen' callback of a WebSocket client. ```Java contractsForSymbolRequest.addProperty("currency", "USD"); contractsForSymbolRequest.addProperty("landing_company", "svg"); contractsForSymbolRequest.addProperty("product_type", "basic"); send(contractsForSymbolRequest.toString()); System.out.println("[sent] Contracts for symbol request sent"); // Schedule a ping every 30 seconds Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { JsonObject pingMessage = new JsonObject(); pingMessage.addProperty("ping", 1); send(pingMessage.toString()); System.out.println("[ping] Ping sent to keep connection alive"); } }, 0, 30000); ``` -------------------------------- ### Handle WebSocket OnOpen Event (JavaScript) Source: https://developers.deriv.com/docs/websockets Demonstrates setting up an `onopen` event listener for a WebSocket. It logs connection establishment and sends an initial 'ping' message to the server once the connection is ready. The `readyState` becomes `1`. ```JavaScript socket.onopen = function (e) { console.log('[open] Connection established'); console.log('Sending to server'); const sendMessage = JSON.stringify({ ping: 1 }); socket.send(sendMessage); }; ``` -------------------------------- ### Swift WebSocket Client Message Handling and Connection Management Source: https://developers.deriv.com/docs/websockets This Swift code snippet demonstrates handling incoming WebSocket messages, managing the connection lifecycle (receiving, closing), and keeping the application running. It includes a `closeWebSocketConnection` function for graceful shutdown and an example of scheduled connection closure. ```Swift 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() } // Function to close the WebSocket connection func closeWebSocketConnection() { // Use this function when you need to close the connection webSocketTask?.cancel(with: .normalClosure, reason: nil) print("[close] Connection closed cleanly") } // Call the function to connect to the WebSocket connectWebSocket() // Example usage: Call closeWebSocketConnection() to close the connection when needed // The following line will close the connection after 10 seconds for demonstration purposes DispatchQueue.main.asyncAfter(deadline: .now() + 10) { closeWebSocketConnection() } // Keep the program running to wait for messages RunLoop.main.run() ``` -------------------------------- ### Maven Dependencies for Java WebSocket Client Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This XML snippet provides the necessary Maven dependencies for integrating WebSocket functionality (java-websocket) and JSON parsing (gson) into a Java project. These dependencies are crucial for building and running the WebSocket client example. ```XML org.java-websocket Java-WebSocket 1.5.2 com.google.code.gson gson 2.8.8 ``` -------------------------------- ### Trading Flow for High-Close Lookback Contracts Source: https://developers.deriv.com/docs/lookbacks Step-by-step guide to trading High-Close lookback contracts using the Deriv API, from authorization to contract monitoring and early closure. This flow outlines the sequence of API calls required for a complete trading lifecycle. ```APIDOC Trading Flow for High-Close Lookback Contracts: 1. Authorize: API: authorize Purpose: Authenticate user with a token. Requirements: Token with trading scope enabled. 2. Fetch Available Instruments: API: active_symbols Purpose: Retrieve a list of all tradable instruments offered on Deriv. 3. Get Contract Details: API: contracts_for Purpose: Obtain a list of contracts available for a specific instrument. 4. Request a Price (Proposal): API: proposal Purpose: Get a quote for a potential trade. Parameters: contract_type: "LBFLOATPUT" (for High-Close Lookback) multiplier: 1 (example value) Returns: proposal ID 5. Buy the Contract: API: buy Purpose: Execute the trade. Parameters: proposal_id: ID obtained from proposal API response. Returns: unique contract_id 6. Monitor the Contract Status: API: proposal_open_contract Purpose: Check the progress or outcome of an open contract. Parameters: contract_id: ID obtained from buy API response. 7. Close the Contract Early: API: sell Purpose: Exit the contract before expiration. Parameters: contract_id: ID of the contract to sell. ``` -------------------------------- ### Swift WebSocket: Connection Initialization and Lifecycle Management Source: https://developers.deriv.com/docs/keep-connection-live This Swift code snippet demonstrates how to initiate the WebSocket connection, start sending a proposal subscription, begin periodic pings, and set up continuous message reception. It also includes a function to cleanly close the WebSocket connection and keeps the application running using `RunLoop.main.run()`. ```Swift // Start sending the proposal subscription and pinging the server sendProposalSubscription() startPing() receiveMessage() // Function to close the WebSocket connection func closeWebSocketConnection() { webSocketTask?.cancel(with: .normalClosure, reason: nil) print("[close] Connection closed cleanly") } // Start WebSocket connection connectWebSocket() // Keep the program running to wait for messages RunLoop.main.run() ``` -------------------------------- ### Create Deriv Demo Account Source: https://developers.deriv.com/docs/create-account-using-api Creates a virtual demo account on Deriv with a starting balance of USD 10,000. This API call requires the user's residence (2-letter country code) and the verification code received from the `verify_email` call. ```APIDOC Endpoint: new_account_virtual Parameters: residence: "string" (2-letter country code, e.g., 'US', 'GB'. Obtain from residence_list API call or documentation.) verification_code: "string" (Code received from verify_email call) ``` -------------------------------- ### Establish and Maintain Deriv WebSocket API Connection Source: https://developers.deriv.com/docs/websockets This collection of code snippets demonstrates how to connect to the Deriv WebSocket API, send a 'ping' message to keep the connection alive, and receive responses. Examples are provided in PHP, Rust, and Swift, showcasing different language-specific WebSocket client implementations. ```PHP send(json_encode(["ping" => 1])); echo "[debug] Message sent: {\"ping\":1}\n"; // Receive a response from the server $response = $client->receive(); echo "[message] Received from WebSocket: '$response'\n"; // Close the connection $client->close(); echo "[close] Connection closed\n"; } catch (\WebSocket\ConnectionException $e) { echo "[error] Connection error: " . $e->getMessage() . "\n"; } catch (Exception $e) { echo "[error] General error: " . $e->getMessage() . "\n"; } ``` ```Rust use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::protocol::Message; use futures_util::{SinkExt, StreamExt}; use tokio; use url::Url; #[tokio::main] async fn main() { let app_id = app_id;//Replace with your app_id let url = format!("wss://ws.derivws.com/websockets/v3?app_id={}", app_id); let url = Url::parse(&url).expect("Invalid URL"); // Connect to the WebSocket server let (mut socket, _response) = connect_async(url).await.expect("Failed to connect"); println!("[open] Connection established"); // Prepare the ping message let send_message = r#"{\"ping\": 1}"#; socket.send(Message::Text(send_message.into())).await.expect("Failed to send message"); println!("Message sent to server"); // Receive a message from the server if let Some(Ok(msg)) = socket.next().await { println!("[message] Data received from server: {:?}", msg); } // Close the connection socket.close(None).await.expect("Failed to close connection"); println!("[close] Connection closed cleanly"); } ``` ```Swift import Foundation // Make webSocketTask a global variable to keep the connection open var webSocketTask: URLSessionWebSocketTask? // 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); // Initialize webSocketTask with URLSession 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 func 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 initially 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): ``` -------------------------------- ### Perl: Connect to WebSocket and Fetch Contracts for Symbol Source: https://developers.deriv.com/docs/get-contracts-for-a-symbol This Perl script connects to a WebSocket endpoint, sends a `contracts_for` request for a specific symbol (R_50), and then parses and prints the details of available contracts. It includes error handling for connection issues, JSON decoding, and API-specific errors, as well as a timeout mechanism for responses. To run this script, ensure Perl is installed, then install required modules (`AnyEvent`, `AnyEvent::WebSocket::Client`, `JSON`) using `cpanm`, save the script, and execute it via `perl your_script_name.pl`. ```Perl $client->connect($url)->cb(sub { my $connection = eval { shift->recv }; if (!$connection) { die "Connection error: $@"; } say "[status] WebSocket connection established."; # Send the contracts for symbol request send_contracts_for_symbol($connection); # Set a timeout for receiving a response my $timeout = AnyEvent->timer( after => 10, cb => sub { say "[error] No response received within 10 seconds. Closing connection."; $connection->close; } ); # Handle incoming messages $connection->on(each_message => sub { my ($connection, $message) = @_; # Cancel timeout upon receiving a message undef $timeout; my $data = eval { decode_json($message->body) }; if ($@) { say "[error] Failed to decode JSON: $@"; return; } # Handle errors if ($data->{error}) { say "[error] " . $data->{error}{message}; $connection->close; return; } # Process contracts_for response if ($data->{msg_type} && $data->{msg_type} eq 'contracts_for') { say "[contracts] Contracts for Symbol (R_50):"; foreach my $contract (@{$data->{contracts_for}{available}}) { my $contract_type = $contract->{contract_type} // "N/A"; my $contract_display = $contract->{contract_display} // "N/A"; my $contract_category_display = $contract->{contract_category_display} // "N/A"; my $market = $contract->{market} // "N/A"; my $submarket = $contract->{submarket} // "N/A"; my $expiry_type = $contract->{expiry_type} // "N/A"; my $min_duration = $contract->{min_contract_duration} // "N/A"; my $max_duration = $contract->{max_contract_duration} // "N/A"; my $barrier = $contract->{barrier} // "N/A"; my $sentiment = $contract->{sentiment} // "N/A"; # Print contract details say " - Contract Type: $contract_type"; say " - Display Name: $contract_display"; say " - Category: $contract_category_display"; say " - Market: $market"; say " - Submarket: $submarket"; say " - Expiry Type: $expiry_type"; say " - Min Duration: $min_duration"; say " - Max Duration: $max_duration"; say " - Barrier: $barrier"; say " - Sentiment: $sentiment"; say " --------------------"; } say "[contracts] End of Contracts Response."; $connection->close; # Close connection after processing the response } }); # Handle connection close $connection->on(finish => sub { say "[status] WebSocket connection closed."; }); }); # Start the AnyEvent event loop AnyEvent->condvar->recv; ``` -------------------------------- ### Run the Perl Script Source: https://developers.deriv.com/docs/websockets Execute the Perl script, assumed to be saved as `connect.pl`, from the command line using the Perl interpreter. Ensure all dependencies are met before running. ```Shell perl connect.pl ``` -------------------------------- ### C WebSocket Client Main Function and Protocol Setup Source: https://developers.deriv.com/docs/check-website-status This C code defines the WebSocket protocols and the `main` function responsible for initializing the libwebsockets context, setting up client connection information, handling graceful shutdown, and running the event loop for a Deriv API WebSocket client. ```C static const struct lws_protocols protocols[] = { { "lws-minimal-client", callback_minimal, 0, 0, 0, NULL, 0 }, LWS_PROTOCOL_LIST_TERM }; // Main function to set up and manage the WebSocket client int main(int argc, const char **argv) { struct lws_context_creation_info info; struct lws_client_connect_info i; // Handle Ctrl+C interrupt for graceful shutdown signal(SIGINT, sigint_handler); memset(&info, 0, sizeof info); memset(&i, 0, sizeof(i)); lwsl_user("Initializing Deriv WebSocket client...\n"); info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; info.fd_limit_per_thread = 1 + 1 + 1; context = lws_create_context(&info); if (!context) { lwsl_err("lws init failed\n"); return 1; } i.context = context; i.port = port; i.address = server_address; i.path = path; i.host = i.address; i.origin = i.address; i.ssl_connection = ssl_connection; i.protocol = pro; i.local_protocol_name = "lws-minimal-client"; if (!lws_client_connect_via_info(&i)) { lwsl_err("Failed to initiate connection\n"); return 1; } // Run the WebSocket client event loop while (!interrupted) lws_service(context, 0); lws_context_destroy(context); lwsl_user("WebSocket client terminated.\n"); return 0; } ```