Git Product home page Git Product logo

deriv-api's Introduction

DerivAPI

Async Websocket API for deriv-app

Code Coverage: codecov

Requirement:

Node.js (v12.18.0 or higher is recommended)

Installation

Installing Deriv API Library

We need to install the Deriv API library if we want to connect to Deriv's websocket.

NPM

npm install @deriv/deriv-api

yarn

yarn add @deriv/deriv-api

Installing Websocket (ws) library

In order to make a websocket connection, we need the websocket (ws) library.

NPM

npm install ws

yarn

yarn add ws

Usage

Basic library

The basic library is a lighter version of the Deriv API, suitable for apps that want to directly deal with API calls.

It can either be imported as a separate module (to reduce the final bundle size) or if the DerivAPI library is already imported, can be accessed using api.basic.

const WebSocket = require('ws');
const DerivAPI = require('@deriv/deriv-api/dist/DerivAPI');

// app_id 1089 is for testing, create your own app_id and use it here.
// go to api.deriv.com to register your own app.
const connection = new WebSocket('wss://ws.derivws.com/websockets/v3?app_id=1089');
const api        = new DerivAPI({ connection });
const basic = api.basic;

basic.ping().then(console.log);

ES6 modules

Basic API

// Smaller bundle size, dealing only with the low-level library
import DerivAPIBasic from '@deriv/deriv-api/dist/DerivAPIBasic.js';
import WebSocket from 'ws';

// app_id 1089 is for testing, create your own app_id and use it here.
// go to api.deriv.com to register your own app.
const connection = new WebSocket('wss://ws.derivws.com/websockets/v3?app_id=1089');
const api        = new DerivAPIBasic({ connection });

api.ping().then(console.log);

CommonJS modules

Basic API

// Smaller bundle size, dealing only with the low-level library
const WebSocket = require('ws');
const DerivAPIBasic = require('@deriv/deriv-api/dist/DerivAPIBasic');

// app_id 1089 is for testing, create your own app_id and use it here.
// go to api.deriv.com to register your own app.
const connection = new WebSocket('wss://ws.derivws.com/websockets/v3?app_id=1089');
const api        = new DerivAPIBasic({ connection });

api.ping().then(console.log);

Using the HTML script tag

Basic API

<script src="https://unpkg.com/@deriv/deriv-api/dist/DerivAPIBasic.js"></script>
<script>
    const api = new DerivAPIBasic({ 
        endpoint: 'ws.derivws.com',
        app_id: 1089 /* 1089 is a default test app_id, replace with your own app_id */,
        lang: 'EN' 
    });
    
    api.ping().then(console.log);
</script>

Creating a WebSocket connection

There are two ways to establish a connection:

  1. Use a previously opened connection:

    const connection = new WebSocket('wss://ws.derivws.com/websockets/v3?app_id=YOUR_APP_ID');
    const api        = new DerivAPI({ connection });
  2. Pass the arguments needed to create a connection:

    const api = new DerivAPI({ endpoint: 'ws.derivws.com', app_id: /* your app_id */, lang: 'EN' });

Documentation

Wiki

There is a short tutorial about how to use Deriv API in the wiki page.

API reference

The complete API reference is hosted here

The above reference in one page: DerivAPI reference

Development

git clone https://github.com/binary-com/deriv-api
cd deriv-api
npm install

To run the tests

npm test

Run tests automatically on source code edits

npm run devel

Run linter

npm run syntax

Run all tests (lint + js tests)

npm run test_all

Prettify the code (done automatically on commit)

npm run prettify

Generate documentations

npm run docs

Regenerate docs automatically on source code edit

Needs inotify to work.

npm run devel_docs

Serve docs on localhost and update on source code changes

npm run serve_docs

Generate html version of the docs and publish it to gh-pages

npm run gh-pages

Build the package

npm run build

Run examples

DERIV_TOKEN=YourTokenHere npm run examples

deriv-api's People

Contributors

