ib.reqTickByTickData raising exception: 'ConnectionError: Socket disconnect'
See original GitHub issueI am attempting to place limit orders based on the prevailing best bid/offer. I am attempting to do this through ‘ib.reqTickByTickData(symbol, ‘BidAsk’)’. This function works perfectly when testing. However when I put it into a while True loop, it acts up and causes the following error:
CancelledError Traceback (most recent call last)
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\tasks.py:234, in Task.__step(***failed resolving arguments***)
[233](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=232) else:
--> [234](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=233) result = coro.throw(exc)
[235](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=234) except StopIteration as exc:
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\tasks.py:605, in sleep(delay, result)
[604](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=603) try:
--> [605](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=604) return await future
[606](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=605) finally:
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\futures.py:284, in Future.__await__(self)
[283](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=282) self._asyncio_future_blocking = True
--> [284](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=283) yield self # This tells Task to wait for completion.
[285](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=284) if not self.done():
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\tasks.py:304, in Task.__wakeup(self, future)
[303](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=302) try:
--> [304](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=303) future.result()
[305](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=304) except BaseException as exc:
[306](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/tasks.py?line=305) # This may also be a cancellation.
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\futures.py:196, in Future.result(self)
[195](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=194) exc = self._make_cancelled_error()
--> [196](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=195) raise exc
[197](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=196) if self._state != _FINISHED:
CancelledError:
During handling of the above exception, another exception occurred:
CancelledError Traceback (most recent call last)
File c:\Users\Azkar\miniconda3\envs\quant\lib\site-packages\ib_insync\util.py:332, in run(timeout, *awaitables)
[331](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=330) try:
--> [332](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=331) result = loop.run_until_complete(task)
[333](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=332) except asyncio.CancelledError as e:
File c:\Users\Azkar\miniconda3\envs\quant\lib\site-packages\nest_asyncio.py:70, in _patch_loop.<locals>.run_until_complete(self, future)
[68](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/nest_asyncio.py?line=67) raise RuntimeError(
[69](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/nest_asyncio.py?line=68) 'Event loop stopped before Future completed.')
---> [70](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/nest_asyncio.py?line=69) return f.result()
File c:\Users\Azkar\miniconda3\envs\quant\lib\asyncio\futures.py:196, in Future.result(self)
[195](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=194) exc = self._make_cancelled_error()
--> [196](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=195) raise exc
[197](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/asyncio/futures.py?line=196) if self._state != _FINISHED:
CancelledError:
During handling of the above exception, another exception occurred:
ConnectionError Traceback (most recent call last)
c:\Users\Azkar\OneDrive\Programming\poseiden_engine\MA_trend\MA_IB_live_algo\limit_multi.ipynb Cell 5' in <cell line: 32>()
[33](vscode-notebook-cell:/c%3A/Users/Azkar/OneDrive/Programming/poseiden_engine/MA_trend/MA_IB_live_algo/limit_multi.ipynb#ch0000020?line=32) for symbol in contracts:
[34](vscode-notebook-cell:/c%3A/Users/Azkar/OneDrive/Programming/poseiden_engine/MA_trend/MA_IB_live_algo/limit_multi.ipynb#ch0000020?line=33) req_real = ib.reqTickByTickData(symbol, 'BidAsk')
---> [35](vscode-notebook-cell:/c%3A/Users/Azkar/OneDrive/Programming/poseiden_engine/MA_trend/MA_IB_live_algo/limit_multi.ipynb#ch0000020?line=34) ib.sleep(1)
[36](vscode-notebook-cell:/c%3A/Users/Azkar/OneDrive/Programming/poseiden_engine/MA_trend/MA_IB_live_algo/limit_multi.ipynb#ch0000020?line=35) place_order('BUY', 1, symbol, req_real.ask)
[37](vscode-notebook-cell:/c%3A/Users/Azkar/OneDrive/Programming/poseiden_engine/MA_trend/MA_IB_live_algo/limit_multi.ipynb#ch0000020?line=36) ib.cancelTickByTickData(symbol,'BidAsk')
File c:\Users\Azkar\miniconda3\envs\quant\lib\site-packages\ib_insync\util.py:378, in sleep(secs)
[370](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=369) def sleep(secs: float = 0.02) -> bool:
[371](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=370) """
[372](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=371) Wait for the given amount of seconds while everything still keeps
[373](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=372) processing in the background. Never use time.sleep().
(...)
[376](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=375) secs (float): Time in seconds to wait.
[377](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=376) """
--> [378](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=377) run(asyncio.sleep(secs))
[379](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=378) return True
File c:\Users\Azkar\miniconda3\envs\quant\lib\site-packages\ib_insync\util.py:334, in run(timeout, *awaitables)
[332](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=331) result = loop.run_until_complete(task)
[333](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=332) except asyncio.CancelledError as e:
--> [334](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=333) raise globalErrorEvent.value() or e
[335](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=334) finally:
[336](file:///c%3A/Users/Azkar/miniconda3/envs/quant/lib/site-packages/ib_insync/util.py?line=335) globalErrorEvent.disconnect(onError)
ConnectionError: Socket disconnect
The code simplified as per below:
import pandas as pd
import numpy as np
from datetime import datetime
from ib_insync import *
util.startLoop()
util.logToConsole()
ib = IB()
ib.connect('127.0.0.1', 6000, clientId=1)
contracts = [Stock(stonk,'SMART','USD') for stonk in ('AAPL','TSLA','JPM')]
ib.qualifyContracts(*contracts)
for contract in contracts:
bar = ib.reqHistoricalData(contract,
endDateTime='',
durationStr='10 D',
barSizeSetting='10 mins',
whatToShow='TRADES',
useRTH=True,
keepUpToDate=True)
def place_order(direction, size, contract, price):
if direction == 'BUY':
contract_order = LimitOrder('BUY', size, price)
trade = ib.placeOrder(contract, contract_order)
elif direction == 'SELL':
contract_order = LimitOrder('SELL', size, price)
trade = ib.placeOrder(contract, contract_order)
while True:
for symbol in contracts:
req_real = ib.reqTickByTickData(symbol, 'BidAsk')
ib.sleep(1)
place_order('BUY', 1, symbol, req_real.ask)
ib.cancelTickByTickData(symbol,'BidAsk')
Tried different variations of the code but the error persists. Thinking of using another way to get current bid/ask if this doesn’t work.
Cheers
Issue Analytics
- State:
- Created a year ago
- Comments:8 (4 by maintainers)
Top Results From Across the Web
insync@groups.io | ConnectionError: Socket disconnect
Occasionally, I need to kill the ib gateway for code updates, testing on another machine, etc. Killing the gateway previously kept the event ......
Read more >Connection raises TimeoutError, but IB gateway is running ...
The TimeoutError exception raises when ib_insync connects to ibgw ... Is there a socket connection in CLOSE_WAIT state during the issue?
Read more >Source code for ib_insync.client - Read the Docs
_logger.error('Make sure API port on TWS/IBG is open') raise. [docs] def disconnect(self): """Disconnect from IB connection.""" self.
Read more >ib_insync - Read the Docs
TimeoutError exception is raised. ... Disconnect from a TWS or IB gateway application. ... Support socket protocol version 176.
Read more >TWS IB Gateway (version 972/974) Client keeps disconnecting
socket connection for client{10} has closed. Connection terminated. Here's my main code for starting the app: class TestApp(TestWrapper, ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thanks @mrwillett I didn’t have exactly the same problem, but one very similar. I do suspect, however, that the problem @miali88 will be fixed by your code sample. One thing, if I may. cancelTickByTickData is looking for exactly the same contract as was provided by reqTickByTickData. So, in your solution, I would change this:
for ticker in tick_bars: ib.cancelTickByTickData(ticker.contract.symbol, 'BidAsk')
to this:for contract in contracts: ib.cancelTickByTickData(contract, 'BidAsk')
Thanks again for your help. KHI can’t reproduce the issue either with this simplified case:
If the connection is actively dropped by TWS/gateway then that tends to be a sort of punishment for what the API is doing.