Quickfix with several Python strategies - python-2.7

I am having difficulties to trade several trading strategies written in Python.
I have established FIX connection via Quickfix but I only can send orders if the script of the strategy is inside the Quickfix connection script. Since I have several strategies I really have no idea how to send the order from a separate script. Can someone give me some solution?
import sys
import datetime
import time
import quickfix as fix
class Application(fix.Application):
orderID = 0
execID = 0
def gen_ord_id(self):
global orderID
orderID+=1
return orderID
def onCreate(self, sessionID):
return
def onLogon(self, sessionID):
self.sessionID = sessionID
print ("Successful Logon to session '%s'." % sessionID.toString())
return
def onLogout(self, sessionID):
return
def toAdmin(self, message, sessionID):
username = fix.Username("username")
mypass = fix.Password("password")
mycompid = fix.TargetSubID("targetsubid")
message.setField(username)
message.setField(mypass)
message.setField(mycompid)
def fromAdmin(self, message, sessionID):
TradeID = fix.TradingSessionID
message.getField(TradeID)
return
def toApp(self, sessionID, message):
print "Sent the following message: %s" % message.toString()
return
def fromApp(self, message, sessionID):
print "Received the following message: %s" % message.toString()
return
def genOrderID(self):
self.orderID = self.orderID + 1
return `self.orderID`
def genExecID(self):
self.execID = self.execID + 1
return `self.execID`
def put_order(self, sessionID, myinstrument, myquantity):
self.myinstrument = myinstrument
self.myquantity = myquantity
print("Creating the following order: ")
today = datetime.datetime.now()
nextID = today.strftime("%m%d%Y%H%M%S%f")
trade = fix.Message()
trade.getHeader().setField(fix.StringField(8, "FIX.4.4"))
trade.getHeader().setField(fix.MsgType(fix.MsgType_NewOrderSingle))
trade.setField(fix.ClOrdID(nextID)) #11=Unique order
trade.getHeader().setField(fix.Account("account"))
trade.getHeader().setField(fix.TargetSubID("targetsubid"))
trade.setField(fix.Symbol(myinstrument)) #55=SMBL ?
trade.setField(fix.TransactTime())
trade.setField(fix.CharField(54, fix.Side_BUY))
trade.setField(fix.OrdType(fix.OrdType_MARKET)) # 40=2 Limit order
trade.setField(fix.OrderQty(myquantity)) # 38=100
print trade.toString()
fix.Session.sendToTarget(trade, self.sessionID)
try:
file = sys.argv[1]
settings = fix.SessionSettings(file)
application = Application()
storeFactory = fix.FileStoreFactory(settings)
logFactory = fix.ScreenLogFactory(settings)
initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
initiator.start()
while 1:
time.sleep(1)
if input == '1':
print "Putin Order"
application.put_order(fix.Application)
if input == '2':
sys.exit(0)
if input == 'd':
import pdb
pdb.set_trace()
else:
print "Valid input is 1 for order, 2 for exit"
except (fix.ConfigError, fix.RuntimeError) as e:
print e
This is my initator app. My question is can I update the following values from another python script:
trade.setField(fix.Symbol(myinstrument))
trade.setField(fix.OrderQty(myquantity))
So I want to change myinstrument and myquantity from another python script and force the initiator to execute the following command application.put_order(fix.Application) with the new values. My question is is this possible at all?

Sounds like you need an internal messaging layer that QuickFIX subscribes to, and that your separate Python scripts publish orders to. It's about workflow design. Try something like VertX as that can be setup using Python.

Related

Load Url on Pepper's Tablet

