[英]reqPostions() help disconnecting TWS / Interactive brokers / api
這是我如何檢查未平倉頭寸的示例。 如果不存在頭寸,它會創建一個 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 市場數據農場連接正常:usfuture 錯誤 -1 2104 市場數據農場連接正常:usfarm 錯誤 -1 2106 HMDS 數據農場連接正常:ushmds 文件創建成功
您刪除了 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.