Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Updated docs, dependencies, made sure demo.js works

  • Loading branch information...
commit 94251110fd41f5beb89e12a6f47302c1791a88df 1 parent 9cdbed9
@johnwarden johnwarden authored
Showing with 294 additions and 120 deletions.
  1. +28 −0 README.md
  2. +21 −18 demo.js
  3. +216 −83 mtgox.js
  4. +29 −19 package.json
View
28 README.md
@@ -8,9 +8,37 @@ Installation
$ npm install mtgox-socket-client
+You may also need to put your API keys inside of 'keys.js' if you want to access the 'client' channel (e.g. your personal trades).
+
+$ node demo.js
+
+Example Use
+------------
+
+ var MtGoxClient = require('./lib/mtgox-client').MtGoxClient;
+
+ var client = new MtGoxClient({channels: {client: true, trade: true}});
+
+ function showMessage(message) {
+ console.log("Got message from mt!",message);
+ }
+
+ /* Show the trade message every time someone makes a trade */
+ client.on("trade",function(message) {
+ console.log("Got trade message from mtgox!",message);
+ });
+
+ /* Show the trade message every there is a client-specific action (buy, sell, etc) */
+ client.on("other",function(message) {
+ console.log("Got client-specific message from mtgox!",message);
+ });
+
+
Contributors
------------
+* [johnwarden](https://github.com/johnwarden)
+* [olalonde](https://github.com/olalonde)
* [dlanod](https://github.com/dlanod)
* [cronopio](https://github.com/cronopio)
* [marak](https://github.com/marak)
View
39 demo.js
@@ -1,12 +1,12 @@
var util = require('util');
var colors = require('colors');
var datetime = require('datetime');
-var mtgox = require('./mtgox');
+var MtGoxClient = require('./mtgox').MtGoxClient
var lastTradePrice = -1;
var lastTickerPrice = -1;
var lastTickerVolume = -1;
-var client = mtgox.connect();
+var client = new MtGoxClient();
client.on('connect', function() {
// Good place to unsubscribe from unwanted channels
@@ -23,19 +23,19 @@ client.on('unsubscribe', function(message) {
renderUnsubscribeMessage(message);
});
-client.on('trade', function(message) {
- renderTradeMessage(message, lastTradePrice);
- lastTradePrice = message.trade.price;
+client.on('trade', function(trade) {
+ renderTradeMessage(trade, lastTradePrice);
+ lastTradePrice = trade.price;
});
-client.on('depth', function(message) {
- renderDepthMessage(message);
+client.on('depth', function(depth) {
+ renderDepthMessage(depth);
});
-client.on('ticker', function(message) {
- renderTickerMessage(message, lastTickerPrice);
- lastTickerPrice = message.ticker.last;
- lastTickerVolume = message.ticker.vol;
+client.on('ticker', function(ticker) {
+ renderTickerMessage(ticker, lastTickerPrice);
+ lastTickerPrice = ticker.last;
+ lastTickerVolume = ticker.vol;
});
process.on('exit', function() {
@@ -53,21 +53,21 @@ var renderUnsubscribeMessage = function(message) {
console.log(getTimeFormat(), format, getChannelFormat(message));
};
-var renderTradeMessage = function(message, lastPrice) {
- console.log(getTimeFormat(), getTradeFormat(message.trade, lastPrice));
+var renderTradeMessage = function(trade, lastPrice) {
+ console.log(getTimeFormat(), getTradeFormat(trade, lastPrice));
};
-var renderTickerMessage = function(message, lastPrice) {
- console.log(getTimeFormat(), getTickerFormat(message.ticker, lastPrice));
+var renderTickerMessage = function(ticker, lastPrice) {
+ console.log(getTimeFormat(), getTickerFormat(ticker, lastPrice));
};
-var renderDepthMessage = function(message) {
- console.log(getTimeFormat(), getDepthFormat(message.depth));
+var renderDepthMessage = function(depth) {
+ console.log(getTimeFormat(), getDepthFormat(depth));
};
var getDepthFormat = function(depth) {
var format = '';
-
+
if (depth.volume < 0) {
format += '+ '.grey;
}
@@ -92,6 +92,8 @@ var getDepthFormat = function(depth) {
};
var getTickerFormat = function(ticker, lastPrice) {
+
+
var format = '> ';
var last = 'Last: '.bold;
@@ -110,6 +112,7 @@ var getTickerFormat = function(ticker, lastPrice) {
};
var getTradeFormat = function(trade, lastPrice) {
+ console.log("Getting tarde format", trade)
var format = '$ ';
if (trade.trade_type == 'ask') {
View
299 mtgox.js
@@ -1,98 +1,231 @@
-var util = require('util');
+
var fs = require('fs');
var events = require('events');
var io = require('socket.io-client');
+var mtGoxAPIV2 = require("mtgox-apiv2");
+var EventEmitter = require('events').EventEmitter;
+var util = require('util');
+var keys = require('./keys').keys;
var MTGOX_SOCKET_URL = 'https://socketio.mtgox.com/mtgox';
-var MTGOX_CHANNELS = [];
-
-try {
- var config = JSON.parse(fs.readFileSync(__dirname + '/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 MTGOX_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" },
+ { "key":"85174711-be64-4de1-b783-0628995d7914", "private":"lag", "name":"Lag" }
+];
+
+
+/* Look up channel by name (e.g. "Market Depth", id (e.g. 24e67e0d-1cad-4cc0-9e7a-f8523ef460fe) or type (e.g. "depth") */
var getChannel = function(key) {
return MTGOX_CHANNELS.filter(function(channel) {
- return (channel.key == key || channel.private == key);
+ return (channel.key == key || channel.private == key || channel.key == key);
})[0];
};
-var MtGoxClient = function() {
- events.EventEmitter.call(this);
- var self = this;
- var socket = io.connect(MTGOX_SOCKET_URL);
-
- socket.on('message', function(raw) {
- // Emit raw data
- var data = raw;
- self.emit('data', data);
-
- // Emit 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') {
- self.emit(message.private, message);
- }
- });
-
- socket.on('error', function(error) {
- util.debug(error);
- self.emit('error', error);
- });
-
- socket.on('connect', function() {
- self.emit('connect');
- });
-
- socket.on('close', function() {
- self.emit('close');
- });
-
- self.subscribe = function(channel) {
- var message = {
- "op": "subscribe",
- "channel": channel
- };
- socket.send(message);
- };
-
- self.unsubscribe = function(channel) {
- var message = {
- "op": "unsubscribe",
- "channel": channel
- };
- socket.send(message);
- };
-
- self.close = function(timeout) {
- };
-
- // Allow access to underlying socket
- self.socket = socket;
-};
-util.inherits(MtGoxClient, events.EventEmitter);
+
+var MtGoxClient = function(options) {
+ if(!options) {
+ options = {};
+ }
+
+ var self = this;
+
+ var socket;
+
+ var lastPulse = new Date() / 1E3;
+ var threshhold = 300; //
+
+ function openSocket() {
+
+ console.info("Opening socket.");
+
+ var socket = io.connect(MTGOX_SOCKET_URL, {
+ "force new connection": !0,
+ reconnect: !0,
+ "reconnection delay": 500 + Math.random() * 500,
+ "max reconnection attempts": 10,
+ transports: ["websockets"],
+ "try multiple transports": !0
+ });
+
+
+ socket.on('message', function(raw) {
+ lastPulse = new Date() / 1E3;
+
+ // Emit raw data
+ var data = raw;
+
+ // Emit messages
+ var message = data;
+
+
+ if (message.op == 'remark') {
+ console.info("Remark",message);
+ console.info("Debug",message.debug);
+ }
+ else if (message.op == 'subscribe') {
+ console.info("Got subscribe confirmation",getChannel(message.channel).name);
+ }
+ else if (message.op == 'unsubscribe') {
+ console.info("Got unsubscribe confirmation",getChannel(message.channel).name);
+ }
+ else if (message.op == 'private') {
+ if (message.private == "trade") {
+ self.emit("trade",message.trade)
+ } else if (message.private == "depth") {
+ self.emit("depth",message.depth)
+ } else if (message.private == "ticker") {
+ self.emit("ticker",message.ticker)
+ } else {
+ self.emit("other",message);
+ }
+ } else {
+ console.info("Other op",message)
+ }
+ });
+
+ socket.on('heartbeat', function(data) {
+ console.info("Got hearbeat");
+ console.info(data);
+ })
+ socket.on('connecting', function(data) {
+ console.info("connecting");
+ console.info(data);
+ })
+ socket.on('reconnecting', function(data) {
+ console.info("reconnecting");
+ console.info(data);
+ })
+
+ socket.on('error', function(error) {
+ console.info("error", error);
+
+ //openSocket();
+ console.info("Reopening socket after error");
+ setTimeout(reopenSocket, 30000 + Math.round(Math.random() * 30000));
+ });
+
+ socket.on('connect', function() {
+ console.info("Got connect");
+
+ if(options.channels) {
+ if(options.channels.client) {
+ console.info("Subscribing to client");
+ self.subscribePrivate();
+ }
+ if(!options.channels.trades) {
+ console.info("unsubscribing trade");
+ self.unsubscribe(getChannel('trade').key)
+ }
+ if(!options.channels.depth) {
+ console.info("unsubscribing depth");
+ self.unsubscribe(getChannel('depth').key)
+ }
+ }
+
+
+ });
+
+ socket.on('disconnected', function() {
+ console.info("disconnected");
+ });
+
+
+ socket.on('disconnect', function() {
+ console.info("disconnect");
+ });
+
+
+ socket.on('close', function() {
+ console.info("Got close");
+ });
+
+ function reSubscribe() {
+ console.info("Resubscribing");
+ self.subscribe('lag');
+ }
+
+
+ self.subscribePrivate = function() {
+ console.info("Subscribe private");
+ var httpsClient = new mtGoxAPIV2(keys.keys[0], keys.keys[1]);
+
+ httpsClient.idKey(function(err, json) {
+ if (err) { throw err; }
+
+ console.info("---------------Client Id Key:--------------");
+ console.info(json);
+
+ var key = json.data;
+ console.info("Subscribing private")
+ var message = {
+ "op": "mtgox.subscribe",
+ "key": key
+ };
+ socket.send(JSON.stringify(message));
+ console.info("Sent private subscribe with",message)
+
+
+ });
+
+ };
+
+
+ self.subscribe = function(channel) {
+ var message = {
+ "op": "subscribe",
+ "channel": channel
+ };
+ socket.send(JSON.stringify(message));
+ };
+ self.subscribeType = function(type) {
+ var message = {
+ "op": "subscribe",
+ "type": type
+ };
+ socket.send(JSON.stringify(message));
+ };
+
+ self.unsubscribe = function(channel) {
+ var message = {
+ "op": "unsubscribe",
+ "channel": channel
+ };
+ socket.send(JSON.stringify(message));
+ };
+
+ self.close = function(timeout) {
+ console.info("Close called");
+ };
+
+ return socket;
+ }
+
+ function reopenSocket() {
+ console.info("Disconnecting socket");
+ self.socket = null;
+ lastPulse = new Date() / 1E3;
+ self.socket = openSocket();
+ }
+ self.socket = openSocket();
+
+ function checkPulse() {
+ var now = new Date() / 1E3;
+ if((now - lastPulse) > 30) {
+ console.info("checking pulse: " + Math.round((now - lastPulse)*100)/100);
+ }
+ if (now - lastPulse > threshhold) {
+ console.info("More than " + threshhold + "s since last data. Reopening socket.")
+ reopenSocket();
+ }
+ }
+ setInterval(checkPulse, 30000);
+};
+util.inherits(MtGoxClient, EventEmitter);
exports.MtGoxClient = MtGoxClient;
-exports.CHANNELS = MTGOX_CHANNELS;
-exports.URL = MTGOX_SOCKET_URL;
-exports.getChannel = getChannel;
-exports.connect = function() {
- return new MtGoxClient();
-};
+
View
48 package.json
@@ -1,22 +1,32 @@
{
- "name": "mtgox-socket-client",
- "version": "0.0.2",
- "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": "https://github.com/kazuyukitanimura/socket.io-client/tarball/master",
- "colors": "0.5.1",
- "datetime": "0.0.3"
+ "name": "mtgox-socket-client",
+ "version": "0.0.2",
+ "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": "https://github.com/kazuyukitanimura/socket.io-client/tarball/master",
+ "colors": "0.5.1",
+ "datetime": "0.0.3",
+ "mtgox-apiv2": "~1.0.6"
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.