I'm trying to load a website on Pepper like "www.google.com"
I'm sure we are connected on the same network. I've tried doing "http://www.google.com" too on the ShowApp Dialog.
I've seen this guide: http://kokorobot.com/2016/08/08/how-to-use-pepper-tablet
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
self.isRunning = False
def onUnload(self):
self.isRunning = False
def _getTabletService(self):
tabletService = None
try:
tabletService = self.session().service("ALTabletService")
except Exception as e:
self.logger.error(e)
return tabletService
def onInput_onStart(self):
if self.isRunning:
return # already running, nothing to do
self.isRunning = True
# We create TabletService here in order to avoid
# problems with connections and disconnections of the tablet during the life of the application
tabletService = self._getTabletService()
appName = self.packageUid()
state = False
if appName:
if tabletService:
if tabletService.loadApplication(appName):
tabletService.loadUrl("www.google.com") self.logger.info("Successfully set application: %s" % appName)
tabletService.showWebview()
state = True
else:
self.logger.warning("Got tablet service, but failed to set application: %s" % appName)
else:
self.logger.warning("Couldn't find tablet service, so can't set application: %s" % appName)
if state:
self.onSuccess()
else:
self.onFailure()
If you want to show a web consider using the box "Show Web View" instead. I've found that Show App gives more trouble than it's worth it.
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
pass
def onUnload(self):
pass
def _getTabletService(self):
tabletService = None
try:
tabletService = self.session().service("ALTabletService")
except Exception as e:
self.logger.error(e)
return tabletService
def _getAbsoluteUrl(self, partial_url):
import os
subPath = os.path.join(self.packageUid(), os.path.normpath(partial_url).lstrip("\\/"))
# We create TabletService here in order to avoid
# problems with connections and disconnections of the tablet during the life of the application
return "http://%s/apps/%s" %(self._getTabletService().robotIp(), subPath.replace(os.path.sep, "/"))
def onInput_onStart(self):
# We create TabletService here in order to avoid
# problems with connections and disconnections of the tablet during the life of the application
tabletService = self._getTabletService()
if tabletService:
try:
url = "http://www.google.com/"
if url == '':
self.logger.error("URL of the image is empty")
if not url.startswith('http'):
url = self._getAbsoluteUrl(url)
self.logger.info(url)
tabletService.showWebview(url)
except Exception as err:
self.logger.error("Error during ShowImage : %s " % err)
self.onStopped()
self.onStopped()

error "not enough arguments given" when setting a function of a class as a callback

I'm new to python. Following is my code. I get this error when I create an instance of my class.
error from callback >: on_open() takes exactly 2 arguments (1 given)
The same code works alright if I do all of this outside the Class, directly in the main file. I think it has something to do with the 'self' thing(attribute ?). But the similar code on the server side works alright.
I'm using this web-socket-client package! and following the example Long-lived connection shown there.
This is the library! I'm using for the server side, which has pretty similar interface as the client library.
Server Side Code
from websocket_server import WebsocketServer
def client_connected(client, server):
print "connected:"
print client
def client_disconnected(client, server):
print "Disconnected:"
print client
def message_received(client, server, message):
server.send_message(client, message)
print "message received: ", message
print client
server = WebsocketServer(13254, host='127.0.0.1')
server.set_fn_new_client(client_connected)
server.set_fn_client_left(client_disconnected)
server.set_fn_message_received(message_received)
server.run_forever()
Client Side code that works.
import websocket
from multiprocessing import Lock
import copy
import json
import time
import thread
txMsg = "hello world"
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run():
for i in range(1):
time.sleep(1)
print txMsg
ws.send(txMsg)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://127.0.0.1:13254",
on_message = on_message,
on_error = on_error,
on_close = on_close,
on_open = on_open)
ws.run_forever()
Client side code that produces error
import websocket
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Client:
__metaclass__ = Singleton
serverAddress = None
serverPort = None
socket = None
def __init__(self, serverAddress, serverPort):
self.serverAddress= serverAddress
self.serverPort = serverPort
websocket.enableTrace(True)
self.socket = websocket.WebSocketApp("ws://"+ serverAddress +":"+str(serverPort),
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close,
on_open = self.on_open)
# Callbacks------------------------------------------------------------------
def on_open(self, ws):
print "***Connection Opened***"
self.close()
def on_close(self, ws):
print "***Connection Closed***"
def on_message(self, ws, message):
print "Message: ", message
self.socket.close()
def on_error(self, ws, error):
print "Error: ", error
# API------------------------------------------------------------------
def close(self):
self.socket.close()
client = Client('127.0.0.1', 13254)
client.socket.run_forever()
In the source code of the client library, go to "_app.py". In function "_callback" of the class "WebSocketApp" (line 339 at the moment of writing this answer), change
if inspect.ismethod(callback):
to
if not inspect.ismethod(callback):

Python 2.7.6: How do I clean up a class properly?

