Deriv API

Quickstart

Quickstart to Deriv API

On this page, you'll find code samples in various programming languages showing you how to work with the Deriv API to perform some of the most important operations.

You can find all of the other available calls in the API Playground.

Before you begin

  • Open a Deriv account (either a demo or real account).
  • Create a new token using the admin scope.
  • Register your app to receive your app_id or use app_id 1089 to test Deriv API.

Setting up your environment

Instructions for setting up your environment and running the examples in your desired programming language are given as comments in the code samples.

Buy contract

A contract is an agreement to buy or sell an asset at an agreed-upon price. This example shows you how to buy a contract using Deriv API.

Copy
Copied to clipboard

/*
 * This is an example of using JavaScript with NodeJS to buy a contract via the Deriv/Binary API.
 * This is a simple example where we do not check first if the user has the 
 * symbol available to buy. To check this you would use the active_symbols call.
 * To run this example using NodeJS
 * - Ensure you have NodeJs installed (https://nodejs.org/).
 * - Save this script to a directory on your computer as `buy_contract.js`.
 * - Run `npm install ws` to install the websocket library.
 * - Edit the example and change the app_id and the API token. 
 * - Then run `node buy_contract.js`.
 * 
 * The api token should be from the same account that the contract is to be purchased for.
 */
const WebSocket = require('ws');

// You can register for an app_id here https://developers.deriv.com/docs/app-registration/.
const app_id = 1089; // Replace with your app_id or leave as 1089 for testing.

const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=' + app_id);

// You can get your token here https://app.deriv.com/account/api-token. 
const token = ''; // Replace with your API token.

ws.onopen = function (evt) {
    ws.send(JSON.stringify({ "authorize": token })) // First send an authorize call.
};

ws.onmessage = function (msg) {
    var data = JSON.parse(msg.data);
    // console.log('Response: %o', data); // Uncomment this to see full response data. 
    if (data.error !== undefined) {
        console.log(data.error.message);
        ws.close();
    } else if (data.msg_type == 'authorize') {
        /*
        * Since we can not ensure calls to websocket are made in order we must wait for 
        * the response to the authorize call before sending the buy request. 
        */
        ws.send(JSON.stringify({
            "buy": 1,
            "subscribe": 1,
            "price": 10,
            "parameters": { "amount": 10, "basis": "stake", "contract_type": "CALL", "currency": "USD", "duration": 1, "duration_unit": "m", "symbol": "R_10" }
        }));
    } else if (data.msg_type == 'buy') { // Our buy request was successful let's print the results. 
        console.log("Contract Id " + data.buy.contract_id + "\n");
        console.log("Details " + data.buy.longcode + "\n");
    } else if (data.msg_type == 'proposal_open_contract') { // Because we subscribed to the buy request we will receive updates on our open contract. 
        var isSold = data.proposal_open_contract.is_sold;
        if (isSold) { // If `isSold` is true it means our contract has finished and we can see if we won or not.
            console.log("Contract " + data.proposal_open_contract.status + "\n");
            console.log("Profit " + data.proposal_open_contract.profit + "\n");
            ws.close();
        } else { // We can track the status of our contract as updates to the spot price occur. 
            var currentSpot = data.proposal_open_contract.current_spot;
            var entrySpot = 0;
            if (typeof (data.proposal_open_contract.entry_tick) != 'undefined') {
                entrySpot = data.proposal_open_contract.entry_tick;
            }
            console.log("Entry spot " + entrySpot + "\n");
            console.log("Current spot " + currentSpot + "\n");
            console.log("Difference " + (currentSpot - entrySpot) + "\n");
        }
    }
};

Ticks

A tick is a measure of minimum upward or downward movement in the price of a trading commodity. This example shows you how to collect ticks for your trading app using Deriv’s API.

Copy
Copied to clipboard

/*
 * This is an example of using JavaScript with NodeJS to collect ticks for your trading app using Deriv's API.
 * To run this example using NodeJS
 * - Ensure you have NodeJs installed (https://nodejs.org/).
 * - Save this script to a directory on your computer as `ticks.js`.
 * - Run `npm install ws` to install the websocket library.
 * - Edit the example and change the app_id (Replace with your app_id or leave as 1089 for testing).
 * - Then run `node ticks.js`.
 */

const WebSocket = require('ws');
var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');

ws.onopen = function (evt) {
    ws.send(JSON.stringify({ ticks: 'R_100' }));
};

ws.onmessage = function (msg) {
    var data = JSON.parse(msg.data);
    console.log('Ticks update: %o', data);
};

Account balance

This example shows you how to use the Deriv API to retrieve account balance information.

Copy
Copied to clipboard

/*
 * This is an example of using JavaScript with NodeJS to subscribe to balance of an account. 
 * To run this example using NodeJS
 * - Ensure you have NodeJs installed (https://nodejs.org/).
 * - Save this script to a directory on your computer as `account_balance.js`.
 * - Run `npm install ws` to install the websocket library.
 * - Edit the example and change the app_id and the API token. 
 * - Then run `node account_balance.js`.
 * 
 * The api token should be from the same account that the balance is to be checked for.
 */
const WebSocket = require('ws');

