-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtgox.js
115 lines (94 loc) · 2.5 KB
/
mtgox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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) {
//socket.onmessage = function(raw) {
// Emit raw data
var data = raw;
self.emit('data', data);
// Emit JSON messages
try {
//var message = JSON.parse(data);
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);
}
}
catch (ex) {
util.debug(util.inspect(ex));
util.debug('Error parsing JSON data: ' + util.inspect(data));
}
});
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(JSON.stringify(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();
};