GithubHelp home page GithubHelp logo

binary-com / binary-live-api Goto Github PK

View Code? Open in Web Editor NEW
45.0 45.0 74.0 1.67 MB

JS library to consume Binary.com WebSocket API

Home Page: https://developers.binary.com

License: MIT License

JavaScript 99.84% Dockerfile 0.16%

binary-live-api's People

Contributors

4p00rv avatar afshin-deriv avatar aminmarashi avatar aminroosta avatar arun-deriv avatar ashkanx avatar balakrishna-deriv avatar borisyankov avatar cakasuma avatar chylli-deriv avatar dansallau avatar dependabot[bot] avatar gokula-krishna-dev avatar jy-deriv avatar khalid-deriv avatar mahboobeh-binary avatar martinov avatar mohammad-deriv avatar mustofa-binary avatar negar-binary avatar qingweibinary avatar raitucarp avatar shudarshon-deriv avatar thibault-deriv 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

Watchers

 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

binary-live-api's Issues

Simple trading example

Hi I am looking at using the Live API to rewrite some of my binary-bot CLI scripts into a webapp. I am really struggling to work out the basics of simply placing a trade. Below is a simple example of a CLI script I have. Is there something someone could share of a similar sort of thing using the live API, perhaps just as simple connect, get ticks, if last tick > previous tick place CALL else PUT. IJust something to help me get started with the API.


  symbol: 'R_100',

  candleInterval: 60,

  contractTypes: ['CALL', 'PUT'],

  shouldRestartOnError: 'true',

});



while (true) {

  Bot.start({

    amount: stake,

    currency: 'USD',

    duration: 3,

    duration_unit: 't',

  });



  //wait to get a trade signal - place trigger below here


  watch('before');



  if (Bot.getLastTick() > previousTick) {



    Bot.purchase('CALL');



  console.log('Purchased:', 'CALL -  - Direction is UP');

    

} else if (Bot.getLastTick() < previousTick) {



    Bot.purchase('PUT');



  console.log('Purchased:', 'PUT - Direction is DOWN');

    

} else {



    Bot.purchase('PUT');



  console.log('Purchased:', 'PUT - NO OTHER DATA');




}



  



  while(watch('during')) {

    if (Bot.isSellAvailable()) {

      previousTick = Bot.getLastTick();

      Bot.sellAtMarket()

      console.log('Contract Sold')

    }

  }



  // post trade calculations below here and before sleep()



  ladderProfit = (ladderProfit + Bot.readDetails(4));

  sessionProfit = (sessionProfit + Bot.readDetails(4));





if (sessionProfit > peakProfit) {



    peakProfit = sessionProfit



} else if (sessionProfit < worstProfit) {



    worstProfit = sessionProfit

}



if (sessionProfit < stopLoss) {



    console.log('Ladder Profit:', ladderProfit, '  ||  Ladders Completed: ', laddersCompleted, '  ||  Peak Profit: ', peakProfit, '  ||  Worst Profit: ', worstProfit,'  ||  Session Profit: ', sessionProfit);

    console.log('Bot Stopping...stop loss');

    Bot.stop();



	} else if (sessionProfit > takeProfit) {

	console.log('Bot Stopping...Take Profit');

	Bot.stop();


}



previousTick = Bot.readDetails(7);


// if ladder is complete, set stake to initial stake value (i.e. 0.35), otherwise change stake by mulitplier



  if (ladderProfit > (initialStake * 7.5)) {

      stake = initialStake

      ladderProfit = 0

      laddersCompleted ++
      
      NoOfTrades ++

  } else {

      stake = (stake * 1.05)
      
      NoOfTrades ++

  }

  console.log('=============================================================');
  console.log('||   Ladder Profit:', ladderProfit);
  console.log('||   Ladders Completed: ', laddersCompleted);
  console.log('||   Peak Profit: ', peakProfit);
  console.log('||   Worst Profit: ', worstProfit)
  console.log('||   Session Profit: ', sessionProfit);
  console.log('||   Number of Trades: ', NoOfTrades);
  console.log('||   Current Stake: ', stake);
  console.log('=============================================================');
  
  sleep(10) // Prevent max sell alert because of trading too fast


}


Many thanks!!

LiveApi.resubscribe crashes

I have implemented a small node.js based test application that subscribes to a symbol and logs all tick events. However, after running for a while it always crashes with the below error message:

/home/ubuntu/binary-options-trader/node_modules/binary-live-api/lib/binary-live-api.js:389
                    this.subscribeToTicks(Object.keys(ticks));
                                                 ^

TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at LiveApi.resubscribe (/home/ubuntu/binary-options-trader/node_modules/binary-live-api/lib/binary-live-api.js:389:43)
    at Timeout._onTimeout (/home/ubuntu/binary-options-trader/node_modules/binary-live-api/lib/binary-live-api.js:284:25)
    at tryOnTimeout (timers.js:224:11)
    at Timer.listOnTimeout (timers.js:198:5)

The ticks object is, actually, an empty dictionary, although it should contain one entry:
LiveSubscriptions { state: { ticks: {}, proposals: {} } }

new app markup call?

Hi there,

Please, could you give me an example for the new API call for gathering app markup details. I have a small mobile app I use to keep track of commissions and it's currently not working.

Please see the screenshot of chrome devtools from the app playground:
image

I am currently parsing the JSON via send raw to get a response. Could you let me know how I can get this information now?

 devParameters = {
        "app_markup_details": 1,
        "description": 1,
        "date_from": date_from,
        "date_to": date_to,
        "app_id": devAppID,
        "limit": 1000,
        "offset": offset,

        "sort_fields": [
            "app_id",
            "client_loginid",
            "transaction_time"
        ],
        "sort": "ASC",
        "req_id": 3,
        "passthrough": {}
    }

    api.authorize(devToken).then(function resolve(resp) {
        api.sendRaw(devParameters).then(function (response) {
        // some code here used to display the data
        });
    }).catch // blah blah

I then just run this on a loop with the offset to gather all trades.

Any help would be greatly appreciated.

Problem with app markup details

Hi,

I have an issue with checking the details of my app mark details, I have been doing test trade with the account shown below every day, but the last listed transaction is on the 09-05-2019. Is there a delay in this information being parsed, or is this a sign of a problem?

 {
        "app_id": "16261",
        "app_markup": "0.01",
        "app_markup_usd": "0.012991",
        "app_markup_value": "0.01000000000000000000",
        "client_currcode": "GBP",
        "client_loginid": "MX430**",
        "dev_currcode": "GBP",
        "dev_loginid": "MF15***",
        "transaction_id": "435634385",
        "transaction_time": "2019-05-09 13:26:43"
      }
    ]
  },
  "echo_req": {
    "app_id": 16261,
    "app_markup_details": 1,
    "date_from": "2019-04-01 00:00:00",
    "date_to": "2019-05-14 23:59:59",
    "description": 1,
    "limit": 1000,
    "offset": 0,
    "passthrough": {},
    "req_id": 3,
    "sort": "ASC",
    "sort_fields": [
      "app_id",
      "transaction_time"
    ]
  },
  "msg_type": "app_markup_details",
  "passthrough": {},
  "req_id": 3
}

Buy Contract for BTC Account

when I try to buy a contract on the BTC account, it returns this error:

Invalid amount. Amount provided can not have more than 2 decimal places.

I need help.

Error: unexpected server response (401)

Hello,

I'm experiencing a very strange issue with the binary-live-api library.

I attempted a test run using the following example code:

var ws = require('ws');
var LiveApi = require('binary-live-api').LiveApi;

var api = new LiveApi({ websocket: ws });
api.authorize('my token is here');
api.getPortfolio();
api.events.on('portfolio', function(data) {
    onsole.log(data);
});

Which resulted in this error:

Error: unexpected server response (401)
    at ClientRequest.options._req.on (/Users/FrancisJoseph/node_modules/ws/lib/WebSocket.js:650:26)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:472:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at TLSSocket.socketOnData (_http_client.js:361:20)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)

Any ideas?

bet put/call AUDJPY by api

how can i bet put/call using api?

In web socket traffic I found this, can I use it?

