Keyboard Shortcuts
Likes
- Ib-Async
- Messages
Search
Re: How to check TWS connectivity?
toggle quoted message
Show quoted text
-------- Original message -------- From: "R Malhotra via groups.io" <rachan.malhotra@...> Date: 2025-01-07 5:47 p.m. (GMT-08:00) Subject: [ib-async] How to check TWS connectivity? Using the API, what is a good way to check if the TWS is connected to IB servers?
|
Re: How to check TWS connectivity?
toggle quoted message
Show quoted text
-------- Original message -------- From: "Pranav Lal via groups.io" <pranav@...> Date: 2025-01-07 6:23 p.m. (GMT-08:00) Subject: Re: [ib-async] How to check TWS connectivity? Hi, ? I cannot remember the exact name of the variable but there is a is_ready variable that tells you if the API is ready to go. ? Pranav |
Re: How to check TWS connectivity?
开云体育Hi, ? I cannot remember the exact name of the variable but there is a is_ready variable that tells you if the API is ready to go. ? Pranav |
Re: Option Open Interest
Thank you!
Confirming that the following code works both during and before and after market open hours: ?
from ib_async import *
import time ?
ib = IB()
ib.connect('127.0.0.1', 4001, clientId=170)
?
ib.reqMarketDataType(1)
?
contract = Option('GOOGL', '20250117', 195, 'C', 'SMART')
contract = ib.qualifyContracts(contract)[0] ?
print("Printing contract")
print("") print(contract) print("") ?
a = ib.reqMktData(contract, genericTickList='100,101')
ib.sleep(2) # wait 2 seconds for the first data packets to arrive ?
print("Printing requested market data")
print("") print(a) print("") print("marketDataType is ", a.marketDataType) print("end of printing") ?
ib.disconnect()
?
The output of the relevant variable "a" on 31 December 2024 after market close is:
?
?
Ticker(contract=Option(conId=584786601, symbol='GOOGL', lastTradeDateOrContractMonth='20250117', strike=195.0, right='C', multiplier='100', exchange='SMART', currency='USD', localSymbol='GOOGL 250117C00195000', tradingClass='GOOGL'), time=datetime.datetime(2024, 12, 31, 22, 26, 39, 1784, tzinfo=datetime.timezone.utc), minTick=0.01, bid=-1.0, bidSize=0.0, ask=-1.0, askSize=0.0, last=2.01, lastSize=5.0, volume=3203.0, high=3.15, low=1.88, close=3.14, putOpenInterest=0.0, callOpenInterest=22092.0, ticks=[TickData(time=datetime.datetime(2024, 12, 31, 22, 26, 39, 1784, tzinfo=datetime.timezone.utc), tickType=5, price=2.01, size=5.0)], bidGreeks=OptionComputation(tickAttrib=0, impliedVol=0.25391115222998306, delta=None, optPrice=None, pvDividend=0.0, gamma=None, vega=-2.0, theta=-2.0, undPrice=189.0066375732422), askGreeks=OptionComputation(tickAttrib=0, impliedVol=0.25592227507404464, delta=None, optPrice=None, pvDividend=0.0, gamma=None, vega=-2.0, theta=-2.0, undPrice=189.0066375732422), lastGreeks=OptionComputation(tickAttrib=0, impliedVol=0.2561369063292868, delta=0.3078586406258187, optPrice=2.009999990463257, pvDividend=0.0, gamma=0.03386755720078562, vega=0.1486588979505994, theta=-0.11558233715117001, undPrice=189.0066375732422), modelGreeks=OptionComputation(tickAttrib=0, impliedVol=0.25530032176703077, delta=0.30719285939414664, optPrice=1.9897448496104688, pvDividend=0.0, gamma=0.033950430193128225, vega=0.14867813869422197, theta=-0.11512370414862398, undPrice=189.0066375732422), bboExchange='c70003', snapshotPermissions=3)
?
?
?
?
|
Re: Trying to load data asynchronously and struggling with asyncio again
Hey Christian,?
?
Sorry, I since realized that your issue is with timeouts, not errors. Perhaps one of these settings will solve the problem:
?
ib.connect('127.0.0.1',7497, clientId=1, timeout=0) # 0 seconds=indefinite --- initial connect timeout – If establishing the connection takes longer than timeout seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
?
ib.setTimeout(timeout=600) # --- Set a timeout for receiving messages from TWS/IBG, emitting timeoutEvent if there is no incoming data for too long.
|
Re: Trying to load data asynchronously and struggling with asyncio again
I ran your code and got the following output:?
?
Loading 2024-12-01
Loading 2024-12-02 BarData(date=datetime.datetime(2024, 12, 2, 6, 59, tzinfo=datetime.timezone.utc), open=1.270505, high=1.270505, low=1.27045, close=1.27047, volume=-1.0, average=-1.0, barCount=-1) BarData(date=datetime.datetime(2024, 12, 3, 6, 59, tzinfo=datetime.timezone.utc), open=1.265025, high=1.265035, low=1.26496, close=1.264965, volume=-1.0, average=-1.0, barCount=-1) All done ?
What errors are you receiving? |
Re: Option Open Interest
Hey Dennis,?
?
The following code should do the trick. Including a link to the IB docs' ticker codes in case you don't already have it:
?
contract = Option('GOOGL', '20250117', 195, 'C', 'SMART')
contract = ib.qualifyContracts(contract)[0]
print(contract)
a = ib.reqMktData(contract, '100,101')
ib.sleep(2) # wait 2 seconds for the first data packets to arrive
print(a)
|
Re: Anyone used the Web API?
I've recently started experimenting with the Web API, after getting a little fed up with TWS API issues. ?From what I understand if you are an individual trader (not an institution) the only way to access the Web API as of now is through a (not to be confused with the TWS Gateway).? This is another Java program that acts as a middleman for authenticating to the WebAPI.? From my limited experience thus far, it has been much more reliable than the TWS Gateway. There is an OAuth2 authentication option, but it appears to be reserved only for institutional users at the moment.
?
The library which has been very helpful in getting up-and-running quickly.? It serves essentially the same purpose that ib-async serves for the TWS API.? My one complaint about the Web API would be that there doesn't seem to be a simple way to stream real-time candles data, such as the "5 second real-time bars" endpoint provided by the TWS API.? I am currently in a back-and-forth with the IBKR helpdesk trying to understand what exactly their MarketData websocket provides.? This is my experience so far, about a week playing around with the Web API.? I would love to hear other's experience as well!
?
? |
Anyone used the Web API?
I run a bot using the ib_async wrapper but when TWS connectivity is unstable, it runs into issues. Before working to fix this, I'd like to understand if anyone has used the and how that experience has been in terms of connectivity, market data, order execution etc.
?
Thank you! |
Option Open Interest
I'm trying to get an option open interest using ib_async, but it does not show the open interest at all.
?
The code I have using ib_async is:
?
from ib_async import *
?
ib = IB()
ib.connect('127.0.0.1', 4001, clientId=138)
?
ib.reqMarketDataType(1)
?
option1 = [Option('GOOGL', '20250117', 195, 'C', 'SMART')]
?
ib.qualifyContracts(option1[0])
?
a=ib.reqMktData(option1[0],genericTickList='100',snapshot=False, regulatorySnapshot=False)
print(a)
print("-")
?
b=ib.reqTickers(Option('GOOGL', '20250117', 195, 'C', 'SMART'))
print("Volume ", b[0].volume)
print("callOpenInterest ", b[0].callOpenInterest)
print("putOpenInterest", b[0].putOpenInterest)
print("impliedVolatility ", b[0].impliedVolatility)
?
ib.disconnect()
?
?
the output of this code is
?
Ticker(contract=Option(conId=584786601, symbol='GOOGL', lastTradeDateOrContractMonth='20250117', strike=195.0, right='C', multiplier='100', exchange='SMART', currency='USD', localSymbol='GOOGL 250117C00195000', tradingClass='GOOGL'))
-
Volume 1385.0
callOpenInterest nan
putOpenInterest nan
impliedVolatility nan
?
?
which means that open interest is missing.
?
?
Using the IBKR TWS API I can get the open interest but the way to there is a bit less user friendly
?
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
import threading
import time
?
class IBApp(EWrapper, EClient):
? ? def __init__(self):
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.call_open_interest = None
? ? ? ? self.reqId = 1
? ? ? ? self.oi_received = False # Flag to track if tick 27 was received
?
? ? def error(self, reqId, errorCode, errorString, advancedOrderRejectJson=''):
? ? ? ? print(f"Error. Id: {reqId}, Code: {errorCode}, Msg: {errorString}")
?
? ? def tickSize(self, reqId: int, tickType: int, size: float):
? ? ? ? if tickType == TickTypeEnum.OPTION_CALL_OPEN_INTEREST:
? ? ? ? ? ? self.call_open_interest = size
? ? ? ? ? ? self.oi_received = True #set flag to true
? ? ? ? ? ? print(f"TickSize. TickerId:", reqId, "TickType:", tickType, "Size: ", size)
? ? ? ? else:
? ? ? ? ? ? print("Not the expected tick type")
?
? ? def tickSnapshotEnd(self, reqId):
? ? ? ? print(f"TickSnapshotEnd. Ticker Id: {reqId}")
?
def run_loop(app):
? ? app.run()
?
if __name__ == "__main__":
? ? app = IBApp()
? ? app.connect("127.0.0.1", 4001, clientId=20)
? ? api_thread = threading.Thread(target=run_loop, args=(app,), daemon=True)
? ? api_thread.start()
? ? time.sleep(1)
?
? ? contract = Contract()
? ? contract.symbol = "GOOGL"
? ? contract.secType = "OPT"
? ? contract.exchange = "SMART"
? ? contract.currency = "USD"
? ? contract.lastTradeDateOrContractMonth = "20250117"
? ? contract.strike = 195
? ? contract.right = "C"
? ? contract.multiplier = "100"
?
? ? app.reqMktData(app.reqId, contract, genericTickList='101', snapshot=False, regulatorySnapshot=False, mktDataOptions=[]) #request tick 27
?
? ? time.sleep(5) # Wait for a reasonable time for data
?
? ? if app.oi_received: #check flag
? ? ? ? print(f"Option Call Open Interest Size: {app.call_open_interest}")
? ? else:
? ? ? ? print("Did not receive Option Call Open Interest data within the timeout.")
?
? ? app.disconnect()
?
?
The output of this code is
?
Error. Id: -1, Code: 2104, Msg: Market data farm connection is OK:usfarm.nj
Error. Id: -1, Code: 2104, Msg: Market data farm connection is OK:usopt
Error. Id: -1, Code: 2104, Msg: Market data farm connection is OK:usfarm
Error. Id: -1, Code: 2107, Msg: HMDS data farm connection is inactive but should be available upon demand.ushmds
Error. Id: -1, Code: 2158, Msg: Sec-def data farm connection is OK:secdefnj
Not the expected tick type
Not the expected tick type
Not the expected tick type
Not the expected tick type
Not the expected tick type
Not the expected tick type
Not the expected tick type
TickSize. TickerId: 1 TickType: 27 Size: 21890
Not the expected tick type
Option Call Open Interest Size: 21890
?
?
Does anyone use ib_async to get the option open interest and if so could you please share the way to request this data? |
Trying to load data asynchronously and struggling with asyncio again
I'm trying to load historical data. It takes a while, so I thought I could speed it up with asyncio, but it doesn't work. Instead of data, I'm getting timeouts. Here is what I've tried.:?
?
import asyncio I don't understand asyncio well, nor how it works within ib_async. So, I'm stuck here. Could anyone point out where I'm wrong??
?
? |
Re: How to place multiple orders AT THE SAME TIME?
On Wed, Dec 11, 2024 at 06:58 AM, Kianti wrote:
Interesting.. I've never done that and never seen that error. Not sure why but good to know. |
Re: How to place multiple orders AT THE SAME TIME?
Note that in some cases it will be necessary to include a small delay of 50 ms or less after placing the parent order for processing, before placing the child order. Otherwise the error “10006: Missing parent order” will be triggered. I use ib.sleep(0.2) |
Re: How to place multiple orders AT THE SAME TIME?
Your first order has transmit=True, it needs to be transmit=False, and you need to add the parent's order id to your exit orders.
?
The last order in the group that has transmit = True will submit all the orders in the group and you don't need any ib.sleep. |
Re: How to place multiple orders AT THE SAME TIME?
Another idea could be to submit both orders using the Good After Time field. Something like this:?
?
now_plus_3_seconds = datetime.now(tz:=ZoneInfo(key='America/New_York')) + timedelta(seconds = 3)
gat_str = now_plus_3_seconds.strftime('%Y%m%d %H:%M:%S') + ' US/Eastern'
order_1.goodAfterTime = gat_str
order_2.goodAfterTime = gat_str
|
Re: How to attach a stop loss order (Child) to a buy order(Parent)?
That code should work okay I would just remove the following two lines. Are you having any problems running it?
?
parent_order_id = ib.client.getReqId() # --- ib_async handles this for you
?
ib.placeOrder(tesla_contract, parent_order) ?# --- i used to use these types of orders and you can just submit the lowest child order and all of the parents will be sent in the same batch
|