Python TWS 盈透证券属性错误

时间:2021-04-15 18:54:32

标签: python api interactive-brokers tws

<块引用>

当我运行此代码时,我收到属性错误但无法从 API 获得结果 我账户中的头寸没有打印出来。 也未执行代码(print("Position", contract.symbol, position, avgCost) IN THE DEF POSITION) 我收到属性错误

AttributeError Traceback(最近一次调用最后一次) 在 158 contract.currency =“美元” 159 --> 160 my.ib.reqMktData(1, contract, "", True, False, []) 161 162 打印(符号)

AttributeError: 'NoneType' 对象没有属性 'ib'

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *
from ibapi.ticktype import TickTypeEnum
from ibapi.scanner import ScannerSubscription
from ibapi.scanner import ScanData
from ibapi.execution import ExecutionFilter
from threading import Timer
from threading import Thread
import threading
import time
import math

symbols = ["MSFT", "C", "SNBR", "LMND"]
quantitys=[1, 2, 3, 4]
pricemoves=[0.5, 1, 1.5, 0.9]
buyorderids=[1,2,3,4]
sellorderids=[1,2,3,4]
currentprices=[0]*4
executions=[]
executionfilter=ExecutionFilter()

numsymbol=len(symbols)
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 historicalData(self, reqId, bar):
        print('HistoricalData. ', reqId, 'Date: ', bar.date, 'Open:', bar.open, 'High:', bar.high, 'Low:', bar.low,
              'Close:', bar.close, 'Volume:', bar.volume, 'Count:', bar.barCount)
        
    def tickPrice(self, reqId, tickType, price, attrib):
        currentprices.append(price)

    def execDetails(self, reqId, contract, execution):
        executions.append(execution)

    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)
            # print(i)
            loopindex = i % numsymbol

# THE TWO LINES OF CODES BELOW DO NOT WORK. THERE ARE NO ERROR MESSAGES CREATED, BUT THE POSITIONS IN MY ACCOUNT ARE NOT PRINTED OUT. 
# ALSO THE CODE (print("Position", contract.symbol, position, avgCost) IN THE DEF POSITION) IS NOT EXECUTED

        print(self.ib.position_symbols)
        print(self.ib.position_shares)

        thissymbol=symbols[loopindex]
        thispricemove=pricemoves[loopindex]
        thisquantity=quantitys[loopindex]

        # MARKET PRICE
        contract=Contract()
        contract.symbol=thissymbol
        contract.secType="STK"
        contract.exchange="SMART"
        contract.currency="USD"
        self.ib.reqRealTimeBars(0, contract, 5, "TRADES", 1, [])
        
        # BUY ORDER
        order=Order()
        order.action="BUY"
        order.orderType="MKT"
        order.totalQuantity=thisquantity

        contract=Contract()
        contract.symbol=thissymbol
        contract.secType="STK"
        contract.exchange="SMART"
        contract.primaryExchange="ISLAND"
        contract.currency="USD"
         
        self.ib.placeOrder(i,contract,order)

        # SELL ORDER
        order=Order()
        order.action="SELL"
        order.orderType="MKT"
        order.totalQuantity=thisquantity

        contract=Contract()
        contract.symbol=thissymbol
        contract.secType="STK"
        contract.exchange="SMART"
        contract.primaryExchange="ISLAND"
        contract.currency="USD"
        self.ib.placeOrder(i+1,contract,order)

        # HANDLE ORDER ID
        buyorderids[loopindex]=i
        sellorderids[loopindex]=i+1
        print(i)

        self.ib.reqMktData(1, contract, "", True, False, []) 
        print(currentprices)

        self.ib.reqExecutions(10001, executionfilter)
        print(executions)
        

my = None
while True:
    user_input = input("What do I do?")
    if user_input == "start thread":
        if my == None: 
            my = MyThread()

    elif user_input.upper() in ["REMOVE", "ADD"]:
        
        symbol = input("Enter stock symbol:")
        if user_input.upper() == "ADD": 
            symbols.append(symbol.upper())

            contract=Contract()
            contract.symbol=user_input.upper()
            contract.secType="STK"
            contract.exchange="SMART"
            contract.primaryExchange="ISLAND"
            contract.currency="USD"

            my.ib.reqMktData(1, contract, "", True, False, []) 

            print(symbols)
        elif user_input.upper() == "REMOVE":
            index=symbols.index(symbol.upper())
            del symbols[index]
            del quantitys[index]
            del pricemoves[index]
            del sellorderids[index]
            del buyorderids[index]  
            print(symbols)```





0 个答案:

没有答案