Python连接到IB Gateway并通过FIX协议进行交易

254 阅读1分钟

除了Java,还有其他语言也可以使用FIX协议连接到IB Gateway,例如C++、Python等。以下是一个使用Python连接到IB Gateway并通过FIX协议进行交易的示例:

import quickfix as fix import time

class IBGatewayFIXClient(fix.Application):

def onCreate(self, sessionID):
    print("Session created:", sessionID)

def onLogon(self, sessionID):
    print("Logged on:", sessionID)

def onLogout(self, sessionID):
    print("Logged out:", sessionID)

def toAdmin(self, message, sessionID):
    print("To admin:", message)

def fromAdmin(self, message, sessionID):
    print("From admin:", message)

def toApp(self, message, sessionID):
    print("To app:", message)

def fromApp(self, message, sessionID):
    print("From app:", message)

def sendOrder(self):
    sessionID = fix.Session.lookupSession("FIX.4.4:CLIENT->IBGATEWAY")
    order = fix.Message()
    order.getHeader().setField(fix.BeginString("FIX.4.4"))
    order.getHeader().setField(fix.MsgType("D"))
    order.setField(fix.ClOrdID("123"))
    order.setField(fix.Side(fix.Side_BUY))
    order.setField(fix.TransactTime())
    order.setField(fix.OrdType(fix.OrdType_MARKET))
    order.setField(fix.Symbol("AAPL"))
    order.setField(fix.OrderQty(100))
    order.setField(fix.Price(100.0))
    fix.Session.sendToTarget(order, sessionID)

if name == 'main': settings = fix.SessionSettings("config.cfg") application = IBGatewayFIXClient() storeFactory = fix.FileStoreFactory(settings) logFactory = fix.FileLogFactory(settings) messageFactory = fix.DefaultMessageFactory() initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory, messageFactory) initiator.start() time.sleep(5) # Wait for connection to be established application.sendOrder() time.sleep(5) # Wait for order to be processed initiator.stop() 与Java版本类似,我们首先创建了一个SocketInitiator并传入了SessionSettings、Application、MessageStoreFactory、LogFactory和MessageFactory。然后我们实现了Application接口中的方法,这些方法在FIX协议的各个阶段会被调用。最后,我们在main方法中启动了SocketInitiator并发送了一个NewOrderSingle订单。

需要注意的是,上述代码中的config.cfg文件应该包含与IB Gateway连接所需的配置信息,例如:

[DEFAULT] ConnectionType=initiator ReconnectInterval=60 SenderCompID=CLIENT TargetCompID=IBGATEWAY SocketConnectHost=localhost SocketConnectPort=4001 HeartBtInt=30

[SESSION] BeginString=FIX.4.4 DefaultApplVerID=9.5 StartTime=00:00:00 EndTime=00:00:00 以上代码仅供参考,实际使用中需要根据具体情况进行修改和优化。