ali-hosseini-deriv avatar aminmarashi avatar ashkanx avatar balakrishna-deriv avatar cakasuma avatar chylli-deriv avatar dependabot[bot] avatar mohammad-deriv avatar mohsen-deriv avatar negar-binary avatar oskar-binary avatar salarhfz-fs avatar sasikala-binary avatar sasikalachinnasamy avatar shantanu-deriv avatar tom-binary avatar yashim-deriv avatar yaswanth-deriv avatar zaki-hanafiah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deriv-api's Issues

api.contract problem

Hello, I´m developing a bot with deriv api, but I can´t buy twice with the same contract options.

If the amount is doubled, it works, but if I try to create a new contract with the same amount, api.contract never returns and the bot keep locked.

This is my code:

while (total < take_profit && total > -stop_loss) {

const contract = await api.contract({
amount: amount,
basis: 'stake',
contract_type: 'CALL',
currency: 'USD',
duration: 3,
duration_unit: 't',
proposal: 1,
symbol: '1HZ100V',
product_type: 'basic'
});

const buy = await contract.buy();

await contract
.onUpdate()
.pipe(find(({ is_sold }) => is_sold))
.toPromise();

const { profit, status } = contract;

if (status == 'won') {
total += Number(profit.display);
} else {
total -= Number(profit.display);
}

}

Any suggestion?

Tks.

Cannot stake decimal amount

Steps to reproduce using the example file a_simple_bot.js:

  1. Change the contract_type to DIGITODD
  2. Change the symbol to R_10
  3. Comment the line 52 that expects the payout: await contract.onUpdate().pipe(find(({ payout }) => payout.value >= expected_payout)).toPromise();
  4. Run, it works
  5. Change the amount to 0.5
  6. Run, it fails with the message:
error: {
  code: 'ContractCreationFailure',
  message: "Contract's stake amount is more than the maximum purchase price."
},

Using onOpen() function from api's instance member

Problem: execute an operation on every Deriv connection opened

According to documentation, there are Instance Members called
▸ closeHandler()
▸ onClose()
▸ onOpen()
▸ onMessage()
▸ expectResponse(types)

coming from

const api= new DerivAPI({...});

The question is: how to access that onOpen() function on code?
api.basic.onOpen() did not seems to work.

Access to Contracts

Hi,
I had a question about the contracts section. Is the information in this section still incomplete? Because I can not get their history or information about them.

TypeError: api.forget is not a function & TypeError: api.forgetAll is not a function

    const { find } = require('rxjs/operators');
    const DerivAPI = require('@deriv/deriv-api');

    const api = new DerivAPI({ app_id });

    async function main() {

      try {
        const account = await api.account(token);
        const contract = await api.contract({ ...options });

        const buy = await contract.buy();

        // Wait until the contract is sold
        await contract.onUpdate().pipe(find(({ is_sold }) => is_sold)).toPromise();

        const forget = await api.forget({ forget: contract.proposal_id }); 
        const forgetAll = await api.forgetAll({ forget_all: 'proposal' }); 
      }
      catch(error) {
        console.log(error); 
        // TypeError: api.forget is not a function
        // TypeError: api.forgetAll is not a function
      }

    }

    main();

🏕️

I'm facing this problem with api.forget and api.forgetAll it both doesn't exist
in spite of they are declared on documentation.

forget
forgetAll

api is not reconnecting to websocket

how to reconnect to websocket i'm not passing the websocket connection as described in the docs
passing only app_id so that api can auto reconnect but still api is disconnecting after an hour and the program exits
here is my code

const api = new DerivAPI({
    app_id
});


fx_symbols = ['frxAUDCAD', 'frxAUDJPY', 'frxAUDUSD', 'frxEURAUD', 'frxEURCAD', 'frxEURCHF', 'frxEURGBP', 'frxEURJPY', 'frxEURNZD', 'frxEURUSD','frxNZDUSD', 'frxUSDCAD', 'frxUSDCHF', 'frxUSDJPY',]

fx_candles_1m = {
    "frxAUDCAD": [],
    "frxAUDJPY": [],
    "frxAUDUSD": [],
    "frxEURAUD": [],
    "frxEURCAD": [],
    "frxEURCHF": [],
    "frxEURGBP": [],
    "frxEURJPY": [],
    "frxEURNZD": [],
    "frxEURUSD": [],
    "frxNZDUSD": [],
    "frxUSDCAD": [],
    "frxUSDCHF": [],
    "frxUSDJPY": [],
}

(async () => {
    fx_symbols.map(x => { getAllCandles(x, 60).catch(err => console.log(err)) })
})()

async function getAllCandles(symbol, tf) {
    candle_data = await api.candles({ symbol: symbol, granularity: tf, end: "latest", style: "candles", subscribe: 1 })
    candle_data.onUpdate(data => {
        if (data.raw.epoch === data.raw.open_time + tf - 1) {
            // console.log("The candle data for " + symbol + " is : ", data.raw);
            o = data.raw.open
            h = data.raw.high
            l = data.raw.low
            c = data.raw.close
            epoch = data.raw.epoch + 1
            const x = [o, h, l, c, epoch]
            const { granularity, id, open_time, pip_size, symbol, ...noA } = data.raw

            noA['epoch'] = noA['epoch'] + 1
            fx_candles_1m[symbol].push(x)
            console.log(symbol, vol_candles_1m[symbol]);

            const open = fx_candles_1m[symbol].map(d => d[0])
            const high = fx_candles_1m[symbol].map(d => d[1])
            const low = fx_candles_1m[symbol].map(d => d[2])
            const close = fx_candles_1m[symbol].map(d => d[3])

            if (fx_candles_1m[symbol].length > 14) {
              let rsi = RSI.calculate({ period: 14, values: close })
              console.log("The RSI value of " + symbol + " is ", rsi.slice(-2))
            }


            if (fx_candles_1m[symbol].length > 15) {
                fx_candles_1m[symbol].shift()
            }
            return Promise.resolve([symbol, data.raw])

        }
    })
}

what should i do to reconnect if api is disconnected

Delay in API Res

I'm trying to make a request of buy contract in a async ticksHistoryResponse, who is called in every response of the async ticksResponse. This ticksHistoryResponse function contains a condition that analyze the last 10 open, high, low and close prices of candles and the currently epoch, and make a buy request when all the condition are satisfied.

This function works good when i get in the computer and when i interact with it.

However, after a period of not interacting with the computer, the server responses are out of sync within 2 minutes, and the logs displayed on the console stop showing real-time information and show information from exactly 2 minutes ago. This causes purchase requests to be delayed.

I tried keeping tabs always on by enabling Chrome browser performance functions, but it didn't work. I'm calling the async functions through the await. Below is the script:

import DerivAPIBasic from "https://cdn.skypack.dev/@deriv/deriv-api/dist/DerivAPIBasic";

const token = "my_token";
const app_id = my_number_app;

function createWebSocket(app_id) {
let connection;

function connect() {
connection = new WebSocket(
wss://ws.derivws.com/websockets/v3?app_id=${app_id},
);

connection.onopen = function (event) {
  console.log("Conexão estabelecida:", event);
  connection;
};

connection.onmessage = function (event) {
  console.log("Mensagem recebida:", event.data);
};

connection.onclose = function (event) {
  console.log("Conexão fechada:", event);
  reconnect();
};

connection.onerror = function (event) {
  console.error("Erro na conexão:", event);
  reconnect();
};
return connection;

}

function reconnect() {
console.log("Tentando reconectar em 500 milisegundos...");
setTimeout(() => {
connect();
}, 500); // Tentar reconectar após 500 milisegundos
}
// Inicializa a conexão
return connect();
}

const a1 = createWebSocket(app_id);

let api = new DerivAPIBasic({ connection: a1 });

const onCloseObservable = api.onClose();
const onOpenObservable = api.onOpen();

// Subscrever aos eventos de fechamento
onCloseObservable.subscribe(() => {
console.log("Conexão fechada. Tentando reconectar...");

setTimeout(() => {
try {
window.location.reload();
console.log("Método reload() chamado.");
} catch (error) {
console.error("Erro ao tentar reconectar:", error);
}
}, 1000); // Tempo de espera de 1 segundos
});