in the following and executable code you see a SessionScope()-class. In the main()-function the user can log on to his MySQL database server. We take a look in the class. There are two magic methods (__enter__, __exit__),
that allows me to use the object easily with the with-statement. In this statement you also see the program uses session. When the __exit__()-method is
calling then the session is closed. BUT we know that will give the connection back to the connection pool of Engine. That means, its doesn't close the connection directly,
because the connection is pooling. So far so good. On GUI side the user has the option to log off. Well, let us imagine: After a very very very long work with the
database the user wants the connection to be actually closed, but he doesn't wants the program closes itself. Later perhaps the user will log on again and continue working. Until then the program is still running without connection to
the database. The user doesn't need the connection anymore.
That means for python, we don't need the SessionScope()-class anymore. In my case we can remove/clean up this class with del session_scope My idea is to re-implement the __del__()-method. In this method I want to
close all connections of the connection pool. If this class is cleared/removed all connections should be disconnected, that is the reason why I use the del in log_out()-function.
Is this the right way to do this?
TA, your Sophus
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
class SessionScope(object):
def __init__(self, dbms, dbdriver, dbuser, dbuser_pwd, db_server_host, dbport, db_name):
self.dbms = dbms
self.dbdriver = dbdriver
self.dbuser = dbuser
self.dbuser_pwd = dbuser_pwd
self.db_server_host = db_server_host
self.dbport = dbport
self.db_name = db_name
url = '{}+{}://{}:{}#{}:{}/{}'.format(
self.dbms, self.dbdriver, self.dbuser, self.dbuser_pwd, self.db_server_host, self.dbport, self.db_name)
self.engine = create_engine(url, encoding='utf8', echo=True)
# store a sessionmaker for this db connection object
self._Session = sessionmaker(bind=self.engine)
self.session = None
def __enter__(self):
self.session = self._Session()
return self._Session()
def __exit__(self, exception, exc_value, traceback):
try:
if exception:
self.session.rollback()
else:
self.session.commit()
finally:
self.session.close()
self.session = None
def __del__(self):
self.engine.dispose()
def log_out(session_scope):
del session_scope
def main():
dbm_system = raw_input("Which DBMS? (type for e.g. mysql): ")
dbm_driver = raw_input("Which db-driver? (type for e.g. pymysql): ")
db_host = raw_input("Server-Host: ")
db_user = raw_input("Database-user: ")
db_passwd = raw_input("User-Password: ")
db_name = raw_input("Database Name: ")
db_port = raw_input("Port: ")
try:
session_scope = SessionScope(dbm_system, dbm_driver, db_user, \
db_passwd, db_host, db_port, db_name)
with session_scope as session:
# Its just for testing.
print session.execute("SELECT VERSION();")
log_out(session_scope)
except SQLAlchemyError as err:
print "ERROR", err[0]
if __name__ == '__main__':
main()
EDIT #1:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
class SessionScope(object):
def __init__(self, engine):
self.engine = engine
# store a sessionmaker for this db connection object
self._Session = sessionmaker(bind=self.engine)
self.session = None
def __enter__(self):
self.session = self._Session()
return self._Session()
def __exit__(self, exception, exc_value, traceback):
try:
if exception:
self.session.rollback()
else:
self.session.commit()
finally:
self.session.close()
self.session = None
class Engine(object):
def __init__(self, dbms, dbdriver, dbuser, dbuser_pwd, db_server_host, dbport, db_name):
self.dbms = dbms
self.dbdriver = dbdriver
self.dbuser = dbuser
self.dbuser_pwd = dbuser_pwd
self.db_server_host = db_server_host
self.dbport = dbport
self.db_name = db_name
url = '{}+{}://{}:{}#{}:{}/{}'.format(
self.dbms, self.dbdriver, self.dbuser, self.dbuser_pwd, self.db_server_host, self.dbport, self.db_name)
self._Engine = create_engine(url, encoding='utf8', echo=True)
def __enter__(self):
return self._Engine
def __exit__(self, exception, exc_value, traceback):
'''
Make sure the dbconnection gets closed
'''
self._Engine.dispose()
logged_in = True
def main():
dbm_system = raw_input("Which DBMS? (type for e.g. mysql): ")
dbm_driver = raw_input("Which db-driver? (type for e.g. pymysql): ")
db_host = raw_input("Server-Host: ")
db_user = raw_input("Database-user: ")
db_passwd = raw_input("User-Password: ")
db_name = raw_input("Database Name: ")
db_port = raw_input("Port: ")
try:
with Engine(dbm_system, dbm_driver, db_user, \
db_passwd, db_host, db_port, db_name) as engine:
while logged_in:
with SessionScope(engine) as session:
# Its just for testing.
print session.execute("SELECT VERSION();")
except SQLAlchemyError as err:
print "ERROR", err[0]
if __name__ == '__main__':
main()
The __del__ method doesn't work like that. It's not called when a user does del some_instance, but when the interpreter's garbage collector sees that there are no live references to the object. Your log_out method does nothing, since the reference it is deleting is an extra one that's created to pass the session to it as an argument (the outside reference still remains).
I suspect you really want to have two different classes that both support the context manager protocol. This lets you have two nested with statements, one which last through an entire login and that only lasts for the length of one per database session. Something like this:
with Engine() as engine:
while logged_in:
with Session(engine) as session:
do_stuff()
You may want another loop around the outer with so that the program doesn't exit after you log out.

Python restkit module connection returns error

I'm attempting to use a script I found online, (https://confluence.atlassian.com/display/DOCSPRINT/The+Simplest+Possible+JIRA+REST+Examples) probably 5+ years old, to access Jira REST API. I have all the modules installed in Pyhton 2.7. However, when run the script I get an error that SimplePool cannot be imported. Having done my Goodiligence (Google searching), I see that SimplePool is deprecated in restkit 4.2.2 (which is the version I have installed). So, the doc that I found (http://pydoc.net/Python/restkit/2.3.0/restkit.pool.simple/) says to use TConnectionManager (which I did with no success). I still get a similar error. So, I stumbled upon another doc (http://benoitc.github.io/restkit/pool.html) and it says to use ConnectionPool, and I still get a similar error. I appreciate any direction given. Here is my code:
import simplejson as json
from restkit import * #added this line after finding the last document
from restkit import Resource, BasicAuth, request
from socketpool import ConnectionPool
SimplePool = ConnectionPool
def rest_test(server_base_url, user, password, issue_key):
'''
Use restkit to make a REST request to JIRA
'''
verbose = False
# A pool of connections
pool = SimplePool(factory=Connection)
# This sends the user and password with the request.
auth = BasicAuth(user, password)
resource_name = "issue"
complete_url = "%s/rest/api/latest/%s/%s" % (server_base_url, resource_name, issue_key)
resource = Resource(complete_url, pool_instance=pool, filters=[auth])
try:
response = resource.get(headers = {'Content-Type' : 'application/json'})
except Exception,ex:
# ex.msg is a string that looks like a dictionary
print "EXCEPTION: %s " % ex.msg
return
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
print "ERROR: status %s" % response.status_int
return
# Convert the text in the reply into a Python dictionary
issue = json.loads(response.body_string())
# Pretty-print the JSON
if verbose:
print json.dumps(issue, sort_keys=True, indent=4)
# The properties of the issue include:
# self, html, key, transitions, expand, fields
print "Issue key: %s" % issue['key']
fields = issue['fields']
for field_name in fields:
field_object = fields[field_name]
print "Field %s = %s" % (field_name, field_object['type'])
# The type of the value of a field depends on the type of the field
if field_name in ["summary"]:
print " Value = %s" % field_object['value']
if __name__ == '__main__':
user = 'myuname'
password = '*****'
server_url = 'http://jira.mysite.com/'
issue_key = 'JRA-219'
rest_test(server_url, user, password, issue_key)
Here is the error returned:
File "simplest_client.py", line 30, in rest_test
pool = SimplePool()
TypeError: __init__() takes at least 2 arguments (1 given)
EXCEPTION: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>404</status-code><message>null for uri: http://jira.mysite.com//rest/api/latest/issue/JRA-219</message></status>

AttributeError: 'NoneType' object has no attribute 'write' and System changes

