Skip to content

Instantly share code, notes, and snippets.

@qsun
Forked from anonymous/py_example.py
Created March 12, 2013 11:58
Show Gist options
  • Save qsun/5142347 to your computer and use it in GitHub Desktop.
Save qsun/5142347 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
class BidAskParseError(Exception): pass
import datetime
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import ClientFactory
class ExampleClient(LineReceiver):
def __init__(self):
self.delimiter = '\n'
self.symbols = [ 'SPY', 'BAC', 'XOM' ]
def lineReceived(self, line):
fields = line.split(',')
if len(fields) > 0:
if fields[0] == 'Q':
self.processQuote(fields)
elif fields[0] == 'S':
if fields[1] == 'CUST':
self.subscribe()
def subscribe(self):
for sym in self.symbols:
self.sendLine('w' + sym)
def processQuote(self, fields):
self.now = datetime.datetime.now()
try:
#sym = fields[1]
#bid = float(fields[10])
#ask = float(fields[11])
#bid_size = int(fields[12])
#ask_size = int(fields[13])
#mid = (bid + ask) / 2.0
#spread = ask - bid
#if bid == 0.0 or ask == 0.0:
# raise BidAskParseError()
print str(self.now) + ' -- quote: ' + str(fields)
except BidAskParseError:
pass
#print str(self.now) + ' -- Unable to parse bid or ask for ' + sym + ': ' + str(fields)
class ExampleClientFactory(ClientFactory):
protocol = ExampleClient
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
def main():
factory = ExampleClientFactory()
reactor.connectTCP('localhost', 5009, factory)
reactor.run()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment