盈透证券交易平台、Python API

时间:2021-04-15 21:21:50

标签: python api tws

我有一个问题。在我的程序中间,请参阅下面的大写问题。 不知何故,这两个列表是空的。类 TestApp 中的函数位置似乎没有被调用。 任何帮助表示赞赏。我被困在这里,没有帮助就找不到解决方案。

An error occurred (InvalidPermission.Duplicate) when calling the AuthorizeSecurityGroupIngress operation: the specified rule "peer: sg-blah, ALL, ALLOW" already exists

1 个答案:

答案 0 :(得分:0)

您应该为 EClient.run() 方法使用新线程。然后在主线程中执行其他所有操作。

现在可以使用了:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from threading import Thread
import time


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.position_symbols = []
        self.position_shares = []

    def error(self, reqId, errorCode, errorString):
        print('Error: ', reqId, " ", errorCode, " ", errorString)

    def position(self, account, contract, position, avgCost):
        super().position(account, contract, position, avgCost)
        print("Position", contract.symbol, position, avgCost)
        self.position_symbols.append(contract.symbol)
        self.position_shares.append(str(position))

    def nextValidId(self, orderId):
        self.nextOrderId = orderId
        self.start()

    def start(self):
        self.reqPositions()

    def stop(self):
        self.done = True
        self.cancelScannerSubscription(1)
        self.disconnect()


# class MyThread(Thread, EWrapper, EClient):
#     ib = None
#
#     def __init__(self):
#         self.ib = TestApp()
#         Thread.__init__(self)
#
#         self.start()
#
#         self.ib.connect('127.0.0.1', 7497, 0)
#         app = TestApp()
#         app.nextOrderId = 0
#
#     def run(self):
#         for i in range(332, 345, 2):
#             time.sleep(4)
#             # loopindex = i % numsymbol
#
#             # THOSE TWO LINES OF CODES ARE NOT WORKING.
#             # PROBABLY DUE TO THREADING ISSUES.
#             # THE TWO LISTS ARE EMPTY
#
#             print(self.ib.position_symbols)
#             print(self.ib.position_shares)


app = TestApp()
app.connect('127.0.0.1', 7497, 0)

my = None
while True:
    app.nextOrderId = 0
    user_input = input("What do I do?")
    if user_input == "start thread":
        if my == None:
            my = Thread(target=app.run)
            my.start()

    elif user_input.upper() in ["REMOVE", "ADD"]:
        # do
        # something....
        pass

    for i in range(332, 345, 2):
        time.sleep(4)
        # loopindex = i % numsymbol

        # NOW WORKING

        print(app.position_symbols)
        print(app.position_shares)