Skip to content

Instantly share code, notes, and snippets.

@tiagosiebler
Last active September 25, 2018 16:14
Show Gist options
  • Save tiagosiebler/ffe9196330a56803f24eb7e3076ce7c3 to your computer and use it in GitHub Desktop.
Save tiagosiebler/ffe9196330a56803f24eb7e3076ce7c3 to your computer and use it in GitHub Desktop.
Download raw trades from the past 24 hours on binance
const api = require('binance');
const binanceRest = new api.BinanceRest({
timeout: 15000, // Optional, defaults to 15000, is the request time out in milliseconds
recvWindow: 10000, // Optional, defaults to 5000, increase if you're getting timestamp errors
disableBeautification: true,
handleDrift: true
});
const symbol = 'XRPUSDT';
const fromMS = 1537800990175;
const toMS = 1537887390175;
const ms = require('ms');
const hourMS = ms('1hour');
const query = {
symbol,
limit: 1000,
startTime: fromMS,
endTime: fromMS + hourMS,
};
const saveObjectToFile = require('./saveObjectToFile');
var tradesList = [];
const didFinishFetching = () => {
return saveObjectToFile(tradesList, `./data/${symbol}_f${fromMS}_t${toMS}.json`)
.then(() => console.log('done'));
}
const didReceiveData = (err, results) => {
if (err) debugger;
// do stuff with results, incl store in array
tradesList = [...tradesList, ...results];
// get timestamp for last trade returned by API
let lastResult = results[results.length - 1];
if (!lastResult && query.endTime == toMS) return didFinishFetching();
if (!lastResult) debugger;
let lastTS = lastResult.T;
// shift time range forward
query.startTime = lastTS + 1;
query.endTime = query.startTime + hourMS;
// exit condition
if (query.endTime == toMS) return didFinishFetching();
// final query might overlap into the future. That means we reached the end, so cap it with our target end range.
if (query.endTime > toMS) query.endTime = toMS;
// repeat execution
return executeNewQuery(query);
}
const executeNewQuery = (query) => {
binanceRest.aggTrades(query, didReceiveData);
}
executeNewQuery(query);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment