Get contracts for a symbol
Follow these steps to retrieve the list of available contracts, along with the latest barrier and duration limits for each contract, for a given symbol using the Deriv API:
- Import Deriv API: Import the
DerivAPIBasic
library from Skypack CDN. - WebSocket connection: Create a WebSocket connection to the Deriv API using your
app_id
. - API initialization: Initialize the
DerivAPIBasic
instance with the WebSocket connection. - Request object: Define a request object to fetch contracts for a specific symbol (e.g.,
R_50
). - Response handling: Handle the API response:
- Parse the data and log any errors.
- If the response contains contract data, log it.
- Remove the event listener after the response is received.
- Trigger request: On a button click, the function sends the request to the API to get the contracts for the symbol.
// Import the Deriv API Basic module from Skypack CDN
import DerivAPIBasic from 'https://cdn.skypack.dev/@deriv/deriv-api/dist/DerivAPIBasic';
// Define your app_id (replace 'app_id' with your actual app ID)
const app_id = app_id;
// Establish a WebSocket connection to the Deriv API using the app_id
const connection = new WebSocket(`wss://ws.derivws.com/websockets/v3?app_id=${app_id}`);
// Initialize the DerivAPIBasic object with the connection
const api = new DerivAPIBasic({ connection });
// Define the request object for getting contracts for a specific symbol (R_50 in this case)
const contracts_for_symbol_request = {
contracts_for: 'R_50', // Symbol for which contracts are requested
currency: 'USD', // Set currency to USD
landing_company: 'svg', // Landing company (svg in this case)
product_type: 'basic', // Product type is set to 'basic'
};
// Function to handle the response from the API
const contractsForSymbolResponse = async (res) => {
// Parse the WebSocket message data
const data = JSON.parse(res.data);
// Check for errors in the response
if (data.error !== undefined) {
console.log('Error : ', data.error?.message); // Log the error message
connection.removeEventListener('message', contractsForSymbolResponse, false); // Remove the message listener
await api.disconnect(); // Disconnect from the API if there is an error
}
// If the response contains contract information for the symbol
if (data.msg_type === 'contracts_for') {
console.log(data.contracts_for); // Log the contracts information
}
// Remove the event listener after the response is received
connection.removeEventListener('message', contractsForSymbolResponse, false);
};
// Function to request contracts for the symbol
const getContractsForSymbol = async () => {
connection.addEventListener('message', contractsForSymbolResponse); // Add the event listener for the API response
await api.contractsFor(contracts_for_symbol_request); // Send the contracts request to the API
};
// Get the HTML button element with id 'contractsForSymbol'
const symbol_button = document.querySelector('#contractsForSymbol');
// Add a click event listener to the button that triggers the getContractsForSymbol function
symbol_button.addEventListener('click', getContractsForSymbol);
// Import necessary packages
import java.net.URI;
import javax.websocket.*;
import java.io.IOException;
import org.json.JSONObject;
// Define WebSocket client for connecting to the Deriv API
@ClientEndpoint
public class DerivAPIClient {
// WebSocket session object to manage connection
private Session session;
// Method to connect to the WebSocket server
public void connect(String app_id) {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
// Establish connection to the Deriv WebSocket API
container.connectToServer(this, new URI("wss://ws.derivws.com/websockets/v3?app_id=" + app_id));
} catch (Exception e) {
e.printStackTrace();
}
}
// Called when the connection is established
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
this.session = session;
// Prepare the request object for contracts_for API call
JSONObject contractsForSymbolRequest = new JSONObject();
contractsForSymbolRequest.put("contracts_for", "R_50");
contractsForSymbolRequest.put("currency", "USD");
contractsForSymbolRequest.put("landing_company", "svg");
contractsForSymbolRequest.put("product_type", "basic");
// Send the request to the WebSocket server
try {
session.getBasicRemote().sendText(contractsForSymbolRequest.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
// Called when a message is received from the server
@OnMessage
public void onMessage(String message) {
JSONObject data = new JSONObject(message);
// Check if there is an error in the response
if (data.has("error")) {
System.out.println("Error: " + data.getJSONObject("error").getString("message"));
try {
session.close(); // Close the connection on error
} catch (IOException e) {
e.printStackTrace();
}
}
// Check if the message type is 'contracts_for'
if (data.getString("msg_type").equals("contracts_for")) {
System.out.println(data.getJSONArray("contracts_for"));
}
}
// Called when the connection is closed
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Session closed: " + closeReason);
}
// Main method to start the WebSocket client
public static void main(String[] args) {
DerivAPIClient client = new DerivAPIClient();
String app_id = "your_app_id"; // Replace with your actual app_id
client.connect(app_id);
}
}
#!/usr/bin/perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::WebSocket::Client;
use JSON;
# Define app_id (Replace with your actual app_id)
my $app_id = 'your_app_id';
# Create a WebSocket client instance
my $client = AnyEvent::WebSocket::Client->new;
# Define the request to get contracts for a specific symbol (R_50)
my $contracts_for_symbol_request = {
contracts_for => 'R_50',
currency => 'USD',
landing_company => 'svg',
product_type => 'basic',
};
# Connect to the Deriv WebSocket API
$client->connect("wss://ws.derivws.com/websockets/v3?app_id=$app_id")->cb(sub {
my $connection = eval { shift->recv };
# Check if connection was successful
if (!$connection) {
die "Failed to connect to the WebSocket server: $@";
}
print "Connected to WebSocket server\n";
# Send the contracts_for request to the WebSocket API
$connection->send(encode_json($contracts_for_symbol_request));
# Handle messages received from the server
$connection->on(each_message => sub {
my ($connection, $message) = @_;
# Decode the received JSON message
my $data = decode_json($message->body);
# Check for errors in the response
if (exists $data->{error}) {
print "Error: ", $data->{error}->{message}, "\n";
$connection->close;
}
# If the response is for 'contracts_for', print the contract information
if ($data->{msg_type} && $data->{msg_type} eq 'contracts_for') {
print "Contracts: ", encode_json($data->{contracts_for}), "\n";
}
});
# Handle the closing of the WebSocket connection
$connection->on(finish => sub {
print "Connection closed\n";
});
});
# Start the event loop to keep the connection alive
AnyEvent->condvar->recv;
<?php
// Include necessary libraries (you may need to install Ratchet via Composer)
require 'vendor/autoload.php';
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory as LoopFactory;
use React\Socket\Connector as ReactConnector;
// Define the app_id (replace 'your_app_id' with your actual app_id)
$app_id = 'your_app_id';
// Create an event loop to handle WebSocket events
$loop = LoopFactory::create();
$reactConnector = new ReactConnector($loop);
$connector = new Connector($loop, $reactConnector);
// Define the request object for contracts_for API call
$contracts_for_symbol_request = [
'contracts_for' => 'R_50', // Symbol for which contracts are requested
'currency' => 'USD', // Set currency to USD
'landing_company' => 'svg', // Landing company
'product_type' => 'basic', // Product type is set to 'basic'
];
// Connect to the Deriv WebSocket API
$connector("wss://ws.derivws.com/websockets/v3?app_id=$app_id")
->then(function(WebSocket $conn) use ($contracts_for_symbol_request, $loop) {
// Send the contracts_for request to the WebSocket server
$conn->send(json_encode($contracts_for_symbol_request));
echo "Request sent: " . json_encode($contracts_for_symbol_request) . PHP_EOL;
// Handle messages received from the server
$conn->on('message', function($message) use ($conn, $loop) {
// Decode the received message (JSON format)
$data = json_decode($message, true);
// Check if there is an error in the response
if (isset($data['error'])) {
echo "Error: " . $data['error']['message'] . PHP_EOL;
$conn->close();
$loop->stop(); // Stop the event loop
}
// If the response is for 'contracts_for', print the contract information
if (isset($data['msg_type']) && $data['msg_type'] === 'contracts_for') {
echo "Contracts for symbol: " . json_encode($data['contracts_for'], JSON_PRETTY_PRINT) . PHP_EOL;
$conn->close(); // Close the WebSocket connection
$loop->stop(); // Stop the event loop
}
});
// Handle WebSocket connection closing
$conn->on('close', function($code = null, $reason = null) use ($loop) {
echo "Connection closed ({$code} - {$reason})" . PHP_EOL;
$loop->stop(); // Stop the event loop when the connection is closed
});
}, function($e) use ($loop) {
// Handle connection errors
echo "Could not connect: {$e->getMessage()}" . PHP_EOL;
$loop->stop();
});
// Run the event loop to keep the connection alive
$loop->run();
# Import necessary libraries
import asyncio
import websockets
import json
# Define the app_id (replace with your actual app_id)
app_id = "your_app_id"
# Define the request object for 'contracts_for' API call
contracts_for_symbol_request = {
"contracts_for": "R_50", # Symbol for which contracts are requested
"currency": "USD", # Set currency to USD
"landing_company": "svg", # Landing company (svg)
"product_type": "basic" # Product type set to 'basic'
}
# Define a function to handle WebSocket communication
async def get_contracts_for_symbol():
# Connect to the Deriv WebSocket API
async with websockets.connect(f"wss://ws.derivws.com/websockets/v3?app_id={app_id}") as websocket:
# Send the 'contracts_for' request to the WebSocket API
await websocket.send(json.dumps(contracts_for_symbol_request))
print(f"Sent request: {contracts_for_symbol_request}")
# Continuously listen for messages from the server
while True:
# Receive response from the server
response = await websocket.recv()
data = json.loads(response)
# Check if there is an error in the response
if "error" in data:
print(f"Error: {data['error']['message']}")
break
# If the response contains 'contracts_for', print the data
if data.get("msg_type") == "contracts_for":
print("Contracts for symbol:", json.dumps(data["contracts_for"], indent=2))
# Once the contracts data is received, break the loop
break
# Main function to start the WebSocket client
async def main():
await get_contracts_for_symbol()
# Run the WebSocket client asynchronously
asyncio.run(main())
// Import necessary libraries
use futures_util::{StreamExt, SinkExt};
use serde_json::{json, Value};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use tokio::runtime::Runtime;
use url::Url;
// Define the app_id (replace 'your_app_id' with your actual app_id)
const APP_ID: &str = "your_app_id";
// Define the request object for 'contracts_for' API call
fn get_contracts_for_symbol_request() -> Value {
json!({
"contracts_for": "R_50", // Symbol for which contracts are requested
"currency": "USD", // Set currency to USD
"landing_company": "svg", // Landing company
"product_type": "basic" // Product type set to 'basic'
})
}
// Asynchronous function to handle WebSocket communication
async fn get_contracts_for_symbol() {
// Create the WebSocket URL using the provided app_id
let url = format!("wss://ws.derivws.com/websockets/v3?app_id={}", APP_ID);
let url = Url::parse(&url).expect("Invalid URL");
// Establish a WebSocket connection
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
println!("Connected to WebSocket server");
let (mut write, mut read) = ws_stream.split();
// Send the contracts_for request to the WebSocket API
let request = get_contracts_for_symbol_request();
write.send(Message::Text(request.to_string())).await.expect("Failed to send request");
println!("Sent request: {}", request);
// Continuously listen for messages from the server
while let Some(message) = read.next().await {
match message {
Ok(Message::Text(response)) => {
// Parse the response into a JSON object
let data: Value = serde_json::from_str(&response).expect("Invalid JSON");
// Check if there is an error in the response
if let Some(error) = data.get("error") {
println!("Error: {}", error["message"]);
break;
}
// If the response is for 'contracts_for', print the contract information
if data.get("msg_type") == Some(&Value::String("contracts_for".to_string())) {
println!("Contracts for symbol: {}", serde_json::to_string_pretty(&data["contracts_for"]).unwrap());
break;
}
}
Ok(_) => continue, // Ignore non-text messages
Err(e) => {
println!("Error receiving message: {}", e);
break;
}
}
}
}
fn main() {
// Create a Tokio runtime to handle the asynchronous operations
let rt = Runtime::new().unwrap();
rt.block_on(get_contracts_for_symbol());
}
import Foundation
// Define the app_id (replace 'your_app_id' with your actual app_id)
let app_id = "your_app_id"
// Define the request object for 'contracts_for' API call
let contractsForSymbolRequest: [String: Any] = [
"contracts_for": "R_50", // Symbol for which contracts are requested
"currency": "USD", // Set currency to USD
"landing_company": "svg", // Landing company
"product_type": "basic" // Product type set to 'basic'
]
// Function to send and receive WebSocket messages
func getContractsForSymbol() {
// Create the WebSocket URL
let urlString = "wss://ws.derivws.com/websockets/v3?app_id=\(app_id)"
guard let url = URL(string: urlString) else {
print("Invalid URL")
return
}
// Create a URLSession and WebSocket task
let session = URLSession(configuration: .default)
let webSocketTask = session.webSocketTask(with: url)
// Function to send the request message
func sendRequest() {
do {
// Convert the request dictionary to JSON data
let jsonData = try JSONSerialization.data(withJSONObject: contractsForSymbolRequest, options: [])
if let jsonString = String(data: jsonData, encoding: .utf8) {
// Create the WebSocket message
let message = URLSessionWebSocketTask.Message.string(jsonString)
print("Sending request: \(jsonString)")
// Send the request message
webSocketTask.send(message) { error in
if let error = error {
print("Error sending message: \(error)")
}
}
}
} catch {
print("Failed to serialize JSON: \(error)")
}
}
// Function to receive and handle WebSocket messages
func receiveResponse() {
webSocketTask.receive { result in
switch result {
case .failure(let error):
print("Error receiving message: \(error)")
case .success(let message):
switch message {
case .string(let text):
print("Received message: \(text)")
// Try to parse the received message as JSON
if let data = text.data(using: .utf8) {
do {
if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// Check for errors in the response
if let error = jsonResponse["error"] as? [String: Any],
let errorMessage = error["message"] as? String {
print("Error: \(errorMessage)")
}
// If the response contains 'contracts_for', print the contract information
if let msgType = jsonResponse["msg_type"] as? String, msgType == "contracts_for" {
if let contractsFor = jsonResponse["contracts_for"] {
print("Contracts for symbol: \(contractsFor)")
}
}
}
} catch {
print("Failed to parse JSON response: \(error)")
}
}
default:
print("Received non-text message")
}
// Continue receiving messages
receiveResponse()
}
}
}
// Start the WebSocket task
webSocketTask.resume()
// Send the request to the WebSocket API
sendRequest()
// Start receiving responses
receiveResponse()
}
// Run the WebSocket client to fetch contracts for the symbol
getContractsForSymbol()
// Keep the program running
RunLoop.main.run()
#include <libwebsockets.h>
#include <jansson.h>
#include <string.h>
#include <stdio.h>
#define APP_ID "your_app_id" // Replace with your actual app_id
// Define the WebSocket protocol handler
static int callback_websockets(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");
// Create the JSON request
json_t *contracts_for_symbol_request = json_pack("{s:s, s:s, s:s, s:s}",
"contracts_for", "R_50",
"currency", "USD",
"landing_company", "svg",
"product_type", "basic");
// Convert JSON object to string
char *request_str = json_dumps(contracts_for_symbol_request, 0);
printf("Sending request: %s\n", request_str);
// Send the request over WebSocket
lws_write(wsi, (unsigned char *)request_str + LWS_PRE, strlen(request_str), LWS_WRITE_TEXT);
// Free the JSON object and request string
free(request_str);
json_decref(contracts_for_symbol_request);
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
printf("Received message: %s\n", (char *)in);
// Parse the received JSON response
json_t *response_json = json_loads((const char *)in, 0, NULL);
if (!response_json) {
printf("Error parsing JSON response\n");
break;
}
// Check for an error in the response
json_t *error = json_object_get(response_json, "error");
if (error) {
const char *error_message = json_string_value(json_object_get(error, "message"));
printf("Error: %s\n", error_message);
lws_close_reason(wsi, LWS_CLOSE_STATUS_NORMAL, NULL, 0);
break;
}
// If the response contains 'contracts_for', print the data
json_t *msg_type = json_object_get(response_json, "msg_type");
if (msg_type && strcmp(json_string_value(msg_type), "contracts_for") == 0) {
json_t *contracts_for = json_object_get(response_json, "contracts_for");
char *contracts_str = json_dumps(contracts_for, JSON_INDENT(2));
printf("Contracts for symbol: %s\n", contracts_str);
free(contracts_str);
}
// Free the JSON object
json_decref(response_json);
break;
case LWS_CALLBACK_CLIENT_CLOSED:
printf("WebSocket connection closed\n");
break;
default:
break;
}
return 0;
}
// Define supported WebSocket protocols
static struct lws_protocols protocols[] = {
{
"protocol", // Protocol name
callback_websockets, // Callback function
0, // No per-session data
4096, // Buffer size
},
{ NULL, NULL, 0, 0 } // Terminator
};
int main(int argc, char **argv) {
// Set up the WebSocket context and connection info
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
info.port = CONTEXT_PORT_NO_LISTEN;
info.protocols = protocols;
struct lws_context *context = lws_create_context(&info);
if (context == NULL) {
printf("Failed to create WebSocket context\n");
return -1;
}
// Define connection parameters
struct lws_client_connect_info ccinfo = {0};
ccinfo.context = context;
ccinfo.address = "ws.derivws.com";
ccinfo.port = 443;
ccinfo.path = "/websockets/v3";
ccinfo.host = lws_canonical_hostname(context);
ccinfo.origin = "origin";
ccinfo.protocol = protocols[0].name;
ccinfo.ssl_connection = LCCSCF_USE_SSL;
// Append the app_id to the WebSocket URL
char ws_url[256];
snprintf(ws_url, sizeof(ws_url), "wss://ws.derivws.com/websockets/v3?app_id=%s", APP_ID);
ccinfo.path = ws_url;
// Establish WebSocket connection
struct lws *wsi = lws_client_connect_via_info(&ccinfo);
if (wsi == NULL) {
printf("Failed to connect to WebSocket server\n");
lws_context_destroy(context);
return -1;
}
// Run the WebSocket event loop
while (lws_service(context, 1000) >= 0);
// Clean up and destroy the WebSocket context
lws_context_destroy(context);
return 0;
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
// Define the app_id (replace 'your_app_id' with your actual app_id)
static readonly string app_id = "your_app_id";
// Define the request object for 'contracts_for' API call
static readonly JObject contractsForSymbolRequest = new JObject
{
{ "contracts_for", "R_50" }, // Symbol for which contracts are requested
{ "currency", "USD" }, // Set currency to USD
{ "landing_company", "svg" }, // Landing company
{ "product_type", "basic" } // Product type set to 'basic'
};
static async Task Main(string[] args)
{
// Create a new ClientWebSocket instance
using (ClientWebSocket ws = new ClientWebSocket())
{
// WebSocket connection URL with app_id
Uri serverUri = new Uri($"wss://ws.derivws.com/websockets/v3?app_id={app_id}");
// Connect to the WebSocket server
await ws.ConnectAsync(serverUri, CancellationToken.None);
Console.WriteLine("Connected to WebSocket server");
// Send the 'contracts_for' request to the WebSocket API
string requestMessage = contractsForSymbolRequest.ToString();
await SendMessageAsync(ws, requestMessage);
Console.WriteLine($"Sent request: {requestMessage}");
// Start receiving responses
await ReceiveMessageAsync(ws);
}
}
// Function to send a message over WebSocket
static async Task SendMessageAsync(ClientWebSocket ws, string message)
{
byte[] bytesToSend = Encoding.UTF8.GetBytes(message);
await ws.SendAsync(new ArraySegment<byte>(bytesToSend), WebSocketMessageType.Text, true, CancellationToken.None);
}
// Function to receive and handle messages from the WebSocket server
static async Task ReceiveMessageAsync(ClientWebSocket ws)
{
byte[] buffer = new byte[1024 * 4];
while (ws.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
// Parse the received message as JSON
JObject responseJson = JObject.Parse(message);
Console.WriteLine($"Received message: {message}");
// Check for errors in the response
if (responseJson["error"] != null)
{
string errorMessage = responseJson["error"]["message"].ToString();
Console.WriteLine($"Error: {errorMessage}");
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Error received", CancellationToken.None);
break;
}
// If the response contains 'contracts_for', print the contract data
if (responseJson["msg_type"] != null && responseJson["msg_type"].ToString() == "contracts_for")
{
Console.WriteLine("Contracts for symbol: " + responseJson["contracts_for"]);
}
}
}
}
package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"github.com/gorilla/websocket"
)
// Define the request object structure
type ContractsForRequest struct {
ContractsFor string `json:"contracts_for"`
Currency string `json:"currency"`
LandingCompany string `json:"landing_company"`
ProductType string `json:"product_type"`
}
// Define the response structure for contract data
type ContractsForResponse struct {
MsgType string `json:"msg_type"`
ContractsFor json.RawMessage `json:"contracts_for,omitempty"`
Error *APIError `json:"error,omitempty"`
}
// Structure for potential errors in the API response
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func main() {
// Define the app_id (replace 'your_app_id' with your actual app_id)
appID := "your_app_id"
// Create a request object for the WebSocket message
request := ContractsForRequest{
ContractsFor: "R_50", // Symbol for which contracts are requested
Currency: "USD", // Set currency to USD
LandingCompany: "svg", // Landing company
ProductType: "basic", // Product type is set to 'basic'
}
// Convert the request object to JSON
requestData, err := json.Marshal(request)
if err != nil {
log.Fatalf("Failed to marshal request: %v", err)
}
// Create WebSocket connection URL with app_id
u := url.URL{Scheme: "wss", Host: "ws.derivws.com", Path: "/websockets/v3", RawQuery: "app_id=" + appID}
fmt.Printf("Connecting to %s\n", u.String())
// Establish the WebSocket connection
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatalf("Failed to connect to WebSocket: %v", err)
}
defer conn.Close()
// Send the request over WebSocket
err = conn.WriteMessage(websocket.TextMessage, requestData)
if err != nil {
log.Fatalf("Failed to send message: %v", err)
}
fmt.Printf("Sent request: %s\n", requestData)
// Start receiving messages from the WebSocket
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Fatalf("Error reading message: %v", err)
}
// Handle the received message
handleResponse(message)
}
}
// Function to handle WebSocket responses
func handleResponse(message []byte) {
// Parse the response as JSON
var response ContractsForResponse
err := json.Unmarshal(message, &response)
if err != nil {
log.Printf("Failed to unmarshal response: %v", err)
return
}
// Check for errors in the response
if response.Error != nil {
log.Printf("Error: %s - %s", response.Error.Code, response.Error.Message)
os.Exit(1)
}
// If the response contains 'contracts_for', print the contract data
if response.MsgType == "contracts_for" {
fmt.Printf("Contracts for symbol: %s\n", response.ContractsFor)
}
}
Updated 10 days ago