Created
September 1, 2020 14:00
-
-
Save robertkowalski/1cc7b7f0e5bae90728dcd344d2074273 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const dazaar = require('dazaar') | |
const swarm = require('dazaar/swarm') | |
const Hyperbee = require('hyperbee') | |
const times = { | |
'1m': 60 * 1000, | |
'5m': 5 * 60 * 1000, | |
'15m': 15 * 60 * 1000, | |
'30m': 30 * 60 * 1000, | |
'1h': 60 * 60 * 1000, | |
'3h': 3 * 60 * 60 * 1000, | |
'6h': 6 * 60 * 60 * 1000, | |
'12h': 12 * 60 * 60 * 1000, | |
'1D': 24 * 60 * 60 * 1000, | |
'7D': 7 * 24 * 60 * 60 * 1000, | |
'14D': 14 * 24 * 60 * 60 * 1000, | |
'1M': 30 * 24 * 60 * 60 * 1000 | |
} | |
const timesReverse = { | |
[60 * 1000]: '1m', | |
[5 * 60 * 1000]: '5m', | |
[15 * 60 * 1000]: '15m', | |
[30 * 60 * 1000]: '30m', | |
[60 * 60 * 1000]: '1h', | |
[3 * 60 * 60 * 1000]: '3h', | |
[6 * 60 * 60 * 1000]: '6h', | |
[12 * 60 * 60 * 1000]: '12h', | |
[24 * 60 * 60 * 1000]: '1D', | |
[7 * 24 * 60 * 60 * 1000]: '7D', | |
[14 * 24 * 60 * 60 * 1000]: '14D', | |
[30 * 24 * 60 * 60 * 1000]: '1M' | |
} | |
const keyEncoding = { | |
encode (range) { | |
if (typeof range === 'number' || range.getTime) { | |
range = { timestamp: range } | |
} | |
return Buffer.from(range.candle | |
? 'c!' + (times[range.candle] || range.candle) + '!' + toMS(range.timestamp || 0) | |
: 't!' + toMS(range.timestamp || 0)) | |
}, | |
decode (bytes) { | |
const key = bytes.toString() | |
if (key[0] === 't') { | |
return { | |
candle: null, | |
timestamp: new Date(Number(key.slice(2))) | |
} | |
} | |
const [candle, timeStr] = key.slice(2).split('!') | |
return { | |
candle: timesReverse[candle], | |
timestamp: new Date(Number(timeStr)) | |
} | |
} | |
} | |
function toMS (s) { | |
return typeof s === 'number' | |
? s | |
: s.getTime() | |
} | |
const tke = keyEncoding // require('./_ke') | |
const market = dazaar('dbs/full-trades') | |
const id = Buffer.from('8fa60e1175030033b6259a0850e8553248ec4302cab36d022cdf2f997d87e04f', 'hex') | |
const buyer = market.buy(id, { live: true, sparse: false }) | |
buyer.on('feed', function () { | |
console.log('got feed') | |
const db = new Hyperbee(buyer.feed, { | |
keyEncoding: tke, | |
valueEncoding: 'json' | |
}) | |
doQuery(db) | |
}) | |
function doQuery (db) { | |
db.createReadStream({ | |
lte: { timestamp: new Date('2019-10-10T09:00:00.000Z') }, | |
limit: 10, | |
reverse: true | |
}).on('data', (d) => { | |
console.log(d) | |
}) | |
} | |
swarm(buyer) | |
setInterval(() => { | |
if (!buyer.feed) return | |
console.log('data feed length is', buyer.feed.length, 'elements') | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment