开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育

ib.reqMktData() does not get certain fields when connecting to the gateway the second time.

 

I am having an odd problem. Everything works as expected when my client makes an initial connection to the gateway. However, if I restart the client process, sometimes reqMktData()won't get all the fields. Specifically, if I do the below, I find everything in the ticker object are filled except for bid and bidSize, which are nan. Sometimes, it is the close price that is nan.


ticker  = ib.reqMktData(contract)
asyncio.sleep(0.5)
# ticker.bid, ticker.bidSize, ticker.close may be nan

I have logic to retry the subscription as follows, but it rarely does anything:


ib.cancelMktData(contract)
asyncio.sleep(0.1)
ib.reqMktData(contract)

When this happens, the same few contracts out of 30 have this problem no matter how many times I retry (like the above). The other contracts are completely fine.

This does not happen every time. Occasionally, restarting the client to make a new connection the second time is okay, and when the second time is okay, it tends to be okay for subsequent connections. Over 50% of the time, however, making the connection the second time will have the above-described problem. If the second time fails, all subsequent connections will also fail.

The problem is not limited to the gateway. Connecting with TWS has exactly the same problem.

Restarting the gateway fixes this problem. I have never seen this happening to the initial connection to the gateway instance. This seems to say that the gateway has to be restarted every time I restart my client, which is tedious.

Has anyone encountered similar issues?


Determining which stock is bringing my portfolio into a loss

 

Hi all,

I am trying to write some code to determine which stock is bringing my
portfolio into a loss.

My logic is to see if the averageCost is greater than the current market
price for each stock in the portfolio.

The problem is that the current market price is nan. I am running this code
after market close. Here is the relevant snippet. What am I missing?
ib.connect('127.0.0.1', 4001, clientId=999990)
positions=ib.positions()
lc=0
for p in positions:

[ticker] = ib.reqTickers(p.contract)
print(p.contract.symbol)

print("number of shares=" + str(p.position))
print("Cost per share=",ib.portfolio()[lc].averageCost)
print("Current price per share=",ticker.marketPrice())

lc+=1
ib.sleep(1)
Pranav


Re: Clicking an override button

 

开云体育

Hi,

?

I do not use as sophisticated an approach. I have just set the property for all orders. There is no harm in setting it that I have seen.

?

Pranav

?

From: [email protected] <[email protected]> On Behalf Of Gonzalo Saenz via groups.io
Sent: Saturday, March 29, 2025 8:24 PM
To: [email protected]
Subject: Re: [ib-async] Clicking an override button

?

Thanks for your reply

?

So if I follow you correctly,?

?

  • you submit an order,?
  • it fails,?
  • you check your Trade.log for the error message,?
  • and in a future order, you set Order.advancedErrorOverride based on the error message on previous point

?

?

?

?



On 28 Mar 2025, at 00:53, Pranav Lal <pranav@...> wrote:

?

Hi?Gonzalo,

?

Documentation is sketchy to say the least. See the below link.?

?

The rest of it was trial and error.?

?

Pranav

?


Re: Clicking an override button

 

开云体育

Thanks for your reply

So if I follow you correctly,?

  • you submit an order,?
  • it fails,?
  • you check your Trade.log for the error message,?
  • and in a future order, you set Order.advancedErrorOverride based on the error message on previous point





On 28 Mar 2025, at 00:53, Pranav Lal <pranav@...> wrote:

Hi?Gonzalo,
?
Documentation is sketchy to say the least. See the below link.?
?
The rest of it was trial and error.?
?
Pranav


Re: Clicking an override button

 

开云体育

Hi Gonzalo,

?

Documentation is sketchy to say the least. See the below link.

?

The rest of it was trial and error.

?

Pranav


Re: Clicking an override button

 

开云体育

Where did you get this information? Is there any documentation for this?

From time to time my orders are canceled, this might help?





---- On Thu, 27 Mar 2025 17:41:35 +0100 Pranav Lal<pranav@...> wrote ----

Hi all,


Problem solved. I had to use a key value pair when specifying the string in
the advancedErrorOverride property.
advancedErrorOverride="8229,SURVEILLANCE"

I initially thought that ib_async did not support this property which is why
I switched to the tws API.
Pranav








Re: Clicking an override button

 

Hi all,


Problem solved. I had to use a key value pair when specifying the string in
the advancedErrorOverride property.
advancedErrorOverride="8229,SURVEILLANCE"

I initially thought that ib_async did not support this property which is why
I switched to the tws API.
Pranav


Re: Trying to load data asynchronously and struggling with asyncio again

 

ib.reqHistoricalDataAsync takes timeout parameter, set it to 0 and this method will not time out.


Re: ib.reqTickers() conflicts with ib.reqTickByTickData()

 

thank you for replying, I have identified the problem: the reqTickers was nested in the reqTickByTickData, so I changed the App structure. BTW do you know the function to use for nested call (even though I remember that nested asyncio and blocking was not recommended)? best


Re: Live and paper data mixed

 

What seems to be happening is the instance of IB() is keeping data and not actually sending a request to TWS. The API logs only show one request being sent per connection, not the two I was expecting from the code above.

If I have two instances of IB(), and switch between those, I get correct data. Just disconnecting, changing port, and reconnecting within the same instance of IB() seems to be causing the confusion.

Any delay between disconnect and reconnect, makes no difference as long as it's still the same instance of IB(). Could someone who maintains the library investigate?


Re: Live and paper data mixed

 

开云体育

Hi Glen,

?

I have a similar setup but do not switch programmatically between the 2 gateways. However, how about adding a delay between the switching? This would ensure connection closure.

?

Pranav


Live and paper data mixed

 

I have a program that will place trades in either the paper or live account. I run both platforms simultaneously on the same machine. It crashes when I try get my account value after switching from one to the other because I get the first result over again. I have a support ticket in with IB, but they keep suggesting it's my code. Can anyone here create the problem to help me sort this out?

With two instances of TWS open, one paper and one live, here's the simplest code I've run to show the problem:

from ib_async import *

def ensure_connection(ib: IB, host: str, desired_port: int, client_id: int): """Ensure IB is connected to the desired port. Reconnect if necessary."""

# Check if IB is connected and if the port matches
if ib.isConnected() and ib.client.port == desired_port:
    print(f"Already connected on the desired port: {desired_port}")
    return

# If connected but on the wrong port, disconnect
if ib.isConnected():
    print(f"Connected on wrong port {ib.client.port}, disconnecting...")
    ib.disconnect()
    ib.sleep(1)

# Reconnect on the correct port
print(f"Connecting to port {desired_port}...")
ib.connect(host, desired_port, client_id)

print(f"Connected on port: {ib.client.port}")

ib = IB()

IBPort = 7496

ensure_connection(ib, "127.0.0.1", IBPort, 33) print(ib.isConnected()) print(ib.client.port)

SummaryAccountValue = ib.accountSummary() print(SummaryAccountValue)

IBPort = 7497

ensure_connection(ib, "127.0.0.1", IBPort, 33) print(ib.isConnected()) print(ib.client.port)

SummaryAccountValue = ib.accountSummary() print(SummaryAccountValue)

ib.disconnect()

print(ib.isConnected()) print(ib.client.port)

IBPort = 7497

ensure_connection(ib, "127.0.0.1", IBPort, 33) print(ib.isConnected()) print(ib.client.port)

SummaryAccountValue = ib.accountSummary() print(SummaryAccountValue)

IBPort = 7496

ensure_connection(ib, "127.0.0.1", IBPort, 33) print(ib.isConnected()) print(ib.client.port)

SummaryAccountValue = ib.accountSummary() print(SummaryAccountValue)