// You can register for an app_id here https://developers.deriv.com/docs/app-registration/.
const app_id = 1089; // Replace with your app_id.
const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=' + app_id);

// You can get your token here https://app.deriv.com/account/api-token. 
const token = ''; // Replace with your API token.

ws.onopen = function (evt) {
    ws.send(JSON.stringify({ "authorize": token })) // First send an authorize call.
};

ws.onmessage = function (msg) {
    var data = JSON.parse(msg.data);
    // console.log('Response: %o', data); // Uncomment to see the full JSON response.
    if (data.error !== undefined) {
        console.log('Error : %o', data.error.message);
    } else if (data.msg_type == 'authorize') {
        /*
        * Since we can not ensure calls to websocket are made in order we must wait for 
        * the response to the authorize call before sending the balance request. 
        * 
        * We subscribe to balance updates so any updates to balance will be received.
        * If you perform a trade while this script is running you should see updates 
        * to the balance printed.  
        */
        ws.send(JSON.stringify({ "balance": 1, "subscribe": 1 }))
    } else if (data.msg_type == 'balance') {
        console.log('Current Balance: %o', data.balance.balance);
    } else {
        console.log('Unknown Response %o', data);
    }
};

Proposal

This example is for getting a contract proposal. You’ll be able to get the price, payout and spot value for your contract.

Copy
Copied to clipboard

/*
 * This is an example of using JavaScript with NodeJS to view contract proposals via the Deriv/Binary API.
 * This is a simple example where we do not check first if the user has the
 * symbol available. To check this you would use the active_symbols call.
 * To run this example using NodeJS
 * - Ensure you have NodeJs installed (https://nodejs.org/).
 * - Save this script to a directory on your computer as `proposal.js`.
 * - Run `npm install ws` to install the websocket library.
 * - Edit the example and change the app_id and the API token. 
 * - Then run `node proposal.js`.
 * 
 */
const WebSocket = require('ws');
const app_id = 1089; // Replace with your app_id or leave as 1089 for testing.
const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=' + app_id);

ws.onopen = function (evt) {
    ws.send(JSON.stringify({
        "proposal": 1,
        "subscribe": 1,
        "amount": 10,
        "basis": "payout",
        "contract_type": "CALL",
        "currency": "USD",
        "duration": 1,
        "duration_unit": "m",
        "symbol": "R_100",
        "barrier": "+0.1"
    }));
};

ws.onmessage = function (msg) {
    var data = JSON.parse(msg.data);
    // console.log('Response: %o', data); // Uncomment this to see full response data. 
    if (data.error !== undefined) {
        console.log("Error: %s", data.error.message);
        ws.close();
    } else if (data.msg_type == 'proposal') {
        console.log("Details: %s", data.proposal.longcode);
        console.log("Ask Price: %s", data.proposal.display_value);
        console.log("Payout: %s", data.proposal.payout);
        console.log("Spot: %s", data.proposal.spot);
    }
};

To keep this connection alive in case of inactivity timeouts, see the example for Keep alive.

Keep alive

In this example you’ll see how to keep a connection alive when getting contract proposals via the Deriv API. This example keeps the connection alive by sending a ping every 30 seconds.

Copy
Copied to clipboard

/*
 * This is an example of using JavaScript with NodeJS to create a proposal subscription and prevent it from timing out.  
 * A ping will be sent via websocket to the server every 30 seconds. 
 * This approach can be used for all subscriptions to prevent timeout.
 * To run this example using NodeJS
 * - Ensure you have NodeJs installed (https://nodejs.org/).
 * - Save this script to a directory on your computer as `proposal_keep_alive.js`.
 * - Run `npm install ws` to install the websocket library.
 * - Edit the example and change the app_id and the API token. 
 * - Then run `node proposal_keep_alive.js`.
 * 
 * The api token should be from the same account that the contract is to be purchased for.
 */
const WebSocket = require('ws');

// You can register for an app_id here https://developers.deriv.com/docs/app-registration/.
const app_id = 1089; // Replace with your app_id.
const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=' + app_id);

ws.onopen = function (evt) {
    ws.send(JSON.stringify({
        "proposal": 1,
        "subscribe": 1,
        "amount": 10,
        "basis": "payout",
        "contract_type": "CALL",
        "currency": "USD",
        "duration": 1,
        "duration_unit": "m",
        "symbol": "R_100",
        "barrier": "+0.1"
    }));
    /*
    * Send a ping ever 30 seconds to keep the connection alive, needs to use the same 
    * websocket connection as the one you want to maintain.
    */
    setInterval(ping, 30000);
};
ws.onmessage = function (msg) {
    var data = JSON.parse(msg.data);
    // console.log('Response: %o', data); // Uncomment this to see full response data. 
    if (data.error !== undefined) {
        console.log("Error: %s ", data.error.message);
        ws.close();
    } else if (data.msg_type == 'proposal') { 
        console.log("Details: %s", data.proposal.longcode);
        console.log("Ask Price: %s", data.proposal.display_value);
        console.log("Payout: %s", data.proposal.payout);
        console.log("Spot: %s", data.proposal.spot);
    } else if (data.msg_type == 'ping') {
        console.log("ping");
    }
};
function ping() { ws.send(JSON.stringify({ "ping": 1 })) }