I know there are tons of posts about the AttributeError: NoneType... but they don't seem to apply. My code has been working for years, and this week i am getting this error. Also, I am not an expert coder.
I checked the Python Path, and it seems normal:
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Python27;C:\Python27\Scripts
When i try to edit the code in Komodo IDE, the autocomplete works fine, e.g., self.ser.write(string) has the write in the suggestion menu.
It is as if it can't find the library. Is that right? How can that be?
I am using XP.
Thanks!
OK, i figured it out. I traced the failure to instantiation of opening a COM port (debugging in Komodo IDE was very helpful). It failed to open the port, and while the wrapper (below) for pyserial caught the error, my code didn't do anything about it. So when i tried to use serial methods, i.e. `ser.write()' (where ser is my port instance) i get the AttributeError.
The port failed to open because of the box on the other end wasn't communicating properly. Resetting this box (a motor controller) fixed the problem.
The wrapper I use for PySerial appears to be in-house code---short but useful. I am sharing it here:
SerialIO: Wrapper for PySerial
#----------------------------------------------------------------------
# serialIO: wrappers for pyserial module for exception handling, etc.
#----------------------------------------------------------------------
# depends on http://pyserial.sourceforge.net/
import serial
import sys
import time
##################################### serial handlers
# all serial commands except stop are filtererd through this
class serialIO():
def __init__(self,port, baudrate, timeout=0.0,echo=False,rtscts=False):
self.port = port
self.br = baudrate
self.to = timeout
self.echo = echo
self.rtscts = rtscts
self.stdout = False
self.ser = None
self.status = "OK"
self.reopen()
def reopen(self):
# first close it if it's already open
if self.ser:
try:
self.ser.close()
except serial.SerialException, v:
self.status = "error"
# do we want stdout (for debug)?
if self.port == "stdout":
self.stdout = True
self.ser = sys.stdout
else: # nope, actually open the prort
try: # xonxoff=True hoses binary polling of Faulhabers!
self.ser = serial.Serial(self.port, self.br,
timeout=self.to,
rtscts =self.rtscts,
xonxoff=False)
except serial.SerialException, v:
self.status = "error"
print str(v)
return(self.status)
def echo(self,str):
pass
# write the given string to the serial device, catching exceptions
def safewrite(self,string,flush=True):
try:
result = self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
except serial.SerialException, v:
print str(v)
return(-1)
return(result)
def REALLYflushInput(self):
""" because ser.flushInput() doesn't seem to work :/"""
if self.stdout:
return
self.ser.flushInput()
time.sleep(0.01)
#self.ser.flushInput()
readstr = ""
incount = self.ser.inWaiting()
while (incount > 0):
readstr += self.ser.read(incount)
time.sleep(0.01)
incount = self.ser.inWaiting()
# write the given string to the serial device
def write(self,string,flush=True):
self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
def read(self,nb):
return(self.ser.read(nb))
# returns number of bytes successfully read, -1 if error
def saferead(self):
if self.stdout:
return("",0)
nread = 0
try:
incount = self.ser.inWaiting()
except serial.SerialException, v:
incount = 0
raise
rstr = ""
while (incount > 0):
try:
rstr += self.ser.read(incount)
except serial.SerialException, v:
print str(v)
return(rstr,-1)
nread = nread + incount
incount = self.ser.inWaiting()
return(rstr,nread)
def readstr(self):
incount = self.ser.inWaiting()
readstring = ""
while (incount > 0):
readstring += self.ser.read(incount)
incount = self.ser.inWaiting()
if self.echo:
self.log("read %s" % readstring)
return readstring
# resturn a list of available serial devices
def GetPortList(plist):
# for port in portlist:
if len(plist) < 1:
# if no list of portnames, make one
plist = ['COM2','COM3','COM4','COM5']
OKports = []
for port in plist:
ser = None
try:
ser = serial.Serial(port, 9600)
except serial.SerialException, v:
#print str(v)
pass
else:
OKports.append(ser.name)
finally:
if(ser):
ser.close()
return OKports
if __name__ == '__main__':
plist = GetPortList([])
print str(plist)
It looks more as if your variable self.ser has NoneType, so you might need to take a look at the place where you initialize self.ser in your class.
Edit: Looking around it seems that the library you are using is pyserial2.7 right? I have seen at the documentation here a class called just Serial, which also takes as input a port and a baudrate, so I guess it might be the class you need. Maybe you are getting NoneType because that SerialIO is deprecated. I have not been able to find it, but that does not mean it doesn't exist. Objects of class Serial also have a write method according to this documentation.