From 7a65dbdcf41827def41351a7086537456ef4626f Mon Sep 17 00:00:00 2001 From: Stefan Thomas Date: Tue, 12 Mar 2013 13:59:21 +0100 Subject: [PATCH] JS: Emit orderbook events when trades happen. --- src/js/amount.js | 4 +++- src/js/orderbook.js | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/js/amount.js b/src/js/amount.js index 5a121d4f4..6302c39b0 100644 --- a/src/js/amount.js +++ b/src/js/amount.js @@ -98,6 +98,8 @@ Amount.prototype.abs = function () { Amount.prototype.add = function (v) { var result; + v = Amount.from_json(v); + if (!this.is_comparable(v)) { result = Amount.NaN(); } @@ -779,7 +781,7 @@ Amount.prototype.set_issuer = function (issuer) { // Result in terms of this' currency and issuer. Amount.prototype.subtract = function (v) { // Correctness over speed, less code has less bugs, reuse add code. - return this.add(v.negate()); + return this.add(Amount.from_json(v).negate()); }; Amount.prototype.to_number = function (allow_nan) { diff --git a/src/js/orderbook.js b/src/js/orderbook.js index a420fdf8f..150743b46 100644 --- a/src/js/orderbook.js +++ b/src/js/orderbook.js @@ -77,7 +77,7 @@ OrderBook.prototype = new EventEmitter; /** * List of events that require a remote subscription to the orderbook. */ -OrderBook.subscribe_events = ['transaction', 'model']; +OrderBook.subscribe_events = ['transaction', 'model', 'trade']; /** * Subscribes to orderbook. @@ -147,6 +147,13 @@ OrderBook.prototype.notifyTx = function (message) var changed = false; + var trade_gets = Amount.from_json("0" + ((this._currency_gets === 'XRP') ? "" : + "/" + this._currency_gets + + "/" + this._issuer_gets)); + var trade_pays = Amount.from_json("0" + ((this._currency_pays === 'XRP') ? "" : + "/" + this._currency_pays + + "/" + this._issuer_pays)); + message.mmeta.each(function (an) { if (an.entryType !== 'Offer') return; @@ -164,6 +171,13 @@ OrderBook.prototype.notifyTx = function (message) break; } } + + trade_gets = trade_gets.add(an.fieldsPrev.TakerGets); + trade_pays = trade_pays.add(an.fieldsPrev.TakerPays); + if (an.diffType === 'ModifiedNode') { + trade_gets = trade_gets.subtract(an.fieldsFinal.TakerGets); + trade_pays = trade_pays.subtract(an.fieldsFinal.TakerPays); + } } else if (an.diffType === 'CreatedNode') { var price = Amount.from_json(an.fields.TakerPays).ratio_human(an.fields.TakerGets); for (i = 0, l = self._offers.length; i < l; i++) { @@ -187,6 +201,7 @@ OrderBook.prototype.notifyTx = function (message) if (this._subs) { this.emit('transaction', message); if (changed) this.emit('model', this._offers); + if (!trade_gets.is_zero()) this.emit('trade', trade_pays, trade_gets); } };