Where to get purchase-id?

  • {
    "buy": "12-34-12-34",
    "price": "10",
    "passthrough": {
    "display_value": "10",
    "payout": "18.69",
    "purchase-id": "12-34-12-34",
    "ask-price": "10",
    "symbol": "frxAUDJPY",
    "amount": "10",
    "basis": "stake",
    "contract_type": "PUT",
    "currency": "USD",
    "duration": "5",
    "duration_unit": "t",
    "product_type": "basic",
    "req_id": "33",
    "subscribe": "1"
    },
    "req_id": 36
    }

in official API https://developers.binary.com/api/#buy I find just strange Buy a Contract Send

image

Websocket error abortHandshake

I want to convert all my nodejs projects from using the api to using this api wrapper. But I cannot get past the first connection with this package.

I keep getting errors with the demo using yarn and npm:

yarn run v1.22.4
$ node node-demo.js
events.js:288
throw er; // Unhandled 'error' event
^

Error: Unexpected server response: 401
at ClientRequest. (C:\Users\binary-live-api-master\binary-live-api-master\demos\node\node_modules\ws\lib\websocket.js:579:7)
at ClientRequest.emit (events.js:311:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:603:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
at TLSSocket.socketOnData (_http_client.js:476:22)
at TLSSocket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at TLSSocket.Readable.push (_stream_readable.js:209:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:186:23)
Emitted 'error' event on WebSocket instance at:
at abortHandshake (C:\Users\binary-live-api-master\binary-live-api-master\demos\node\node_modules\ws\lib\websocket.js:693:15)
at ClientRequest. (C:\Users\binary-live-api-master\binary-live-api-master\demos\node\node_modules\ws\lib\websocket.js:579:7)
[... lines matching original stack trace ...]
at TLSSocket.Readable.push (_stream_readable.js:209:10)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

How can I fix this?

Any plans to allow date formatted values for getStatment date/time parameters?

Currently the Get Profit Table method can allow you to use a date formatted (YYYY-MM-DD) value for date_from and date_to.

Is there a reason why this isn't consistent for the Get Statement method?
Any plans on adding this feature for the Get Statement Method?

Just to note: Not a blocker but consistency would be nice

Regards

See screenshots below

Profit Table Docs
Get Statement Docs

VS

Get Statement Docs
Get Statement Docs

Anyone wanting to use the API

For anyone wanting to use a platform utilising this API. I have a web based and a NodeJS application using the API.

Please, feel to check it out. Also, if you have any question regarding usage, my source is un-minimised on the webtrader so you can copy snippets as you see fit.

Any nodeJS queries with app, I am closed source, but happy to help any new user trying to build something privately.

Will @ https://binarybottrading.com

Under knowledge there are also videos to help you 👍

Query about rate limits

Hi, I am building a desktop platform for trading with binary.com . while testing I sometime get the error

[ServerError] You have reached the rate limit for ticks_history.

Please, can you confirm if this is API token based or AppId based? I am assuming it is because I am using the same API token across a couple of computers while testing simultaneously, but I just want to be sure it is not something my user will experience unless they are using multiple instances.

i.e. the rate limit is on the API token or IP address, and not limited by the AppId which will be the same for every user who is using my platform.

Many thanks

Getting disconnected before response

Working on a NodeJs app to use the LiveAPI and after some hours placing trades, i got this message.

{ {"message":"Websocket disconnected before response received.","stack":[{"file":"/Users/exmachina/Github/binaryapp/node_modules/binary-live-api/lib/binary-live-api.js","column":37,"line":2680,"functionName":null},{"file":null,"column":null,"line":null,"functionName":"forEach"},{"file":"/Users/exmachina/Github/binaryapp/node_modules/binary-live-api/lib/binary-live-api.js","column":46,"line":2679,"functionName":"connect"},{"file":"/Users/exmachina/Github/binaryapp/node_modules/binary-live-api/lib/binary-live-api.js","column":31,"line":2693,"functionName":"socket.onclose"},{"file":"/Users/exmachina/Github/binaryapp/node_modules/ws/lib/WebSocket.js","column":14,"line":446,"functionName":"onClose"},{"file":"events.js","column":13,"line":125,"functionName":"emitTwo"},{"file":"events.js","column":7,"line":213,"functionName":"emit"},{"file":"/Users/exmachina/Github/binaryapp/node_modules/ws/lib/WebSocket.js","column":8,"line":950,"functionName":"cleanupWebsocketResources"},{"file":"events.js","column":13,"line":115,"functionName":"emitOne"},{"file":"events.js","column":7,"line":210,"functionName":"emit"},{"file":"internal/streams/destroy.js","column":8,"line":64,"functionName":"emitErrorNT"},{"file":"internal/process/next_tick.js","column":11,"line":138,"functionName":"_combinedTickCallback"},{"file":"internal/process/next_tick.js","column":9,"line":180,"functionName":"_tickCallback"}]} name: 'DisconnectError' }

Can someone help me avoid this? Happen every day at least 3 times. I'm only subscribed to balance and OpenContracts.

Authorization issue.

I´m trying to test the binary-live-api, using the code example of the github page, but I´m only getting error messages.

My code:

var ws = require('ws');
var LiveApi = require('binary-live-api').LiveApi;

var api = new LiveApi({ websocket: ws });
api.authorize('My token'');
api.getPortfolio();
api.events.on('portfolio', function(data) {
ping();
});

Error message of node:

(node:2756) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AuthorizationRequired: [ServerError] Please log in.
{
"portfolio": 1,
"req_id": 2
}

What should I do?

Thank you.

Error: Required is not defined

Hi im newbie to a programming and here I was trying to use the code given in the github which is :
var ws = require('ws');
var LiveApi = require('binary-live-api').LiveApi;

var api = new LiveApi({ websocket: ws, appId: my_id });
api.authorize('mytoken');
api.events.on('authorize', function(data) {
api.getPortfolio();
});
api.events.on('portfolio', function(data) {
console.log(data);
});

but then i see this error which is saying
Uncaught ReferenceError: require is not defined

can anyone explain to me whats the error means? thank you

Options for "Allow equals" in API

On binary.com web trading platform, there is an option to "Allow equals" when trading an UP/DOWN option.
How can this "Allow equals" be specified through the trading API?

dist folder

Hi boris,

I have tried to build this library.

cd binary-live-api && npm install && webpack

but webpack doesn't seem to recognize the webpack.config.js file.

Can you add the prebuild version (dist folder) ?
That way when we install it with bower we don't need to build it with webpack.
Thanks.

TypeError: api.cancel is not a function

How to use cancel functionality with binary-live-api?

async function main() {
    const api = new LiveApi({ ...options });
    try {
       const proposal = await api.subscribeToPriceForContractProposal({ ...proposalObj });
       const buy = await api.buyContract(proposal.proposal.id, proposal.proposal.spot);
       await api.cancel(buy.proposal_open_contract.contract_id);
    }
    catch(error) {
      console.log(error); // TypeError: api.cancel is not a function
    }
}

main();

Set limit in number of retries

  1. We should limit number of retries.
  2. If some cases, where apiURL is pointing to a deprecated endpoint, eg v2, it will return 301 permanently moved, in such case we might not want to retry

2 is something good to have but non-essential.

documentation misleading

i followed the documentation for using this in nodejs but was getting no response.

took me some time investigating the code to realise a couple things

  1. the constructor accepts an object where the ws library should be passed as the websocket property
  2. calls that require auth have to wait on confirmation before you can execute

so my code looks something like below

var ws = require('ws');
var LiveApi = require('binary-live-api').LiveApi;
var api = new LiveApi({websocket:ws});

api.authorize('XXXXXXXXXXXX').then(function(){

  api.getProfitTable()
  .then(function(results){
    console.log(results)
  });

});

while your documentation has

var ws = require('ws');
var LiveApi = require('binary-live-api').LiveApi;

var api = new LiveApi(ws);
api.authorize('yourtoken');
api.getPortfolio();
api.events.on('portfolio', function(data) {
    // do stuff with portfolio data
});

WebSocket faces many times timeout/disconnection

Hi,

I am using the websocket-client (as proposed in the examples on binary.com) in Python. After starting up the script, the websocket connection opens and I can start trading. I place trades every 20 seconds and I am subscribed to the trades as well. It's very random, but between 1 minute-20 minutes the connection is facing timeouts or is suddenly disconnected.

Are there any other people with similar issues? Is there a workaround?

Thanks!

Edit: i've tried it also using google colab, it gives the error [Errno 104] Connection reset by peer.
Edit2: trying now with a downgraded websocket client version 0.54.0

how to get parameters from transaction event

when i got an event with msg_type buy i got some data like this

"parameters":{  
         "amount":4.72,
         "app_markup_percentage":"0",
         "basis":"payout",
         "contract_type":"CALL",
         "currency":"USD",
         "duration":5,
         "duration_unit":"t",
         "symbol":"frxAUDJPY"
}

how can i get data like that, but from event transaction event ?

am i only get buy event after calling buy api ?
or can i get it too from other client ? like from binary.com website ?

Bug - Sorry, an error occurred while processing your request.

Placing the trade with
api.buyContractParams(params, limit).then(console.log).catch(error =>console.error(error.message))

go well for some period of time, but after several hours i got this error message

[ServerError] Sorry, an error occurred while processing your request.

why this occur everyday after some hours the server running? I'm using NodeJs.

this message appears together with this message below. I tried to find this promise rejection but i think is server related issue.

UnhandledPromiseRejectionWarning: {"message":"","stack":[{"file":"/app/node_modules/binary-live-api/lib/binary-live-api.js","column":23,"line":2768,"functionName":"ServerError"},{"file":"/app/node_modules/binary-live-api/lib/binary-live-api.js","column":39,"line":2405,"functionName":"LiveApi.resolvePromiseForResponse"},{"file":"/app/node_modules/binary-live-api/lib/binary-live-api.js","column":26,"line":2464,"functionName":"LiveApi.onMessage"},{"file":"/app/node_modules/ws/lib/event-target.js","column":16,"line":120,"functionName":"onMessage"},{"file":"events.js","column":13,"line":116,"functionName":"emitOne"},{"file":"events.js","column":7,"line":211,"functionName":"emit"},{"file":"/app/node_modules/ws/lib/websocket.js","column":20,"line":715,"functionName":"receiverOnMessage"},{"file":"events.js","column":13,"line":116,"functionName":"emitOne"},{"file":"events.js","column":7,"line":211,"functionName":"emit"},{"file":"/app/node_modules/ws/lib/receiver.js","column":14,"line":414,"functionName":"dataMessage"},{"file":"/app/node_modules/ws/lib/receiver.js","column":23,"line":371,"functionName":"perMessageDeflate.decompress"},{"file":"/app/node_modules/ws/lib/permessage-deflate.js","column":9,"line":307,"functionName":"_decompress"},{"file":"/app/node_modules/ws/lib/permessage-deflate.js","column":7,"line":389,"functionName":"_inflate.flush"},{"file":"_stream_writable.js","column":3,"line":464,"functionName":"afterWrite"},{"file":"_stream_writable.js","column":7,"line":455,"functionName":"onwrite"},{"file":"_stream_transform.js","column":3,"line":90,"functionName":"afterTransform"},{"file":"zlib.js","column":5,"line":515,"functionName":"callback"}]}

More explanation needed on how to use in Browser

I think more explanation is needed on how to use this library in browser. We have to be very flexible with libraries because libraries are not just meant for us(only), its for everybody who probably don't have much JS knowledge.

For example

Usage in the Browser

var api = new LiveApi();
api.authorize('yourtoken');
api.getPortfolio();
api.events.on('portfolio', function(data) {
// do stuff with portfolio data
});

I was assuming that, if I start a new simple HTML, JS project and I do npm install binary-live-api and then include the minified version of the js file from dist folder in my index.html, I can do new LiveApi() and start working with the API without getting into too much of the AMD world. But it failed and I was getting "Uncaught ReferenceError: LiveApi is not defined"

buyContract without proposing

The Binary.com API provides for the parameters option in the buy contract request, but with this API, buying can only be done after proposing.

Can we change this to the underlying API behaviour?

How to catch an error?

Could you provide onerror listener such as events.on("error", function(message)) ?

And where is the documentation of error messages and its code?

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.