这是我如何检查未结头寸的示例。如果不存在职位,它将创建一个txt文件;如果存在未结职位,则将删除.txt文件。 我的问题是我不知道如何断开连接。它还输出错误-1,请参见下面的脚本
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
from ib.opt import ibConnection
import os.path
from os import path
class CheckPos(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId:int):
self.reqPositions()
def position(self, account: str, contract: Contract, position: float,
avgCost: float):
super().position(account, contract, position, avgCost)
if position >0:
try:
os.remove("noposition.txt")
except:
print("Open Positons")
else:
try:
open("noposition.txt","w+")
print("File Created Sucessfully")
except:
print("No Open Positions")
def main():
app = CheckPos()
app.connect("127.0.0.1", 7497,421 )
app.run()
if __name__ == "__main__":
main()
输出为 错误-1 2104市场数据场连接正常:将来 错误-1 2104市场数据场连接正常:usfarm 错误-1 2106 HMDS数据场连接正常:ushmds 文件创建成功
答案 0 :(得分:0)
您删除了positionEnd()方法。那是您应该断开连接的时候。
此行from ib.opt import ibConnection
来自IbPy,请将其删除。
我不确定您要对文件做什么,但是您可能会在回调中返回很多职位。最好将它们添加到列表中,并在程序完成所有职位后对其进行处理。我在positionEnd()方法中编写了一些内容,该方法可以断开连接,然后保存数据。
ERROR -1 2104 Market data farm connection is OK:usfuture
之类的行只是信息。除非他们说它已损坏,否则您可以忽略它们,但这是另一个错误代码。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
import os
class TestApp(EClient, EWrapper):
posns = []
fname = 'fname.txt'
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId:int):
print("id", orderId)
print("starting program")
self.reqPositions()
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error: ", reqId, "", errorCode, "", errorString)
def position(self, account: str, contract: Contract, position: float, avgCost: float):
self.posns.append((account, contract.symbol, position, avgCost))
print(contract.symbol, position)
def positionEnd(self):
print("end, disconnecting")
self.disconnect()
#write posns to file or delete file if no positions
if self.posns: #means not empty
with open(self.fname, "w") as outfile:
outfile.write('\n'.join(str(posn) for posn in self.posns))
else: # no posns so delete file
os.remove(self.fname)
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 421)
app.run()
if __name__ == "__main__":
main()