开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育
asyncio example 8
Hi, Ewald at some point had an example of using asyncio in one of his notebook examples. But I cant find it in the new ib_async or the previous ib_insync. Was it removed at some point.....if so, question (1), does anyone know where i could find this example? I have been using ib_insync for several years in a way that runs through a series of executions then ends. I now want to take this to another level where the program runs and monitors for a given opportunity continuously through the day session.......so I am assuming i may need to learn how to implement with asyncio, given comments on this S.O question https://stackoverflow.com/questions/76348014/running-ib-insyn-in-a-while-true-loop-that-buys-and-sells-on-tws-instance question (2) can anyone point me to any specific examples that help me understand how to implement an algo as a continuously running/monitoring process? This part is hard for me as I am a self-taught programmer, and according to the S.O link there seem to be some pitfalls in doing this. Finally, thank you so much to the extremely generous people who have taken up Ewalds legacy in continuing this library. Regards B.
Started by in_woolloomooloo @ · Most recent @
Mid price for options spread 3
Hi Guys, does anybody have experience with midpoint()). I am showing the code below. I suspect this may not be 100% reliable. I am thinking of calculating the mid price as bid + ask/ 2, what is your opinion? Thank you, # Step 1: Define the long/short calls symbol = 'TSLA' long_strike = 220 short_strike = 225 expiry = '20241220' assert long_strike < short_strike, "Not a bull call debit spread" long_call = Option(symbol=symbol, lastTradeDateOrContractMonth=expiry, strike=long_strike, right='C', exchange='SMART', currency='USD') short_call = Option(symbol=symbol, lastTradeDateOrContractMonth=expiry, strike=short_strike, right='C', exchange='SMART', currency='USD') # Qualify the contracts ib.qualifyContracts(long_call, short_call) # Print long and short calls to check if they are correctly defined print(long_call) print(short_call) combo_legs = [ ComboLeg(conId=long_call.conId, ratio=1, action='BUY', exchange='SMART'), ComboLeg(conId=short_call.conId, ratio=1, action='SELL', exchange='SMART') ] bull_call_debit_spread = Bag(symbol=symbol, comboLegs=combo_legs, exchange='SMART') # Print the bull call debit spread to verify print(bull_call_debit_spread) ticker = ib.reqMktData(bull_call_debit_spread, "", False, False) ib.sleep(2) # Print ticker information to diagnose any issues print(ticker) print('Bid:', ticker.bid) print('Ask:', ticker.ask) print('Midpoint:', ticker.midpoint()) ticker.midpoint()
Started by Draql12 @ · Most recent @
Handling Error 201 3
Any idea to handle the following error: Error 201, reqId 1285: Order rejected - reason:Order has been cancelled already, too late to replace Error 201, reqId 1285: Order rejected - reason:Prior submit/modify was rejected
Started by Kianti @ · Most recent @
Error 162, Historical Market Data Service error message:API scanner subscription cancelled: 2
Hello, i am using a basic scanner, that is repeated in a loop: if ENABLE_BUYING and ((is_premarket() and PREMARKET_ONLY) or not PREMARKET_ONLY): scan_sub = ScannerSubscription( instrument='STK', locationCode='STK.US.MAJOR', scanCode='TOP_PERC_GAIN' ) scan_results = ib.reqScannerData(scan_sub) scan_results = scan_results[:10] # Limit to top 10 results Everything works fine, but my terminal gets flooded with this error: Error 162, reqId 33346: Historical Market Data Service error message:API scanner subscription cancelled: 33346 They only mention of this error in the docs is that you can ignore it. I found other posts in the TWSAPI group, but they also dont know how to fix it. Any suggestions?
Started by saschaludo@... @ · Most recent @
Ticker.Tickfilter.timebars usage?
Hey everyone, Thank you for keeping this project and forum up and running. Writing to ask if someone has any examples or pointers of how tick data can be aggregated into timebars? The functionality seems to exist already, I just haven't been able to put it together on my own. ib_async: Ticker.Tickfilter.timebars I appreciate whatever comments you can provide.
Started by Some_guy_555 @
conditional orders 3
Hi, I am trying to do a conditional order with two OR conditions e.g. a price condition and time condition i.e. the the order will execute with EITHER the price condition OR the time condition is met. Is there an example to do so? Thanks Andy
Started by andyl9259@... @ · Most recent @
Starting and stopping market data using ticker object 3
Hi all, First thanks for resurrecting the forum following Ewald's sad passing. He was very kind and helpful to me when i was getting my head around Insync. My problem now though is that I need to both start streaming a ticker, and also to stop it later. I can start it no problem: stock_symbols = ['SPY', 'AAPL'], stocks = [Stock(symbol, 'SMART', 'USD') for symbol in stock_symbols] for stock in stocks: ib.qualifyContracts(*stocks) ticker = ib.reqMktData(stock, '', False, False) ..but have been unable to selectively cancel a ticker, ie cancel AAPL and keep SPY streaming. This seems to be because there is no reqID fround to identify the tickers. Any help would be much appreciated. Thanks Dan
Started by Daniel Stewart @ · Most recent @
Email digests 3
Yes, FP was helping me with them, but first I was away for a while and now that I'm working on them again, I am having issues with some code he gave me. It seemed like a simple process when I started, but to strip out email addresses, but to keep in a names so you can follow a thread was tough. Also to keep attachments such as images and files was another fun task. I am working on it again now, but any help would be fine since my python is obviously not as exceptional as I would like to think! Mel
Started by Mel @ · Most recent @
Merci 6
Thanks for letting me join this group What are the plan concerning the archive regarding the previous post on ib_insync, this was a gold mine of learning and it seems a missed opportunity for everyone not to migrate it to the new group? Have a great day Olivier Van Parys
Started by Sdoof @ · Most recent @
Installing ib_async 5
Hello, I tried to install the package on my Ubuntu laptop but got the error "This environment is externally managed". After searching for resolutions online, first I tried the virtual environment option but that got messy. Instead I was able to install it using pipx with 'pipx install --include-deps ib_async' followed by 'pipx ensurepath'. At this point, running 'pipx list' confirms that the package was installed but 'pip list' does not display it. (I think this is expected) Now, when running my Python script to connect with IB and place orders, I'm getting 'ModuleNotFoundError' error. Anyone know how to resolve this? Thanks!
Started by R Malhotra @ · Most recent @
Update order 6
Hi, I’m running an algo that triggers Market-on-Open orders. As it’s a MOO order the price is not known (although my logic will use a ticker to decide to trigger or not) at the time the order is created. As I want to have a stop loss, I have added a commissionReportEvent handler. When orders are filled, I wait for the order to be fully filled, “trade.order.totalQuantity == fill.execution.cumQty” and I update the stop loss attached to the MOO order, with a stop loss price in line with the avg fill price. This is working all fine. The problem that I have is that the updated order is never actually in status “submitted”. As per the orders notebook https://nbviewer.org/github/ib-api-reloaded/ib_async/blob/main/notebooks/ordering.ipynb, I update the order, execute placeOrder(contract,updated_order), status is ‘PendingSubmit’ then —> ‘PreSubmitted’ but it never reaches “Submited” There is no error message, nothing on the log not TWS. I used to have some problems due to incorrect values on the order, but those were showing an actual error message. Now there is nothing. Any pointer to the right direction will be appreciated. Cheers
Started by Gonzalo Saenz @ · Most recent @
What is the proper way to get an option's greeks? 3
Any code samples? TIA.
Started by Lipp F. @ · Most recent @
Incorrect 4
I have been running ib_insync/ib_async in production for over 4 years with few issues. Lately I have seen more and more cases where I receive missing or incorrect positionEvent responses. I checked the ibgateway API logs, and the API looks correct. Does anyone know why the positionEvent was missed, but incorrect ones continued to be emitted? Any pointers on how to fix or debug this? What triggers a PositionEvent? I am considering using the Portfolio position update + recent fills to sanity check the position and cancel orders if there is a mismatch. Is anyone else doing something similar? I'm worried about timing / race conditions of doing this Here is one recent example, times are Pacific 20240606.081023 Bought 500 WESTW $2.06, correctly received positionEvent, position=500 20240606.081023.294 I handle_position_update WESTW, equity=WESTW: Position(account='UXXX', contract=Warrant(conId=582332975, symbol='WEST', lastTradeDateOrContractMonth='20270829', strike=11.5, right='C', multiplier='1', exchange='NASDAQ', currency='USD', localSymbol='WESTW', tradingClass='WEST'), position=500.0, avgCost=2.06) 20240606.081023.294 I handle_position_update WESTW new qty=500, was 0 081939 Filled 359 of order to sell 500 WESTW $2.30 20240606.081939.129 I handle_position_update WESTW, equity=WESTW: Position(account='UXXX', contract=Warrant(conId=582332975, symbol='WEST', lastTradeDateOrContractMonth='20270829', strike=11.5, right='C', multiplier='1', exchange='NASDAQ', currency='USD', localSymbol='WESTW', tradingClass='WEST'), position=141.0, avgCost=2.06010145) 20240606.081939.129 I handle_position_update WESTW new qty=141, was 500 20240606.081939.274 I handle_exec_details, trade = WESTW WESTW permId=461612295 orderId=1040716 SELL 500.0 2.3 ref=P-WrtBS Submitted filled=359.0, log(msg=Fill [email protected], status=Submitted 08:19:39) 081939.275 filled remaining 141, position should be 0 now. Fill and commission responses are correct, but a positionEvent was never received 20240606.081939.275 I handle_order_status trade summary=WESTW WESTW permId=461612295 orderId=1040716 SELL 500.0 2.3 ref=P-WrtBS Filled filled=500.0, log(msg=Fill [email protected], status=Submitted 08:19:39) 20240606.081939.276 I handle_commission_report, fill=Fill(contract=Contract(secType='WAR', conId=582332975, symbol='WEST', lastTradeDateOrContractMonth='20270829', strike=11.5, right='C', multiplier='1', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='WESTW', tradingClass='WEST'), execution=Execution(execId='00010196.6661b194.01.01', time=datetime.datetime(2024, 6, 6, 15, 19, 39, tzinfo=datetime.timezone.utc), acctNumber='UXXX', exchange='NASDAQ', side='SLD', shares=359.0, price=2.3, permId=461612295, clientId=1002, orderId=1040716, liquidation=0, cumQty=359.0, avgPrice=2.3, orderRef='P-WrtBS', evRule='', evMultiplier=0.0, modelCode='', lastLiquidity=1, pendingPriceRevision=False), commissionReport=CommissionReport(execId='00010196.6661b194.01.01', commission=0.118976, currency='USD', realizedPNL=86.004596, yield_=0.0, yieldRedemptionDate=0), time=datetime.datetime(2024, 6, 6, 15, 19, 39, 136787, tzinfo=datetime.timezone.utc)) 20240606.081939.348 I handle_commission_report, fill=Fill(contract=Contract(secType='WAR', conId=582332975, symbol='WEST', lastTradeDateOrContractMonth='20270829', strike=11.5, right='C', multiplier='1', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='WESTW', tradingClass='WEST'), execution=Execution(execId='00010196.6661b196.01.01', time=datetime.datetime(2024, 6, 6, 15, 19, 39, tzinfo=datetime.timezone.utc), acctNumber='UXXX', exchange='NASDAQ', side='SLD', shares=141.0, price=2.3, permId=461612295, clientId=1002, orderId=1040716, liquidation=0, cumQty=500.0, avgPrice=2.3, orderRef='P-WrtBS', evRule='', evMultiplier=0.0, modelCode='', lastLiquidity=1, pendingPriceRevision=False), commissionReport=CommissionReport(execId='00010196.6661b196.01.01', commission=0.046729, currency='USD', realizedPNL=33.778964, yield_=0.0, yieldRedemptionDate=0), time=datetime.datetime(2024, 6, 6, 15, 19, 39, 273794, tzinfo=dateti
Started by Scott Kister @ · Most recent @
unexpected keyword argument 'conid' in Contract() 3
In the docs of Contract() there is an example: Contract(conId=270639) which should return a Contract Object. But I got the error: Traceback (most recent call last): File "...\venv\lib\site-packages\IPython\core\interactiveshell.py", line 3577, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-23-8d88e504d067>", line 1, in <module> Contract(conid=270639) TypeError: Contract.__init__() got an unexpected keyword argument 'conid' In the source: ... @staticmethod def create(**kwargs) -> "Contract": """ Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. """ ... is no conId. I thought if I have a conId, I dont need any further Contract description. Am I wrong or is it a bug? Regards Hans
Started by Papageno @ · Most recent @
Quantity for MIDPRICE orders 3
Hello, When placing a Midprice order via the TWS API, I do not have the quantity, since the actual price isn't known yet. But I do have the $ amount to use for the order. I know that TWS, mobile app etc. allow placing the order using $ amount, and then the app calculates the quantity, rounded down to the nearest integer. Is this also possible via the API i.e. provide the $ amount instead of quantity? Thank you!
Started by R Malhotra @ · Most recent @
Incorrect positionEvents received 2
As a workaround I started verifying if the positionEvent or execDetailsEvent received matches the last verified position plus any fills since then. This is an improvement and caught some cases, but I saw one instance where I did not receive either a positionEvent or an execDetailsEvent after the second of two partial fills, but did receive an orderStatusEvent with the full fill. I will start using those in the verification as well. Also, I somehow missed the trade.fillEvent, thanks for that tip, I will start handling that as well, hopefully it is reliable. This seems to only happen on rapid subsequent partial fills. I will look at filing an issue with ib-api-reloaded and hopefully someone can give me pointers on how to debug it further.
Started by Scott Kister @ · Most recent @
Sell orders executing as soon as I buy 3
You need to add lines for triggerPrice and triggerMethod for stop order. I think that is unset. And check the prices again. Last resort, place an order manually from IBKR TWS and then check the order object from API to know what exactly is needed in the order that you send. That works Pratik Babhulkar
Started by Pratik Babhulkar @ · Most recent @
IB-insync library - how to invoke the priceSizeTick() function 5
Hello, IB-insync is a python library developed to make it easier to work with the TWS api. https://ib-insync.readthedocs.io/_modules/ib_insync/client.html# I would like to know how to invoke the method 'priceSizeTick' in the ib_insync.wrapper class. or alternatively how to invoke the 'priceTick' and 'sizeTick' functions. (which are combined in the 'priceSizeTick' function) Please attach a code script if you can. Thank you! Itay
Started by itaysh @ · Most recent @
Precautionary settings while sending orders via API
Hi guys, Not a specific ib_async query but a general query about precautionary settings and API orders. I have always bypassed precautionary settings. However, attempted to let the orders go through precautionary settings this time with Total Value Limit of $20k. Most of the orders go through fine. However, for some of the orders, I receive error "The Total Value Limit of the following order "ID:XYZ" can not be verified. Restriction is specified in Precautionary Settings of Global Configuration/Presets" What does this error mean? I am trading SPX Weekly Options and spreads on that. I am placing Spread - Combo - Market Order with IBALGO. The order value is well within $20k. Also, error does not seem to state that "Order Value exceeds the limit". It instead states something like "Value limit can not be verified". Does this mean, somehow, IB server could not get an idea of the Order Value and hence cannot check that precaution pass? And hence it rejects the order? Anyone else faced similar error and how to circumvent that with precautions in place? Regards, Pratik Babhulkar
Started by Pratik Babhulkar @
Sponsorship of group 14
I have received one sponsor and we are at 50 members and growing daily. Are people still interested in sponsoring the group? If I get some sponsors (they don't need to be much to cover costs) I will switch to the paid model. That will allow us to go past the 100 member cap as well as it allows us to have sub threads and also to have a file repository among other things. Thanks, Mel
Started by Mel @ · Most recent @
Current Image
Image Name
Sat 8:39am