I run the code below, but it seams to get out of sync with TWS. The first order will work, but then the positions call will not return what shows up in TWS. I think it has something to do with started to listening to the port then sending orders and losing the next valid ID for incoming messages from TWS. How would I write the below in asynchronous format? I know I can wrap things in tasks then run them in the while true loop as tasks. Please help.
from ib_insync import *
ib.connect()
while True:
time_stamp = time.strftime("%H:%M")
today = str(date.today())
if today == '2023-05-24' and time_stamp > '0400':
if stocks_list.count(ticker) == 0:
print(ticker)
print(gain)
print(price)
send_price = round((price *1.10),2)
try:
stock = Stock(ticker, 'SMART', 'USD')
order = LimitOrder('BUY', 100, send_price, outsideRth = True)
sell_trade = ib.placeOrder(stock, order)
print(sell_trade)
stocks_list.append(ticker)
except Exception as e:
pass
print(e)
d = ib.portfolio()
if d:
for s in d:
print(s)
stock = Stock(ticker, 'SMART', 'USD')
order = LimitOrder('BUY', 50, .9600, outsideRth = True, tif = 'DAY')
sell_trade = ib.placeOrder(stock, order)
print(sell_trade)
For the while true loop to stay synced with TWS. It would work on the first order then the data being shown was not current after a few hours.