dutu / poloniex-api-node Goto Github PK
View Code? Open in Web Editor NEWPoloniex API client for REST and WebSocket API
Home Page: https://www.npmjs.com/package/poloniex-api-node
License: MIT License
Poloniex API client for REST and WebSocket API
Home Page: https://www.npmjs.com/package/poloniex-api-node
License: MIT License
I am subscribing USDT_BTC market, I get the ordermodify and orderremove messages but not newTrade message.
Hello everyone,
I'm trying to make the function returnLendingHistory work from the lib poloniex.js
I've attached the file concerned, I do not have any error message so I assume that the "start" and "end" parameter are correctly defined
The only thing is that I do not get any value returned when trying this example:
$node myExample1.js
$[ ]
Does anyone have an example that is working?
Thank you
yendor987
I have had several API calls rejected because of a nonce
with a smaller number than the previous. Is there a reason you went with the npm nonce
library instead of just using new Date().getTime()
?
Example error I am getting:
{
error: 'Nonce must be greater than 149394554342600. You provided 149394554342500.'
}
Steps to reproduce:
/node_modules/poloniex-api-node/lib/poloniex.js:603
currencyPair: markets.byID[rawData[0]].currencyPair,
^
UPDATE *** -always happens when rawData[0] = 200
I don't know if it my implementation mistake, but I am running into nonce problems very often.
I check the ticker every 1.5s and when certain cenario appear I make a buy. Sometimes i might send 5 buys every 1.5s and that's where i got into problems like sending the same nonce in every request and getting mutiple EQUAL erros like these:
Error: Poloniex error 422: . Nonce must be greater than 149973383738800. You provided 149973383730200.
also, I use one API key for each action: one for ticker, one for buy, one for checking balance, etc.
Salut, thanks for releasing this library.
How does it compare with more established libraries?
Background: https://pinboard.in/u:dandv/b:19ae24e7f634
Hi
Did Poloniex change something on WS API (version 2). Following does not seem to work anymore
//const Poloniex = require ('poloniex-api-node');
const Poloniex = require ('../lib/poloniex.js');
let poloniex = new Poloniex();
poloniex.subscribe('USDT_BTC');
poloniex.on('message', (channelName, data, seq) => {
if (channelName === 'USDT_BTC') {
console.log(`order book and trade updates received for currency pair ${channelName}`);
console.log(`data sequence number is ${seq}`);
}
});
poloniex.on('open', () => {
console.log(`Poloniex WebSocket connection open`);
// after 10s unsubscribe from market
setTimeout(function(){
console.log('Unsubscribing...');
//poloniex.unsubscribe('USDT_BTC');
}, 10000);
});
poloniex.on('close', (reason, details) => {
console.log(`Poloniex WebSocket connection disconnected`);
});
poloniex.on('error', (error) => {
console.log(`An error has occured`);
});
poloniex.openWebSocket({version:2});
I keep receiving orderbook updates. Anybody experiences the same ?
Thanks
BTC_STORJ was added a few months ago and its id is 200.
Hi,
I am getting an ESOCKETTIMEDOUT error when using private API methods (e.g. returnBalances). I do not get this error when using public API methods (e.g. returnOrderBook). Increasing the timeout option on the request to something like 30000ms fixes this for me. I never got this error before the past few weeks.
I'm not sure if this is related to recent Poloniex DDOS mitigation measures. Sometimes (~10% of the time) I can get a response without increasing the timeout. But more often, the request times out before Poloniex sends the response.
Here's my fix below:
// Make an API request
options.timeout = 30000; //was 3000ms
This is not an ideal fix. Any thoughts?
I am receiving this error while executing private apis
Poloniex error 422: . Nonce must be greater than 150711082672900. You provided 150711082671300.
Due to problems with Wamp api, I'm considering switching to pure Web Socket api2. Just looked through the code and this dictionary confused me:
const ws2SubscriptionToChannelIdMap = {
trollbox: 1001,
ticker: 1002,
footer: 1003,
heartbeat: 1010,
};
Does it mean there's no subscription for orderbook and trades (snapshot and updates)? It would be weird as I've heard Poloniex uses api2 on their main page which does have orderbook and trades information.
https://github.com/dutu/poloniex-api-node/blob/master/lib/poloniex.js#L684
If msg[2]
is undefined, this crashes.
The error with Nonce you do not work in any way?
Error: Poloniex error 422: Nonce must be greater than 1492403545596268. You provided 149266840128300.
There is also no possibility to set it manually. How can I fix it?
In your code,
_private: function(command, parameters, callback){
let param = parameters;
param.nonce = nonce (16);
Closed for manual update in case of such an error.
Can you handle this error yourself or add an set-nonce method?
set-nonce: (nonce) !->
@poloniex.nonce = nonce
I received the error after making a buy REST call. All public API call worked just fine and no error related to API key and secret. I've also tried creating new API key and secret.
The error happened after I make a test call using the code below:
_poloniex.buy({
currencyPair: 'BTC_BCH',
rate: 0.058,
amount: 1,
}).then(msg => console.log(msg.body))
.catch(err => console.log(err))
Complete error messages below:
Error: Poloniex error 422: . Invalid currencyPair parameter.
at Request._callback (/Users/user_a/poloniex_project/node_modules/poloniex-api-node/lib/poloniex.js:161:18)
at Request.self.callback (/Users/user_a/poloniex_project/node_modules/request/request.js:186:22)
at Request.emit (events.js:159:13)
at Request. (/Users/user_a/poloniex_project/node_modules/request/request.js:1163:10)
at Request.emit (events.js:159:13)
at IncomingMessage. (/Users/user_a/poloniex_project/node_modules/request/request.js:1085:12)
at Object.onceWrapper (events.js:254:19)
at IncomingMessage.emit (events.js:164:20)
at endReadableNT (_stream_readable.js:1062:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
getting Poloniex error 403: Forbidden on all api
/node_modules/poloniex-api-node/lib/poloniex.js:48
class Poloniex extends EventEmitter {
^^^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
I'm running the example ws1.js but I am unable to get a connection. As soon as I try to open the close handler gets called over and over so my output is:
Poloniex WebSocket connection disconnected unreachable
I tried putting the subscribe calls within the open handler but it didn't help.
My code is now as follows:
const Poloniex = require('poloniex-api-node')
let poloniex = new Poloniex()
poloniex.on('message', (channelName, data, seq) => {
if (channelName === 'ticker') {
console.log(`Ticker: ${data}`)
}
if (channelName === 'BTC_ETH') {
console.log(`order book and trade updates received for currency pair ${channelName}`)
console.log(`data sequence number is ${seq}`)
}
})
poloniex.on('open', () => {
poloniex.subscribe('ticker')
poloniex.subscribe('BTC_ETH')
console.log('Poloniex WebSocket connection open')
})
poloniex.on('close', (reason, details) => {
console.log('Poloniex WebSocket connection disconnected ' + reason)
})
poloniex.on('error', (error) => {
console.log('An error has occured')
})
poloniex.openWebSocket()
error Error: SSL Error: https://poloniex.com/public?command=returnCurrencies does not support SSL
I've seen other libraries comment on this error. Any suggestions to fix?
My code below is not receiving any BTC_ETH messages when I use version 2 as an option for 'openWebSocket'.
I receive the console message "Poloniex WebSocket connection open", but never receive anything after subscribing to BTC_ETH. However, if I take away the version 2 option, these messages come through. What should be different here to receive messages when opening a web socket with version 2?
Thanks in advance
`
poloniex.subscribe('BTC_ETH');
poloniex.on('message', (channelName, data, seq) => {
console.log("Message Received");
if (channelName === 'BTC_ETH') {
console.log('order book and trade updates received for currency pair ', channelName);
console.log('data sequence number is ', seq);
}
});
poloniex.on('open', () => {
console.log('Poloniex WebSocket connection open');
});
poloniex.on('close', (reason, details) => {
console.log('Poloniex WebSocket connection disconnected');
});
poloniex.on('error', (error) => {
console.log('An error has occured');
});
poloniex.openWebSocket({ version: 2 });
`
Would be nice, since you're using ES6 already. Thank you for your work!
I use poloniex-api-node to subscribe to ticker events using openWebSocket({ version: 2 }) method.
From time to time node app exits after such error:
node[15508]: /app/node_modules/poloniex-api-node/lib/poloniex.js:601
node[15508]: this.ws.send('.')
node[15508]: ^
node[15508]: TypeError: Cannot read property 'send' of null
node[15508]: at Timeout.ws.keepAliveId.setInterval [as _onTimeout] (/app/node_modules/poloniex-api-node/lib/poloniex.js:601:24)
node[15508]: at ontimeout (timers.js:469:11)
node[15508]: at tryOnTimeout (timers.js:304:5)
node[15508]: at Timer.listOnTimeout (timers.js:264:5)
Current workaround is to restart node app after every exit.
Cannot read property 'error' of undefined
/home/shura/bots/app-trader-master/node_modules/poloniex-api-node/lib/poloniex.js:63
err = new Error(`Poloniex error ${response.statusCode}: ${response.body.error || response.body}`);
^
at Request._callback (/home/shura/bots/btce-app-trader-master/node_modules/poloniex-api-node/lib/poloniex.js:63:93)
at Request.self.callback (/home/shura/bots/app-trader-master/node_modules/request/request.js:188:22)
In poloniex.js Line 63:
err = new Error(`Poloniex error ${response.statusCode}: ${response.body}` );
should be:
err = new Error(`Poloniex error ${response.statusCode}: ${JSON.stringify(response.body) }`);
Same with line 71, otherwise error output is [object Object]
rather than {"error":"errorcode."}
Is there a documented way to authenticate and subscribe for private channels (like order events) in the websocket?
Is there a way to call the private version? Perhaps there can be a differentiation between each?
I know this is most likely not on your side but I have to ask because I am not seeing this anywhere.
It looks like today, 6/6/2017, and yesterday during the day 6/5//2017 there was a massive problem with the poloniex servers. (The servers were fine last night)
Nearly all requests returned with a ESOCKETTIMEDOUT error, and after a couple or a few of these, results in a 2 minute ban.
I am handling the bans gracefully so that the next call waits the ban time and I add 10 seconds to all my calls. (Example: I run the program every 30 seconds which should be enough. If there is a ban, I than run my program at 40 seconds. This got up to 200 seconds so something is massively wrong with poloniex servers)
I just am trying to think of all edge cases and wanted to make sure it is not poloniex-api-node which is failing but the poloniex servers as I think.
Also, is anyone else experiencing this or am I going crazy over here? It's always been a little shaky but this time is different.
Thanks.
When using returnLendingHistory with the end parameter higher than the last lending record the api returns an empty array.
For example in my account the last closed lending is at 10/06/2017 but if I try to pass as the end parameter 11/06/2017 it all of a sudden returns an empty array
any idea why?
As the title says: Does Websocket v2 support trade/order updates for my own orders and if so, does anyone know the channel names?
_poloniex.moveOrder(order_number, rate, amount).then((msg) => {
console.log(msg);
}).catch(err => console.log(err)); //this line throws error "Invalid currency pair".
I'm currently having a hard time debugging this part of the code, which is currently breaking my whole application because of it throwing an "invalid currency pair" error. I'm not sure why that is happening, and not aware of additional parameter of currency pair string as a missing required parameter I assume causing this error.
Error message:
Error: Invalid currency pair.
at Request._callback (/Users/user_1/person/myapp/node_modules/poloniex-api-node/lib/poloniex.js:183:17)
at Request.self.callback (/Users/user_1/person/myapp/node_modules/request/request.js:186:22)
at Request.emit (events.js:159:13)
at Request.<anonymous> (/Users/user_1/person/myapp/node_modules/request/request.js:1163:10)
at Request.emit (events.js:159:13)
at IncomingMessage.<anonymous> (/Users/user_1/person/myapp/node_modules/request/request.js:1085:12)
at Object.onceWrapper (events.js:254:19)
at IncomingMessage.emit (events.js:164:20)
at endReadableNT (_stream_readable.js:1062:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
This part also never caused issue when I was testing out last week, where my app ran just fine. This seems to be a recent issue (happening since yesterday). Please advise. thanks.
Error: Not enough BTS.
at Request._callback (/Applications/MAMP/htdocs/btc-e/node_modules/poloniex-api-node/lib/poloniex.js:69:27)
at Request.self.callback (/Applications/MAMP/htdocs/btc-e/node_modules/request/request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:194:7)
at Request.<anonymous> (/Applications/MAMP/htdocs/btc-e/node_modules/request/request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:191:7)
at IncomingMessage.<anonymous> (/Applications/MAMP/htdocs/btc-e/node_modules/request/request.js:1091:12)
at Object.onceWrapper (events.js:293:19)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Hi,
The documentation says that when subscribing to a currency pair (version 2), the orderbook message type should be emitted:
"orderBook (v2 only)
Provides a snapshot of the order book for the subscribed currency pair. The message is emitted immediately after subscription to the currency pair is activated."
However, I never receive this type. Can anyone confirm that they are indeed getting this type. Code is shown below. Thanks
`poloniex.on('message', (channelName, data, seq) => {
console.log("Message Received: ", channelName, seq);
for (var i = 0; i < data.length; i++){
console.log("type: ", data[i].type);
}
if (channelName === 'BTC_ETH') {
}
});
poloniex.on('open', () => {
console.log('Poloniex WebSocket connection open');
});
poloniex.on('close', (reason, details) => {
console.log('Poloniex WebSocket connection disconnected:', reason, details);
});
poloniex.on('error', (error) => {
console.log('An error has occured');
});
poloniex.openWebSocket({version: 2});
poloniex.subscribe('BTC_ETH');`
Hi everyone,
I clone this example on local and run it after that I have to receive an error "Socket Closed."
`const Poloniex = require ('poloniex-api-node');
const SocksProxyAgent = require('socks-proxy-agent');
const proxy = 'socks://localhost:1080';
let agent = new SocksProxyAgent(proxy);
let poloniex = new Poloniex('', '', {agent: agent});
poloniex.subscribe('ticker');
poloniex.subscribe('BTC_ETH');
poloniex.on('message', (channelName, data, seq) => {
if (channelName === 'ticker') {
console.log(Ticker: ${JSON.stringify(data)}
);
}
if (channelName === 'BTC_ETH') {
console.log(`order book and trade updates received for currency pair ${channelName}`);
console.log(`data sequence number is ${seq}`);
}
});
poloniex.on('open', () => {
console.log(Poloniex WebSocket connection open
);
});
poloniex.on('close', (reason, details) => {
console.log(Poloniex WebSocket connection disconnected
);
});
poloniex.on('error', (error) => {
console.log(An error has occur: ${error}
);
});
poloniex.openWebSocket({ version: 2 });`
Please help me check this error!
Thanks for the support!!!
im trying out the node api.
after npm i install, i would type
node my-rest.js
and returns the following error:
tradingApi.js:4
const create = (apiKey, secret, debug = false) => {
^
SyntaxError: Unexpected token =
Not really an issue, nor a bug, but the Poloniex API doesn't like to be called more then 8 times per second.
I have tweeked my copy of your excellent script to use throttled-request (found through NPM) which wraps request with a throttling mechanism.
It may very well be that my implementation is not the way you would want to go, but I have included my patched copy just as an example.
poloniex.js.txt
I am using the module in version 1.8.1(downloaded by npm install --save poloniex-api-node) and writing a code as below:
'use strict';
const Poloniex = require('poloniex-api-node');
let poloniex = new Poloniex();
var btc_ltc = null;
poloniex.on('open', () => {
console.log(`WebSocket connection has be opened.`);
poloniex.subscribe('ticker');
poloniex.on('message', (channelName, data) => {
if (channelName === 'ticker') {
if (data['currencyPair'] === 'BTC_LTC') {
btc_ltc = {
"currencyPair": data['currencyPair'],
"last": data['last'],
"lowestAsk": data['lowestAsk'],
"highestBid": data['highestBid'],
"percentChange": data['percentChange'],
"baseVolume": data['baseVolume'],
"quoteVolume": data['quoteVolume'],
"isFrozen": data['isFrozen'],
"24hrHigh": data['24hrHigh'],
"24hrLow": data['24hrLow']
}
}
}
});
});
The problem is that it works perfectly for a few hours on, but nothing happens to the server close and issue this error below:
Example app listening on port 3000!
WebSocket connection has be opened.
events.js:165
throw er; // Unhandled 'error' event
^
Error: read ETIMEDOUT
at TLSWrap.onread (net.js:599:25)
Emitted 'error' event at:
at WebSocket.ws.onerror.args (/home/mycomputer/robotpoloniex/server/node_modules/poloniex-api-node/lib/poloniex.js:745:20)
at WebSocket.onError (/home/mycomputer/robotpoloniex/server/node_modules/ws/lib/EventTarget.js:109:16)
at WebSocket.emit (events.js:180:13)
at WebSocket.finalize (/home/mycomputer/robotpoloniex/server/node_modules/ws/lib/WebSocket.js:182:41)
at TLSSocket.emit (events.js:180:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:114:19)
i have placed a limitBuy order which returns this response:
{ info:
{ timestamp: 1519480276683,
status: 'open',
type: 'limit',
side: 'buy',
price: 1e-8,
amount: 10000,
orderNumber: '19640401965',
resultingTrades: [] },
id: '19640401965',
timestamp: 1519480276683,
datetime: '2018-02-24T13:51:16.683Z',
status: 'open',
symbol: 'DOGE/BTC',
type: 'limit',
side: 'buy',
price: 1e-8,
cost: 0,
amount: 10000,
filled: 0,
remaining: 10000,
trades: [],
fee: undefined }
immediately i check for open orders which returns empty array and my full balance also there.
Code i used
let polo = new ccxt.poloniex({
apiKey: "******",
secret: "******",
nonce: () => nonce() * 10,
});
const symbol = 'DOGE/BTC';
const orderType = 'limit';
const side = 'buy';
const amount = 10000;
const price = 0.00000001;
polo.createLimitBuyOrder(symbol, amount, price).then(res => console.log(res));
I am trying to connect to websocket, but it's returning 403 error with version 2 and not reachable on version 1
It is logging that "Poloniex websocket connected" but there is no incoming messages altough subscribed.
EDIT:
I checked examples and version 2 is working. sorry.
Final Edit: ok this is a timing issue. I pulled the header from the request response and dropped that into a browser. At first I got an empty page. I went to compare the header href to the one below to see what was different. The only difference is the position of the command tag. When I went back to the web page it had populated with data. At any rate, here is the header pulled from the response in the API.
{"statusCode":200,"body":[],"headers":{"date":"Mon, 05 Feb 2018 06:11:18 GMT","content-type":"application/json","transfer-encoding":"chunked","connection":"keep-alive","set-cookie":["__cfduid=d62fed55e290841d93d9986017a75f20c1517811078; expires=Tue, 05-Feb-19 06:11:18 GMT; path=/; domain=.poloniex.com; HttpOnly"],"access-control-allow-origin":"*","access-control-allow-methods":"GET","expect-ct":"max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"","server":"cloudflare","cf-ray":"3e83b6294f0b58a9-DFW"},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"poloniex.com","port":null,"hostname":"poloniex.com","hash":null,"search":"?currencyPair=USDT_BTC&start=1517811078&end=1517831078&limit=300&command=returnTradeHistory","query":"currencyPair=USDT_BTC&start=1517811078&end=1517831078&limit=300&command=returnTradeHistory","pathname":"/public","path":"/public?currencyPair=USDT_BTC&start=1517811078&end=1517831078&limit=300&command=returnTradeHistory","href":"https://poloniex.com/public?currencyPair=USDT_BTC&start=1517811078&end=1517831078&limit=300&command=returnTradeHistory"},"method":"GET","headers":{"User-Agent":"poloniex-api-node 1.6.5","Connection":"keep-alive","accept":"application/json"}}}
edit:
Tracking this deeper. The API is seeing the right options, the following is pulled from the request() on options.qt :
{"currencyPair":"USDT_BTC","start":1517809825,"end":1517829825,"limit":300,"command":"returnTradeHistory"}
You can put those directly into the the web request html and they work. I print the body body before the callback in request() just to see if we get anything back there and it's the same empty array. Could this be a timing issue where the API isn't waiting long enough for a full response from the web request?
edit:
I know Polo is working just tried a web request and it worked: https://poloniex.com/public?command=returnTradeHistory¤cyPair=USDT_BTC&start=1517808279&end=1517828279
original:
I have tried increasing the start and stop times and limit to no avail. It managed to return 2 completed orders on one run but nothing since. Has Polo moved all of its trade history to a stream? I haven't tried subscribing to a stream yet. Code below in case you see if I'm doing something wrong.
`
function PullTradeHistory(pair, callback){
var startTime = ~~(Date.now()/1000);
var endTime = startTime + 2000000;
console.log(startTime);
console.log(endTime);
console.log(pair);
poloniex.returnTradeHistory(pair, startTime, endTime, 300, function(err, completedTrades){
if(err){
//handle error
}
else{
console.log("getting completed trades back");
console.log(JSON.stringify(completedTrades));
console.log(JSON.stringify(err));
callback(err, completedTrades);
}
});
};
`
output:
1517807472
1519807472
USDT_BTC
getting completed trades back
[ ]
null
When I try to run the ws2.js it gives 403 forbidden error.
where I am getting wrong?
Hey, I keep getting a 403 error which returns the security check screen. Is there some way to get around this? Have you encountered this when using your wrapper?
Poloniex error 422: . Nonce must be greater than 1515827307860912000. You provided 151582954164400.
I believe that new format is nonce(20) instead of the nonce(16).
Could you please fix it?
I wonder if you have some way to test the API in an approval environment to test the features before putting into production.
Please add an param 'limit' in method returnMyTradeHistory
returnTradeHistory
You may optionally limit the number of entries returned using the "limit" parameter, up to a maximum of 10,000. If the "limit" parameter is not specified, no more than 500 entries will be returned.
https://poloniex.com/support/api/
Hi,
ws2.js
after printing out Poloniex WebSocket connection open
, no real time update comes back.
I recently started to receive this error.
Poloniex error 422: . Nonce must be greater than 9020150321878175800. You provided 150334380587500.
When calling returnDepositAddresses(), for currencies that use address tags like Stellar (STR), only the tag is being returned rather than both the tag and the address.
Also, I'm not sure if withdraw() supports passing through an address tag? If so, it is not documented.
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.