Skip to content

Instantly share code, notes, and snippets.

@prdn
Created May 1, 2020 09:15
Show Gist options
  • Save prdn/9356798b30ffce60666781118985bd12 to your computer and use it in GitHub Desktop.
Save prdn/9356798b30ffce60666781118985bd12 to your computer and use it in GitHub Desktop.
bfx-market-data-mcast-udp.js
const dgram = require('dgram')
const UInt64BE = require('int64-buffer').Uint64BE
const BN = require('bignumber.js')
const _ = require('lodash')
const process = require('process')
const PORT = 30000
const MULTICAST_ADDR = '233.255.255.255'
const nBN = v => {
return new BN(v)
}
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true })
socket.bind(PORT)
const BOOKS = {}
socket.on('message', function(m, rinfo) {
const type = m.readUInt8(0)
const len = m.readUInt8(1)
if (type >= 20 && type < 30) {
const [seq, sym] = [
(new UInt64BE(m.slice(2, 10))).toNumber(),
m.readUInt32BE(10)
]
if (type >= 24 && type <= 25) {
const [active, oid, price, amount, sign] = [
m.readUInt8(14),
(new UInt64BE(m.slice(15, 23))).toString(),
nBN((new UInt64BE(m.slice(23, 31))).toString()).div(100000000).toNumber(),
nBN((new UInt64BE(m.slice(31, 39))).toString()).div(100000000).toNumber(),
m.readUInt8(39)
]
if (!BOOKS[sym]) {
return
}
const book = BOOKS[sym]
if (active) {
book[oid] = {
id: oid,
price: price,
amount: amount * (sign > 0 ? -1 : 1)
}
} else {
delete book[oid]
}
} else if (type === 21) {
BOOKS[sym] = {}
console.log('BOOK SNAP SYNC INIT', sym, seq)
} else if (type === 22) {
console.log('BOOK SNAP SYNC FINISH', sym)
}
} else if (type === 35) {
}
})
setInterval(() => {
_.each([1], sym => {
if (!BOOKS[sym]) {
return
}
_.each(['bid', 'ask'], side => {
console.log(side, _.filter(_.values(BOOKS[sym]), e => {
return side === 'bid' ? e.amount >= 0 : e.amount < 0
}).sort((a, b) => {
return side === 'bid' ? b.price - a.price : a.price - b.price
}).slice(0, 5))
})
})
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment