public
anonymous / py_example.py
Last active

  • Download Gist
py_example.py
Python
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
#!/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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.