window.addEventListener("offline", () => {
console.log("O dispositivo está offline.");
window.location.reload();
});

// Subscrever aos eventos de abertura
onOpenObservable.subscribe(() => {
autorization();
subscribeTicks();
ping()
console.log("Conexão aberta.");
});

const autorizacao = {
authorize: "my_token",
};
const autorization = async () => {
await api.authorize(autorizacao);
};

const ticks_history_request = {
ticks_history: "Any_VIX",
adjust_start_time: 1,
count: 10,
end: "latest",
start: 1,
style: "candles",
granularity: 60,
};

const ticks_request = {
...ticks_history_request,
subscribe: 1,
};

const ping = () => {
setInterval(() => {
api.ping();
}, 15000);
};

const balance1 = {
balance: 1,
subscribe: 1,
account: "current",
loginid: "my_loginid",
};

const balance2 = async () => {
api.balance(balance1);
};

const observable = api.onMessage(); // Assumindo que api.onMessage() retorna um Observable
let saldo;
let saldoAtual;
let balancinha;
let balanca3
const subscription1 = observable.subscribe((message) => {
// Exibe os dados recebidos no console para depuração

// Verifica se a estrutura da mensagem está conforme o esperado
if (
message &&
message.name === 'message' &&
message.data &&
message.data.balance &&
message.data.balance.balance !== undefined
) {
saldo = message.data.balance.balance
saldoAtual = parseFloat(saldo.toFixed(2));
balancinha = saldoAtual * 0.01
balanca3 = parseFloat(balancinha.toFixed(2))
}
});

const createBuyContract = async () => {

const buyContract = {
buy: 1,
price: 25000,
parameters: {
contract_type: "CALLE",
amount: balanca3,
basis: "stake",
symbol: "Any_VIX",
currency: "USD",
duration: 1,
duration_unit: "m",
},
};
return buyContract;
};

const buy = async () => {
const contract = await createBuyContract(); // Espera a resolução da função assíncrona
const buy1 = api.buy(contract);
return buy1
};

let timeepoch
let timeepoch2
let timeepoch3
let logs
const subscription2 = observable.subscribe((message) => {
// Exibe os dados recebidos no console para depuração
logs = console.log(message)

// Verifica se a estrutura da mensagem está conforme o esperado
if (
message &&
message.name === 'message' &&
message.data &&
message.data.ohlc &&
message.data.ohlc.epoch !== undefined
) {

timeepoch = message.data.ohlc.epoch;
timeepoch2 = parseInt(timeepoch.toFixed())
timeepoch3 = timeepoch2 % 60

}
});

const tickSubscriber = () => api.subscribe(ticks_request);

const ticksHistoryResponse = async (res) => {
const data = JSON.parse(res.data);
if (data.error !== undefined) {
console.log("Error : ", data.error.message);
}
if (data.msg_type === "candles") {

if (
  timeepoch3 = 0 &&
  (data.candles[data.candles.length - x].open - data.candles[data.candles.length - x].close) / (data.candles[data.candles.length - x].high - data.candles[data.candles.length - x].low) >= 0.05 &&
  data.candles[data.candles.length - x].open > data.candles[data.candles.length - x].close
) {
  console.log("Buy");
  console.log(timeepoch);
  logs;
  await buy();
} else {
  console.log("Dbuy");
  logs
}

}
}

const ticksResponse = async (res) => {
const data = JSON.parse(res.data);
// This example returns an object with a selected amount of past ticks.
if (data.error !== undefined) {
console.log("Error : ", data.error.message);
}
// Allows you to monitor ticks.
if (data.msg_type === "ohlc") {

await getTicksHistory();

}
if (data.msg_type === "ping") {
console.log("ping");
}
if (data.msg_type === "buy") {
console.log(data.buy);
}
if (data.msg_type === "authorize") {
console.log(data.authorize.email);
await balance2();
}
if (data.msg_type === "balance") {
console.log(data.balance.balance);
}
};

const subscribeTicks = async () => {
a1.addEventListener("message", ticksResponse);
await tickSubscriber();
};

const unsubscribeTicks = async () => {
a1.removeEventListener("message", ticksResponse, false);
await tickSubscriber().unsubscribe();
};

const getTicksHistory = async () => {
a1.addEventListener("message", ticksHistoryResponse);
await api.ticksHistory(ticks_history_request);
};

const subscribe_ticks_button = document.querySelector("#ticks");
subscribe_ticks_button.addEventListener("click", subscribeTicks);

const unsubscribe_ticks_button = document.querySelector("#ticks-unsubscribe");
unsubscribe_ticks_button.addEventListener("click", unsubscribeTicks);

const ticks_history_button = document.querySelector("#ticks-history");
ticks_history_button.addEventListener("click", getTicksHistory);

Error trying to import deriv-api

Hi there,

I'm trying to import deriv-api, but I'm receving the following error message:

> [email protected] start C:\Users\User\vscode-workspace\binarybot
> node index.js

file:///C:/Users/User/vscode-workspace/binarybot/index.js:4
import DerivAPI from '@deriv/deriv-api';
       ^^^^^^^^
SyntaxError: The requested module '@deriv/deriv-api' does not provide an export named 'default'
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:92:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:107:20)
    at async Loader.import (internal/modules/esm/loader.js:179:24)

I ran the code below using NodeJs v14.0.0 and v13.5.

Could you guys help me?

import express from 'express';
import cors from 'cors';
import routes from './routes.js';
import DerivAPI from '@deriv/deriv-api';

var app = express();
var router = express.Router()

app.use(cors());
app.use(express.json());

router.get('/', function (req, res) {
    res.send('ROOT FOLDER')
  })

app.use(routes);
app.listen(3333, () => {
    console.log('debug > console listening on port 3333');
});

If you guys need more information, please, let me know.

How to get proposal stream?

const proposal = await api.basic.proposal({ ...proposalData, subscribe: 1 });

proposal.onUpdate(async ({ ask_price }) => {}); // TypeError: proposal.onUpdate is not a function
        

It does not contains that function, is there would other way to get it?

Use a new dws domain in docs

I had issues while trying to connect to ws.binaryws.com as usual. I investigated a bit and found that I need to switch to the derivws.com domain to make it work.

@ali-hosseini-deriv Just a friendly reminder to change the URL for API docs too.

Can't get assets or trade digits in vix.

First, Tried to operate digits, but dont get return, if i change from DIGITOVER to CALL, it works fine.
`async function main() {
try {
let gstake = 1;

    const account = await api.account(token);

    const { balance, currency } = account;

    console.log(`Your current balance is: ${balance.currency} ${balance.display}`);

    balance.onUpdate(() => {
        console.log(`Your new balance is: ${balance.currency} ${balance.display}`);
    });

    let data = {
        contract_type: 'DIGITOVER',
        currency,
        amount: gstake,
        duration: 5,
        duration_unit: 't',
        symbol: 'R_100',
        basis: 'stake',
        barrier: 2,
    };

    let contract = await api.contract(data);

    contract.onUpdate(({ status, payout, bid_price }) => {
        switch (status) {
            case 'proposal':
                return console.log(
                    `Current payout: ${payout.currency} ${payout.display}`);
            case 'open':
                return console.log(
                    `Current bid price: ${bid_price.currency} ${bid_price.display}`);
            default:
                break;
        };
    });

    // Wait until payout is greater than USD 19
    await contract.onUpdate().pipe(find(({ payout }) => payout.value >= expected_payout)).toPromise();
    
    const buy = await contract.buy();
    
    console.log(`Buy price is: ${buy.price.currency} ${buy.price.display}`);

    // Wait until the contract is sold
    await contract.onUpdate().pipe(find(({ is_sold }) => is_sold)).toPromise();
    await api.basic.forgetAll();

    const { profit, status } = contract;

    console.log(`You ${status}: ${profit.currency} ${profit.display}`);
    if(status == "loss") {
        gstake = gstake * 2.15;
    } else {
        gstake = 1;
    }
    api.basic.forgetAll('proposal', 'proposal_open_contract');

} catch (err) {
    console.error(err);
} finally {
    // Close the connection and exit
    //api.basic.disconnect();
}

}`

