Skip to content

Instantly share code, notes, and snippets.

@svasva
Last active December 21, 2015 14:19
Show Gist options
  • Save svasva/6318878 to your computer and use it in GitHub Desktop.
Save svasva/6318878 to your computer and use it in GitHub Desktop.
Meteor.publish 'order_book', (pairId) ->
return unless pairId
selector =
pairId: pairId
complete: false
cancelled: false
bids = {}
asks = {}
round = (amount, precision = 8) ->
Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision)
obs = Orders.find(selector).observe
added: (order) =>
h = if order.bid then bids else asks
rate = round(order.rate).noExponents()
if h[rate]
h[rate].amount = round(h[rate].amount + order.unmatchedAmount())
@changed('order_book', h[rate]._id , h[rate])
else
h[rate] =
_id: Random.id()
amount: order.unmatchedAmount()
bid: order.bid
rate: rate
@added('order_book', h[rate]._id , h[rate])
changed: (oldOrder, newOrder) =>
h = if oldOrder.bid then bids else asks
rate = round(oldOrder.rate).noExponents()
return if oldOrder.filled == newOrder.filled || !h[rate]
change = round(newOrder.filled - oldOrder.filled)
h[rate].amount = round(h[rate].amount + change)
if h[rate].amount > 0
@changed('order_book', h[rate]._id, h[rate])
else
@removed('order_book', h[rate]._id)
h[rate] = undefined
removed: (order) =>
h = if order.bid then bids else asks
rate = round(order.rate).noExponents()
return unless h[rate]
h[rate].amount = round(h[rate].amount - order.unmatchedAmount())
if h[rate].amount > 0
@changed('order_book', h[rate]._id, h[rate])
else
@removed('order_book', h[rate]._id)
h[rate] = undefined
@ready()
@onStop -> obs.stop()
Meteor.publish 'graph_data', (pairId) ->
data = {}
pub = @
round = (amount, precision = 8) ->
Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision)
handle = Trades.find({pairId: pairId}, {sort: {timestamp: 1}}).observe
added: (trade) ->
return unless trade.rate
rate = round(trade.rate)
minute = Math.round(trade.timestamp / (60 * 1000 * 5)) * (60 * 1000 * 5)
unless data[minute]?.o
newRec = true
data[minute] = {}
data[minute].o = rate
data[minute].h = rate unless data[minute].h > rate
data[minute].l = rate unless data[minute].l < rate
data[minute].c = rate
if newRec
pub.added('graph_data', minute, data[minute])
else
pub.changed('graph_data', minute, data[minute])
@onStop -> handle.stop()
@ready()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment