From 97deac7f201a192a36800d04c8cab2709ba862d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Ma=C5=82ecki?= Date: Fri, 25 Apr 2014 16:34:24 +0200 Subject: [PATCH] Add everything back for trading --- lib/trader.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/lib/trader.js b/lib/trader.js index 8e106924..43dcd0d2 100644 --- a/lib/trader.js +++ b/lib/trader.js @@ -79,6 +79,16 @@ Trader.prototype._consolidateTrades = function () { return tradeRec; }; +Trader.prototype._purchase = function (trade) { + var self = this; + self.rate(trade.currency, function (err, rate) { + self.tradeExchange.purchase(trade.satoshis, rate, function (err) { + // XXX: don't ignore purchase errors + self.pollBalance(); + }); + }); +}; + Trader.prototype.configure = function (config) { if (config.exchanges.settings.lowBalanceMargin < 1) { throw new Error('`settings.lowBalanceMargin` has to be >= 1'); @@ -201,12 +211,46 @@ Trader.prototype.trade = function (fiat, satoshis, currency, callback) { callback(null); }; +Trader.prototype.executeTrades = function () { + if (!this.tradeExchange) return; + + this.logger.info('checking for trades'); + + var trade = this._consolidateTrades(); + this.logger.info('consolidated: ', JSON.stringify(trade)); + + if (trade.fiat === 0) { + this.logger.info('rejecting 0 trade'); + return; + } + + if (trade.fiat < this.config.exchanges.settings.minimumTradeFiat) { + // throw it back in the water + this.logger.info('reject fiat too small'); + this._tradeQueue.unshift(trade); + return; + } + + this.logger.info('making a trade: %d', trade.satoshis / Math.pow(10, 8)); + this._purchase(trade); +}; + Trader.prototype.startPolling = function () { this.pollBalance(); this.pollRate(); + this.executeTrades(); this.balanceInterval = setInterval(this.pollBalance.bind(this), 60 * 1000); this.rateInterval = setInterval(this.pollRate.bind(this), 60 * 1000); + + // Always start trading, even if we don't have a trade exchange configured, + // since configuration can always change in `Trader#configure`. + // `Trader#executeTrades` returns early if we don't have a trade exchange + // configured at the moment. + this.tradeInterval = setInterval( + this.executeTrades.bind(this), + this.config.exchanges.settings.tradeInterval + ); }; Trader.prototype.stopPolling = function () {