ib.disconnect() ''' ib.fills also seems to have problems. For the first connection, it will show correct information, but on the second connection, it will show the first plus the second.

Is there a problem somewhere in the ib_async library or is this an IB issue? Can anyone reproduce this or suggest how I can fix it?

Glenn


Re: Clicking an override button

 

Hi all,

I am answering my own question. I suspect I need to specify order conditions
and allow the advancedErrorOverride flag.

How do I do this?
Pranav

-----Original Message-----
From: Pranav Lal <pranav@...>
Sent: Monday, March 24, 2025 1:36 PM
To: '[email protected]' <[email protected]>
Subject: Clicking an override button

Hi all,

I have recently begun getting messages that a security is under
surveillance.
The exact entry in my program's log is below.
2025-03-24 06:59:15,321 ib_async.wrapper ERROR Error 201, reqId 7: Order
rejected - reason:Security is under Surveillance Measure - The scrip PE is
greater than 50 for the previous 4 trailing quarters.<br><br><br>Would you
like to continue?.

How do I click yes programmatically?
Pranav


Clicking an override button

 

Hi all,

I have recently begun getting messages that a security is under
surveillance.
The exact entry in my program's log is below.
2025-03-24 06:59:15,321 ib_async.wrapper ERROR Error 201, reqId 7: Order
rejected - reason:Security is under Surveillance Measure - The scrip PE is
greater than 50 for the previous 4 trailing quarters.<br><br><br>Would you
like to continue?.

How do I click yes programmatically?
Pranav


Re: ib.reqTickers() conflicts with ib.reqTickByTickData()

 

These two methods are very different:
?
reqTickers(*contracts,?regulatorySnapshot=False)

Request and return a list of snapshot tickers. The list is returned when all tickers are ready.

This method is blocking.

?

reqTickByTickData(contract,?tickType,?numberOfTicks=0,?ignoreSize=False)

Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks.

?

Can you post more code snippet, and more importantly what you are trying to achieve?


Re: Unable to determine when an order is submitted

 

开云体育

Hi Elat,

<snip Moreover the status gets fired once and not for each status.

PL] Ouch, that is one reason why my code is not executing the way I expect. I’ll do some tweaking.

?

Thanks for your input.

Pranav


Re: Unable to determine when an order is submitted

 

Hi Prenav,?
?
be careful on choosing the status.. I've noticed in paper trading that stutus (PreSubmitted) could never be reached as those statuses are executed very quickly. Moreover the status gets fired once and not for each status.
?
Elat


ib.reqTickers() conflicts with ib.reqTickByTickData()

 

Hello Everyone, when building the APP (not in a notebook Jupyter), if call the ib.reqTickers() after having called ib.reqTickByTickData() it goes in overflow and crashes. But, if I call reqTickers() before reqTickByTickData works perfectly! I have tried with ib.sleep(30) but nothing. Any help? Thank you.


Re: Unable to determine when an order is submitted

 

Might work in simulation, but remember in real trade there will be delay after placing order:
?

? ? stop_loss_trade = ib.placeOrder(contract, stop_loss_order)

# BELOW might not be true always so quickly!

? ? if stop_loss_trade.isActive():

?

You should stick to event driven for robustness as you had before.


Re: Unable to determine when an order is submitted

 

开云体育

Hi biney59,

Thanks for your suggestion.

?

I got rid of the event logic and the program is working as I want it to at least in the simulator.

?

Here is a snippet of the modified code.

? ? # Create the limit order (parent order)

? ? limit_order = LimitOrder(order_type, order_quantity, limit_price, outsideRth=True, transmit=False)

? ?

? ? # Place the limit order

? ? print("Placing limit order")

? ? parent_trade = ib.placeOrder(contract, limit_order)

? ?

? ? # Create the stop loss order (child order)

? ? stop_loss_order = Order()

? ? stop_loss_order.action = stop_loss_action

? ? stop_loss_order.orderType = "STP"

? ? stop_loss_order.totalQuantity = order_quantity

? ? stop_loss_order.auxPrice = stop_loss_price

? ? stop_loss_order.parentId = parent_trade.order.orderId

? ? stop_loss_order.transmit = True

? ?

? ? # Place the stop loss order (this transmits both orders)

? ? print("Placing stop loss order")

? ? stop_loss_trade = ib.placeOrder(contract, stop_loss_order)

? ? if stop_loss_trade.isActive():

? ? ? ? ib.disconnect()

? ? ? ? print("Exiting")

? ? ? ? sys.exit(0)

? ? # Run the event loop to process order status updates

? ? ib.run()

?

?

Pranav