Second, tried to get assets and open markets, with
const assets = await api.assets(); const open_markets = assets.open_markets; const trading_times = assets.trading_times;

Got an error, saying that assets is not a function.

Binary-live-api vs Deriv

Hi Guys,

I'm an app developer using the binary-live-api. I would like to update the application to support the new margin trading method, is this supported in binary-live-api? Also will the old api end up being depricated in favour of this one?

Basically, should I be refactoring and migrating my applications over to Deriv-api?

Many thanks in advance!

Will

cant connect to account

I have the following code

const connection = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=app_id');
const api = new DerivAPIBasic({ connection });

` async function main() {
try {
const account = await api.account('token');
const { balance, currency } = account;

        console.log(balance);
    } catch (error) {
        console.log(error);
    }
}`

i have tried getting the balance or currency but instead am getting TypeError: undefined is not a function in this line const account = await api.account('token'); What could i be doing wrong?

Buy contract is not updating

As you can see below @ buy_contract_request ----> " amount ": lot, this is not updating in loop
As you can see below on the 8th line ---> let lot = 0.35; this value changes on every loop
When I run this code it should increase the amount on every loop eg:- amount : 0.35 , amount : 0.77 ,amount: 1.5
But it's not increasing the amount in loop, It just taking trade like , amount : 0.35, amount : 0.35,amount : 0.35

const WebSocket = require('ws');
const DerivAPIBasic = require('@deriv/deriv-api/dist/DerivAPIBasic');
const app_id = 1089; // Replace with your app_id or leave as 1089 for testing.
const connection = new WebSocket(wss://ws.binaryws.com/websockets/v3?app_id=${app_id});
const api = new DerivAPIBasic({ connection });
const token = 'xxxxxxxxxxx';// ----->API token

let trade_status = 0;

let lot = 0.35;

const buy_contract_request = { "buy": 1, "subscribe": 1, "price": 1000, "parameters": { "amount": lot, // this is not updating "duration": 1, "basis": "stake", "symbol": "R_10", "currency": "USD", "duration_unit": "t", "contract_type": "CALL" } }

const buyContractResponse = async (res) => {
const data = JSON.parse(res.data);
const is_sold = data.proposal_open_contract?.is_sold;

if (data.error !== undefined) {
    console.log('Error : %o', data.error.message);
    connection.removeEventListener('message', buyContractResponse, false);
    //await api.disconnect();
}

if (data.msg_type === 'buy') {
    console.log(`Contract Id ${data.buy.contract_id} \n`);
    console.log(`Details ${data.buy.longcode} \n`);
}

if (data.msg_type === 'proposal_open_contract') {
    // If `is_sold` is true it means our contract has finished and we can see if we won or not.
    if (is_sold) {
        const contract_status = data.proposal_open_contract.status;
        const contract_profit = data.proposal_open_contract.profit;
        console.log(`Profit ${contract_profit} \n`);
        console.log(`Contract ${contract_status} \n`);
        connection.removeEventListener('message', buyContractResponse, false);
        //await api.disconnect();
        trade_status = 0;
        get_all = lot * 2.5 ;
        lot = get_all.toFixed(2);
        console.log(lot)
    } else {
        // We can track the status of our contract as updates to the spot price occur.
        let entry_spot = 0; 
        const entry_tick = data.proposal_open_contract.entry_tick;
        const current_spot = data.proposal_open_contract.current_spot;
        if (typeof (entry_tick) !== 'undefined') entry_spot = entry_tick;
        //console.log(`Entry spot ${entry_spot} \n`);
       // console.log(`Current spot ${current_spot} \n`);
        //console.log(`Difference ${current_spot - entry_spot} \n`);
    }
}

}

const buyContract = async () => {
await api.authorize(token);
await api.buy(buy_contract_request);
connection.addEventListener('message', buyContractResponse);

}

setInterval(function () {
if (trade_status === 0){

buyContract();
trade_status = 1;

}}, 1);

Creating api.contract and buying is too slow

Creating api.contract and buying it take 3-7 sec. How can I reduce that time?

Code -

`...
const contract = await api.contract({...});

contract.onUpdate(async ({status}) => {...
})

const buy = await contract.buy();
...
`

Log -

[19:06:24:756] [10/5/2021] $ {1} frxAUDJPY $939 5M CALL Create order
[19:06:35:599] [10/5/2021] $ {138614057128} frxAUDJPY 5M $939 Order Opend
[19:11:32:167] [10/5/2021] $ {138614057128 LOSS}

1time buy success and stop.

https://github.com/binary-com/deriv-api/blob/master/examples/a_simple_bot.js

get account balance is working can repeat many time in loop.
async function main() {
while (1) {
const account = await api.account(token);
const { balance } = account;
console.log(Your current balance is: ${balance.currency} ${balance.display});
}
}
Out put
Your current balance is: USD 13,464.40
Your current balance is: USD 13,464.40
Your current balance is: USD 13,464.40
Your current balance is: USD 13,464.40
Your current balance is: USD 13,464.40
Your current balance is: USD 13,464.40

after add by contract only buy 1 time and stop.
async function main() {
while (1) {
const account = await api.account(token);

    const { balance } = account;

    console.log(`Your current balance is: ${balance.currency} ${balance.display}`);
    const contract = await api.contract({
        contract_type: 'CALL',
        currency: balance.currency,
        amount: 10,
        duration: 5,
        duration_unit: 't',
        symbol: 'R_10',
        basis: 'stake',
    });
    const buy = await contract.buy();

}
}
out put only buy 1 time and stop
Your current balance is: USD 13,473.93
buy and loss
Your current balance is: USD 13,463.93

what im did wrong? all follow example script

Support for trade types such as rise/fall and matches/differs

Can anyone suggest an approach to incorporate various trade types like "rise/fall" and "matches/differs" using the deriv API library? If you have any ideas, kindly share a code snippet or provide guidance on how to implement these trade types effectively. Your guidance on integrating these trade types would be much appreciated.

Question about js-interpreter in npm -- from the js-interpreter team

Hi Amin,

I apologise for contacting you here, but I just couldn't find your email address anywhere.

We would like to manage our own NPM packge releases for JS-Interpreter. At the moment, anybody using NPM would assume your package is the official one -- although it's a fork, and it hasn't been updated for about 3 years.

Would it be OK for you to hand over the js-interpreter NPM domain so that we can start using it?

Sorry to pollute this unrelated issue list again.

We haven't updated our homepage yet, but will do that once we get an answer from you.

Thank you!

Merc.

How do I use decimal values?

I tried to use a value as in the example but Deriv did not recognize decimal numbers. What do I do?

const stream_src = api.basic.subscribe(
            {
                    amount: 0.35,
                    basis: 'stake',
                    contract_type: 'CALL',
                    proposal: 1,
                    subscribe: 1,
                    currency: 'USD',
                    duration: 100,
                    symbol: 'frxUSDJPY',
            }
        );
// listen for updates, filter those which have payouts greater than 18
const response = await stream_src.pipe(filter(item => item.payout > 18)).toPromise();
console.log(response);

Originally posted by @salar-fs in #43 (comment)

TypeError: account.contract is not a function

const account = await api.account(token);
const contract = account.contract({ 
    contract_type: 'CALL',
    amount: 10,
    duration: 5,
    duration_unit: 't',
    symbol: 'frxUSDJPY',
    basis: 'stake'
 });

Error when trying to access contract from account

paymentagentTransfer example

hello, want to inquire about paymentagentTransfer is it about the new DP2P way of transfer or not, i need some sort of making payment transfers with the api. Wanted to know with an example if it is the same thing as doing DP2P

api.contract blocks after requests of the same contract type

hello, if I make 2 requests in a row on the same connection with the same contract_type, the second call blocks
await api.contract({ contract_type: curTradeType, symbol: 'R_10', duration: 5, duration_unit: 't', barrier: barrierOffset, basis: 'stake', currency: 'USD', amount: 50 });

If I make two 'CALL' requests, the first on is successful but the second one blocks with no response at all, not even an error message.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.