IB-Insync only place Stk order once (will not execute additional buy or sell) - Posted solution generates an error for me

Viewed 194

I'm using an existing set of scripts to connect tradingview with interactive brokers (ib.insync).

Tradingview sends a webhook with JSON text, which is received by a flask web app and redis server. The latter is scanned by an ib.insync python script and an order is generated.

These applications were created by a programmer at the below github repository and I am very grateful.

Hacking the markets

All individual components of the program work just fine, but IB only triggers the first order upon receiving the webhook containing JSON.

After that, even though the JSON messages are received, IB does not trigger any additional trades.

There is a solution posted on stackoverflow

Which suggests using ib.qualifyContracts

but this produces the below error message for me:

{'type': 'message', 'pattern': None, 'channel': b'tradingview', 'data': 
b'{\n    "passphrase": "########",\n    "time": "2021-09-05T19:49:00Z",\n    
"ticker": "AAPL",\n    "bar": {\n        "time": "2021-09-05T19:48:00Z",\n        
"open": 126.35,\n        "high": 128.02,\n        "low": 126.02,\n        
"close": 127.75,\n        "volume": 12345\n    },\n    "strategy": {\n        
"position_size": 1,\n        "order_action": "BUY",\n        
"order_contracts": 1,\n        "order_price": 128.50,\n        "order_id": 
"Close entry(s) order long",\n        "market_position": "long",\n        
"market_position_size": 1,\n        "prev_market_position": "flat",\n        
"prev_market_position_size": 0\n    }\n}'}
Traceback (most recent call last):
File "C:\Users\smana\PycharmProjects\TV_IB\venv\brokerappMO.py", line 31,
in <module>
asyncio.run(run_periodically(1, check_messages))
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in 
run_until_complete
return future.result()
File "C:\Users\smana\PycharmProjects\TV_IB\venv\brokerappMO.py", line 29,
in run_periodically
await asyncio.gather(asyncio.sleep(interval), periodic_function())
File "C:\Users\smana\PycharmProjects\TV_IB\venv\brokerappMO.py", line 23,
in check_messages
ib.qualifyContracts(stock)
File "C:\Users\smana\AppData\Roaming\Python\Python39\site
packages\ib_insync\ib.py", line 553, in qualifyContracts
return self._run(self.qualifyContractsAsync(*contracts))
File "C:\Users\smana\AppData\Roaming\Python\Python39\site
packages\ib_insync\ib.py", line 310, in _run
return util.run(*awaitables, timeout=self.RequestTimeout)
File "C:\Users\smana\AppData\Roaming\Python\Python39\site- 
packages\ib_insync\util.py", line 332, in run
result = loop.run_until_complete(task)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 618, in
run_until_complete
self._check_running()
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 578, in 
_check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
Process finished with exit code 1

here is the ib.insync application:

import redis, json
from ib_insync import *
import asyncio, time, random

# connect to Interactive Brokers 
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

# connect to Redis and subscribe to tradingview messages
r = redis.Redis(host='localhost', port=6379, db=0)
p = r.pubsub()
p.subscribe('tradingview')

async def check_messages():
    print(f"{time.time()} - checking for tradingview webhook messages")
    message = p.get_message()
    if message is not None and message['type'] == 'message':
        print(message)

        message_data = json.loads(message['data'])

        stock = Stock(message_data['ticker'], 'SMART', 'USD')
        order = MarketOrder(message_data['strategy']['order_action'],             
        message_data['strategy']['order_contracts'])
        trade = ib.placeOrder(stock, order)

async def run_periodically(interval, periodic_function):
    while True:
        await asyncio.gather(asyncio.sleep(interval), periodic_function())

asyncio.run(run_periodically(1, check_messages))

ib.run()

Would love any input into getting ib.insync to run properly and execute whenever a JSON message is sent. if ib.qualifyContracts() is indeed the solution any insight into why it doesnt work would be helpful.

thank you

0 Answers
Related