binary-com / binary-live-api Goto Github PK
View Code? Open in Web Editor NEWJS library to consume Binary.com WebSocket API
Home Page: https://developers.binary.com
License: MIT License
JS library to consume Binary.com WebSocket API
Home Page: https://developers.binary.com
License: MIT License
Guys,
I have received this error some times, can anyone help me how to identify how can I get this limit?
Can I trust the get_limits
API to give me that limit?
Thank you
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!!
If the user is subscribed to both ticks and candles (which is always the case in binary bot), after a reconnect only candle stream is recovered.
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: {} } }
Imagine you're buying a contract, a buy request is sent, right before getting the response your connection is lost, you should somehow become aware that this to investigate if you have to buy again or not.
If the connection is closed before the proposal_open_contract is sent live api is unable to resubscribe.
The reason is streamId is required to save the contracts: https://github.com/binary-com/binary-live-api/blob/master/src/ApiState.js#L40
@borisyankov I think it's worth fixing if we can make things a little bit better in the code, otherwise this is a very rare condition and is not of high priority.
Who can code in python for me,
login, and trade put call 5ticks.
Call> when ticks is Rising
Put > when tick is Falling
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:
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.
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
}
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.
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?
how can i bet put/call using api?
In web socket traffic I found this, can I use it?
Where to get purchase-id?
in official API https://developers.binary.com/api/#buy I find just strange Buy a Contract Send
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?
When I try to run my script..
Error: Cannot find module './LiveEvents'
but, its filename is liveevents.js
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
VS
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 👍
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
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.
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.
Can we get user id of logged account?
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
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?
Current stream subscription returns nothing and to handle it, callback is required, which is not ideal
Return an observable might make things better.
Possible candidates
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.
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();
Hi guys,
I have this new error in my apps come up, I don't see any outstanding terms approvals on my account, would you be bale to assist?
Many htanks,
Currently if I want to unsubscribe from candles I need to use send directly. But send is going to be deprecated.
301 permanently moved
, in such case we might not want to retry2 is something good to have but non-essential.
Hello,I want to connect my app_id obtained after registering my bot on Binary.com to their WebSocket API for auto trading and I was told I need a system build.
Please I need a step-by-step guide on how to build a system with Binary.com API Library on GitHub or a link to an already built system.
Thanks.
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
ws
library should be passed as the websocket
propertyso 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
});
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
{
"sell": "some ID from Price Proposal call",
"price": some price
}
Not working on the opening sell contract !
function subscribeToTransactions() {
api.events.on('transactions', function(response) {
console.log(response);
});
api.subscribeToTransactions();
}
I used this method ,
with this i can get if trade placed
but i want to copy that same trade to multiple account using Tokens
@martinov @raitucarp @borisyankov @raunakkathuria @aminroosta @gokula-krishna-dev
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 ?
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"}]}
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"
/del
Please help. where should i start using the live api binary
Have more questions?
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?
Is there a way to get trading durations like described in https://developers.binary.com/api/#trading_durations ?
Could you provide onerror listener such as events.on("error", function(message)) ?
And where is the documentation of error messages and its code?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.