Skip to content
Browse files

ported node-mtgox-websocket-client to use Socket.io instead of WebSoc…

…ket which is deprecated by mtgox
  • Loading branch information...
0 parents commit 8de538297ac8d29474e1c08f48d2565afd34bdab @olalonde committed
Showing with 322 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +26 −0 README.md
  3. +7 −0 config.json
  4. +159 −0 index.js
  5. +106 −0 mtgox.js
  6. +22 −0 package.json
2 .gitignore
@@ -0,0 +1,2 @@
+node_modules/
+*.log
26 README.md
@@ -0,0 +1,26 @@
+node-mtgox-websocket-client
+===========================
+
+A node.js websocket client for the MtGox bitcoin exchange.
+
+Installation
+------------
+
+$ npm install mtgox-websocket-client
+
+Contributors
+------------
+
+* [cronopio](https://github.com/cronopio)
+* [marak](https://github.com/marak)
+
+License
+-------
+
+Copyright 2011 Donald Ness
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7 config.json
@@ -0,0 +1,7 @@
+{
+ "channels": [
+ { "key":"dbf1dee9-4f2e-4a08-8cb7-748919a71b21", "private":"trade", "name":"Trade" },
+ { "key":"d5f06780-30a8-4a48-a2f8-7ed181b4a13f", "private":"ticker", "name":"Ticker" },
+ { "key":"24e67e0d-1cad-4cc0-9e7a-f8523ef460fe", "private":"depth", "name":"Market Depth" }
+ ]
+}
159 index.js
@@ -0,0 +1,159 @@
+var util = require('util');
+var colors = require('colors');
+var datetime = require('datetime');
+var mtgox = require('./mtgox');
+
+var lastTradePrice = -1;
+var lastTickerPrice = -1;
+var lastTickerVolume = -1;
+var client = mtgox.connect();
+
+client.on('open', function() {
+ // Good place to unsubscribe from unwanted channels
+ // client.unsubscribe(mtgox.getChannel('trade').key);
+ // client.unsubscribe(mtgox.getChannel('depth').key);
+ // client.unsubscribe(mtgox.getChannel('ticker').key);
+});
+
+client.on('subscribe', function(message) {
+ renderSubscribeMessage(message);
+});
+
+client.on('unsubscribe', function(message) {
+ renderUnsubscribeMessage(message);
+});
+
+client.on('trade', function(message) {
+ renderTradeMessage(message, lastTradePrice);
+ lastTradePrice = message.trade.price;
+});
+
+client.on('depth', function(message) {
+ renderDepthMessage(message);
+});
+
+client.on('ticker', function(message) {
+ renderTickerMessage(message, lastTickerPrice);
+ lastTickerPrice = message.ticker.last;
+ lastTickerVolume = message.ticker.vol;
+});
+
+process.on('exit', function() {
+ console.log('Goodbye!'.bold);
+ client.close();
+});
+
+var renderSubscribeMessage = function(message) {
+ var format = 'Subscribed to channel:'.green;
+ console.log(getTimeFormat(), format, getChannelFormat(message));
+};
+
+var renderUnsubscribeMessage = function(message) {
+ var format = 'Unsubscribed from channel:'.red;
+ console.log(getTimeFormat(), format, getChannelFormat(message));
+};
+
+var renderTradeMessage = function(message, lastPrice) {
+ console.log(getTimeFormat(), getTradeFormat(message.trade, lastPrice));
+};
+
+var renderTickerMessage = function(message, lastPrice) {
+ console.log(getTimeFormat(), getTickerFormat(message.ticker, lastPrice));
+};
+
+var renderDepthMessage = function(message) {
+ console.log(getTimeFormat(), getDepthFormat(message.depth));
+};
+
+var getDepthFormat = function(depth) {
+ var format = '';
+
+ if (depth.volume < 0) {
+ format += '+ '.grey;
+ }
+ else {
+ format += '- '.grey;
+ };
+
+ if (depth.type_str == 'ask') {
+ format += 'Ask: '.grey.bold;
+ }
+ else if (depth.type_str = 'bid') {
+ format += 'Bid: '.grey.bold;
+ }
+
+ var amount = Math.abs(depth.volume);
+ var price = Math.abs(depth.price);
+
+ format += (amount + ' ' + depth.item).yellow + ' @ ';
+ format += getPriceFormat(price, price, depth.currency);
+
+ return format;
+};
+
+var getTickerFormat = function(ticker, lastPrice) {
+ var format = '> ';
+
+ var last = 'Last: '.bold;
+ var high = 'High: '.bold;
+ var low = 'Low: '.bold;
+ var vol = 'Vol: '.bold;
+ var avg = 'Avg: '.bold;
+
+ last += getPriceFormat(ticker.last.display, lastPrice);
+ high += ticker.high.display;
+ low += ticker.low.display;
+ vol += ticker.vol.display;
+ avg += ticker.vwap.display;
+
+ return format + [vol, high, low, avg, last].join(' ');
+};
+
+var getTradeFormat = function(trade, lastPrice) {
+ var format = '$ ';
+
+ if (trade.trade_type == 'ask') {
+ format += 'Ask: '.bold;
+ }
+ else if (trade.trade_type == 'bid') {
+ format += 'Bid: '.bold;
+ }
+
+ format += (trade.amount + ' ' + trade.item).yellow + ' @ ';
+ format += getPriceFormat(trade.price, lastPrice, trade.price_currency);
+
+ return format;
+};
+
+var getChannelFormat = function(message) {
+ var channel = mtgox.getChannel(message.channel)||message.channel;
+ return channel.name.magenta;
+};
+
+var getTimeFormat = function() {
+ var now = new Date();
+ var time = '[' + datetime.format(now, '%T') + ']';
+ return time.blue;
+};
+
+var getPriceFormat = function(currentPrice, lastPrice, currency) {
+ var format = currentPrice + (currency ? ' ' + currency : '');
+ if (lastPrice < 0) {
+ return format;
+ }
+
+ var delta = lastPrice - currentPrice;
+ var percent = (lastPrice > 0) ? (delta / lastPrice) * 100 : 100;
+ var round = function(n) {
+ return Math.round(Math.abs(n) * 100) / 100;
+ };
+
+ if (delta > 0) {
+ format += (' \u25b2 +' + round(delta) + ' +' + round(percent) + '%').green;
+ }
+ else if (delta < 0) {
+ format += (' \u25bc -' + round(delta) + ' -' +round( percent) + '%').red;
+ }
+
+ return format;
+};
106 mtgox.js
@@ -0,0 +1,106 @@
+var util = require('util');
+var fs = require('fs');
+var events = require('events');
+var io = require('socket.io-client');
+
+var MTGOX_WEBSOCKET_URL = 'https://socketio.mtgox.com/mtgox';
+var MTGOX_CHANNELS = [];
+
+try {
+ var config = JSON.parse(fs.readFileSync('./config.json'));
+ if (Array.isArray(config.channels)) {
+ MTGOX_CHANNELS = config.channels;
+ }
+}
+catch(ex) {
+ util.debug(util.inspect(ex));
+ util.debug('Failed to parse config.json. No channels available.');
+}
+
+var getChannel = function(key) {
+ return MTGOX_CHANNELS.filter(function(channel) {
+ return (channel.key == key || channel.private == key);
+ })[0];
+};
+
+var MtGoxClient = function() {
+ events.EventEmitter.call(this);
+ var self = this;
+ var socket = io.connect(MTGOX_WEBSOCKET_URL);
+
+ var emitChannelMessage = function(message) {
+ var channel = getChannel(message.channel);
+ if (channel) {
+ self.emit(channel.private, message);
+ }
+ };
+
+ socket.on('message', function(raw) {
+ // Emit raw data
+ var data = raw;
+ self.emit('data', data);
+
+ // Emit JSON messages
+ var message = data;
+ self.emit('message', message);
+
+ if (message.op == 'subscribe') {
+ self.emit('subscribe', message);
+ }
+
+ if (message.op == 'unsubscribe') {
+ self.emit('unsubscribe', message);
+ }
+
+ if (message.op == 'private') {
+ emitChannelMessage(message);
+ }
+ });
+
+ socket.onerror = function(error) {
+ util.debug(error);
+ self.emit('error', error);
+ };
+
+ socket.onopen = function() {
+ self.emit('open');
+ };
+
+ socket.onclose = function() {
+ self.emit('close');
+ }
+
+ self.subscribe = function(channel) {
+ var message = {
+ "op": "subscribe",
+ "channel": channel
+ };
+ socket.send(JSON.stringify(message));
+ };
+
+ self.unsubscribe = function(channel) {
+ var message = {
+ "op": "unsubscribe",
+ "channel": channel
+ };
+ socket.send(message);
+ };
+
+ self.close = function(timeout) {
+ socket.close(timeout);
+ };
+
+ // Allow access to underlying socket
+ self.socket = socket;
+};
+
+util.inherits(MtGoxClient, events.EventEmitter);
+
+exports.MtGoxClient = MtGoxClient;
+exports.CHANNELS = MTGOX_CHANNELS;
+exports.URL = MTGOX_WEBSOCKET_URL;
+exports.getChannel = getChannel;
+
+exports.connect = function() {
+ return new MtGoxClient();
+};
22 package.json
@@ -0,0 +1,22 @@
+{
+ "name": "mtgox-socket-client",
+ "version": "0.0.1",
+ "description": "A Socket.io client for MtGox",
+ "keywords": ["mtgox", "socket.io", "bitcoin"],
+ "homepage": "http://github.com/olalonde/node-socket-client",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/dlanod/node-socket-client"
+ },
+ "author": "Donald Ness <donald.ness@gmail.com>",
+ "contributors": [{ "name": "Olivier Lalonde", "email": "olalonde@gmail.com" }]
+ "main": "./mtgox.js",
+ "engines": {
+ "node": ">= v0.4.12"
+ },
+ "dependencies": {
+ "socket.io-client": "0.8.7"
+ "colors": "0.5.1",
+ "datetime": "0.0.3"
+ }
+}

0 comments on commit 8de5382

Please sign in to comment.
Something went wrong with that request. Please try again.