Skip to content

Instantly share code, notes, and snippets.

@cdhowie
Created June 8, 2011 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdhowie/1015309 to your computer and use it in GitHub Desktop.
Save cdhowie/1015309 to your computer and use it in GitHub Desktop.
Mt. Gox live trade watcher
#!/usr/bin/perl -w
# Donations may be sent to 1Ni6BojkPJ62HvCrdx4LQRrgvNKg56yq3y
#
# Copyright (C) 2011 by Chris Howie <me@chrishowie.com>
#
# 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.
use strict;
use IO::Socket::INET;
use JSON;
$| = 1;
my $socket = new IO::Socket::INET(
PeerAddr => 'websocket.mtgox.com',
PeerPort => 80,
Proto => 'tcp')
or die 'Unable to connect';
binmode $socket;
print $socket <<REQUEST;
GET /mtgox HTTP/1.1\r
Upgrade: WebSocket\r
Connection: Upgrade\r
Host: websocket.mtgox.com\r
Origin: null\r
\r
REQUEST
$socket->flush();
my $line;
do {
$line = <$socket>;
if (defined($line)) {
$line =~ s/\r//g;
print $line;
}
} while (defined($line) and $line !~ /^$/m);
my $buffer = '';
my $char;
while (read($socket, $char, 1)) {
if ($char eq "\xff") {
&display_event(decode_json($buffer));
$buffer = '';
} elsif ($char ne "\0") {
$buffer .= $char;
}
}
$socket->close();
sub display_event ($) {
my $event = shift;
if ($event->{'channel'} ne 'dbf1dee9-4f2e-4a08-8cb7-748919a71b21') {
return;
}
my $trade = $event->{'trade'};
return unless defined($trade);
my $time = localtime($trade->{'date'});
printf "%s -- %11.5f %3s @ %11.5f %3s\n",
$time,
$trade->{'amount'}, $trade->{'item'},
$trade->{'price'}, $trade->{'price_currency'};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment