开云体育

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

Re: Not properly parsing modified orders or am I missing the point of `Trade` objects?

 


Here is something that may be related. ?Take a look at line 512 of ib_async/wrapper.py, in the openOrder function, where it does

? ? ? ? ? ? trade.order.lmtPrice = order.lmtPrice
In my experience, after I submit a modified orde via ib_async to change the lmtPrice, later, when the modified order is then accepted by the server, IBKR sends back a response that ib_async handles via this openOrder function. ?Among other things, the openOrder function updates the lmtPrice field of the order registered with the trade (at the line noted above). ? This is how I've been tracking when IBKR accepts price modifications (which doesn't always happen right away). ?This has worked pretty reliably for me. ?There was a short email thread about it in the old ib_insync forum, which I don't have a copy of now.

Here is code for the "patched" limit order object that I've used to implement this. ?It adds a new event that fires when the price is accepted in this way:

class PatchedIBOrder(ibs.Order):
? ? def __init__(self, action, totalQuantity, orderType="LMT", **kwargs):
? ? ? ? ibs.Order.__init__(
? ? ? ? ? ? self,
? ? ? ? ? ? orderType=orderType,
? ? ? ? ? ? action=action,
? ? ? ? ? ? totalQuantity=totalQuantity,
? ? ? ? ? ? **kwargs,
? ? ? ? )
? ? ? ? self.priceAcceptedEvent = Event("priceAcceptedEvent")
? ? ? ? self.acceptedPrice = None
? ? ? ? self._lmtPrice = None

? ? @property
? ? def lmtPrice(self):
? ? ? ? return self._lmtPrice

? ? @lmtPrice.setter
? ? def lmtPrice(self, value):
? ? ? ? self._lmtPrice = float(value) if value else None
? ? ? ? if inspect.stack()[1][3] == "openOrder":
? ? ? ? ? ? self.acceptedPrice = value
? ? ? ? ? ? # logging.warning(f"order {self.priceAcceptedEvent}: price accepted")
? ? ? ? ? ? self.priceAcceptedEvent.emit()
? ? ? ? ? ? # logging.warning(f"order {self.orderId}: price accepted event emitted")


Not properly parsing modified orders or am I missing the point of `Trade` objects?

 

I'm having some issues getting correct modified order data returned by ib_insync and I'm trying to get to the bottom of it.

As an example workflow, I place a position order and a stop order. Once the position order fills, I modify the stop order and send it.

Placed Order

Order object I transmitted to place the order:

Order(orderId=509133, action='BUY', totalQuantity=200, orderType='LIT', lmtPrice=169.97, auxPrice=169.94, tif='GTD', orderRef='position-2U-2U-1h--eid-1914--ogid-13491', goodTillDate='20240611 18:22:00 UTC', usePriceMgmtAlgo=True), Order(orderId=509134, action='SELL', totalQuantity=200, orderType='STP LMT', lmtPrice=169.83, auxPrice=169.86, orderRef='stop-2U-2U-1h--eid-1914--ogid-13491', parentId=509133, triggerMethod=4, usePriceMgmtAlgo=True)

Trade object received from orderStatusEvent after order placed:

Trade(contract=Stock(conId=76792991, symbol='TSLA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='TSLA', tradingClass='NMS'), order=Order(orderId=509134, clientId=1000, permId=541689050, action='SELL', totalQuantity=200.0, orderType='STP LMT', lmtPrice=169.83, auxPrice=169.86, orderRef='stop-2U-2U-1h--eid-1914--ogid-13491', parentId=509133, triggerMethod=4, usePriceMgmtAlgo=True), orderStatus=OrderStatus(orderId=509134, status='PreSubmitted', filled=0.0, remaining=200.0, avgFillPrice=0.0, permId=541689050, parentId=509133, lastFillPrice=0.0, clientId=1000, whyHeld='child,trigger', mktCapPrice=0.0), fills=[], log=[TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 14, 397321, tzinfo=datetime.timezone.utc), status='PendingSubmit', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 14, 530493, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0)], advancedError='')

Here are the TWS API Logs to corroborate what's in the returned Trade object:

14:21:14:340 -> --?5-509134-76792991-TSLA-STK--0-?--SMART-USD-TSLA-NMS-SELL-200-STP LMT-169.83-169.86-DAY-541689049-DU5623872-O-0-stop-2U-2U-1h--eid-1914--ogid-13491-1000-541689050-0-0-0--541689050.0/DU5623872/100----------0---1-0------2147483647-0-0-0--3-0-0--509133-4--0-None--0----?-0-0--0-0------0-0-0-2147483647-2147483647---0--IB-0-0--0-0-PreSubmitted-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308------0-0-0-None-1.7976931348623157E308-169.86-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-0----0-1-0-0-1---0--100-0.02------F3-509134-PreSubmitted-0-200-0-541689050-509133-0-1000-child,trigger-0-

Modified Order

Order object I transmitted to modify the order. I modify lmtPrice and auxPrice:

Order(orderId=509134, clientId=1000, permId=541689050, action='SELL', totalQuantity=200.0, orderType='STP LMT', lmtPrice=169.98, auxPrice=170.02, orderRef='stop-2U-2U-1h--eid-1914--ogid-13491', parentId=509133, triggerMethod=4, usePriceMgmtAlgo=True)]

Trade object received from modifyOrderEvent after modified order placed doesn't reflect the modified price. TradeLogEntry shows message='Modify' so I know I'm receiving the correct event:

Trade(contract=Stock(conId=76792991, symbol='TSLA', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='TSLA', tradingClass='NMS'), order=Order(orderId=509134, clientId=1000, permId=541689050, action='SELL', totalQuantity=200.0, orderType='STP LMT', lmtPrice=169.83, auxPrice=169.86, orderRef='stop-2U-2U-1h--eid-1914--ogid-13491', parentId=509133, triggerMethod=4, usePriceMgmtAlgo=True), orderStatus=OrderStatus(orderId=509134, status='PreSubmitted', filled=0.0, remaining=200.0, avgFillPrice=0.0, permId=541689050, parentId=509133, lastFillPrice=0.0, clientId=1000, whyHeld='trigger', mktCapPrice=0.0), fills=[], log=[TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 14, 397321, tzinfo=datetime.timezone.utc), status='PendingSubmit', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 14, 530493, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 15, 20879, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 15, 742958, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 15, 748802, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 6, 11, 18, 21, 36, 525137, tzinfo=datetime.timezone.utc), status='PreSubmitted', message='Modify', errorCode=0)], advancedError='')

However, the TWS API Logs show the modified price in the callback:

14:21:36:376 -> --?5-509134-76792991-TSLA-STK--0-?--SMART-USD-TSLA-NMS-SELL-200-STP LMT-169.98-170.02-DAY-541689049-DU5623872-O-0-stop-2U-2U-1h--eid-1914--ogid-13491-1000-541689050-0-0-0--541689050.1/DU5623872/100----------0---1-0------2147483647-0-0-0--3-0-0--509133-4--0-None--0----?-0-0--0-0------0-0-0-2147483647-2147483647---0--IB-0-0--0-0-PreSubmitted-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308------0-0-0-None-1.7976931348623157E308-170.02-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-1.7976931348623157E308-0----0-1-0-0-1---0---------@3-509134-PreSubmitted-0-200-0-541689050-509133-0-1000-trigger-0-

Since TWS is sending back the price as modified, maybe I'm missing the point of Trade objects in the context of their transmission after things like Order modifications? There's a part of me that could understand if a Trade object was always intended to keep the original Order object intact and the Trade.log entries just log changes in a trade's lifecycle (ie: whyHeld= and status=). If that's the case, then maybe I'm just going about this incorrectly and I should be looking elsewhere to catch updated price data from a modified order?


Re: Forum planning #forum_planning

 

Dear Mel,

thanks for the discussion.

Indeed I would appreciate a general instruction like your mentioned general framework. Personally, I have still the problem that I don't know if I am running into troubles as a result of a wrong IB setup routine (e.g. starting the async loop or qasync loop or using ib_async loop or class implementation or something else) or wrong calls of ib_async functions (e.g. ib.reqContractDetails vs. ib.reqContractDetailsAsync). I moved to ib_in/async because I ended with the tws-api in a dead-end street (of my knowledge), now I don't know if I should move left (function calls) or right (async calls) or is 3 times right = 1 time left (which means it's possible to mix with async calls)

Therefore it would be very helpfull to have a structured example with base functions. It's not needed to have a full running code, but the logic should be visible to get the used strategie. There are many ways to Rome...

Kind Regards
Hans


Re: Forum planning #forum_planning

 

That is where sample code is difficult... I have a lot of basic modules I can call such as starting IB, various reporting, Flex Reports and on and on. But then when it comes to others using that code, there can be issues such as you would need to use the same folder structure as I do to use a lot of my code as I have the code in 3 folders (code, gui, flex) depending on what I want to run. I also have parm, input & output that all my modules expect to find. The other issue comes to other added modues... I use tkinter as it is already built in. Others use pyQt, pySide or even pyGame. One fellow built a nice framework () that was nice but complex. The downside was he wanted to make it multi broker and then TDA merged with Schwab and the API was gone. I may have to delve into it again and consider something like that except just for IB. If something like a general framework that utilizes ib-async interests you and you want to work on it with others, let me know and I will set up a repo for it. Then people could install that and have a lot of built in capabilities for ib_async. Just thoughts...

Mel


Re: Forum planning #forum_planning

 

Dear Ray,

yes, I know them. But indeed, for use in a program they are sometimes not handy enough. Do you think that it makes sense to write small programs (Pyqt6 in my case) to demonstrate the usages and keep them like the notebook receipes?
So, e.g. if we have a 'standard' init function for IB, it will also be easier to support and find bugs / program issues.

Kind Regards
Hans


Re: Forum planning #forum_planning

 

Yes I have added the new addresses to the Links Wiki.

I re-wrote some of those notebooks to run simply with python as I don't use Jupyter Notebook. I will have those on ib_tools if anyone is interested.

Thanks, Mel


Updated Wiki Page: Links #wiki-notice

Group Notification
 

The wiki page Links has been updated by Mel <climbermel@...>.

Compare Revisions


Re: Merci

 

开云体育

We don't have the "raw" files from the old forum.? One user has provided all the emails and email digests, but they need the personal data removed which we are close to finishing.

Mel





-------- Original message --------
From: "MB via groups.io" <mbaker@...>
Date: 2024-06-06 5:33 a.m. (GMT-08:00)
Subject: Re: [ib-async] Merci

I'm looking for the entire archive. Can you put the raw files somewhere? We can all use Python here after all.


Re: Forum planning #forum_planning

 

开云体育

I have been trying to do something along those lines in my ib_tools.? It was a place for me to collect functions as I got them working.? I haven't used async much but I just posted an example there from the old forum that shows setting up a callback.

I don't use jupyter so the notebooks were a pain when I first started.? So my ib_tools runs just under python.

If there is a specific part you are having trouble with give us an example and some code that isn't working and I'm sure one of us can help.

Welcome,

Mel





-------- Original message --------
From: "hjm via groups.io" <hjm@...>
Date: 2024-06-06 5:33 a.m. (GMT-08:00)
Subject: Re: [ib-async] Forum planning #forum_planning

Hi there and many thanks that some people continue the work of erdewit. According suggestion what's interesting for the 'new' forum, I will give my 5 cent.

To my person: I'm new to trading and also ib_async, have medium level of python and pyqt. I tried before with tws-api, but got more troubles than expected. Now I came to similar situations with ib_async.

Unfortunally there are not that large number of examples and receips which could help me. If I'm able to write clean code, of course I will support here as well.

Actually I have some troubles with async routines and callback. I'm sure all the mentioned functions in the doc have similar structures to call and receive. So, it would be helpfull (not just for me) to have a general instruction for each categorie and how to read the doc and set it up as a function. Further it would be great to have a small full functional code which shows how to init IB correctly and how to setup async processes, awaits and callbacks. There were some snippets in the old forum, but I havn't taken any...

One further idea is to sort functions and to create a toolbox from the receips.

Thanks for your attention

Hans


Re: Forum planning #forum_planning

 

Hans,

I assume you are familiar with the Ib_Insync Notebooks, code recipes and docs?
For now, all or most of that code should still work for Ib_async:

https://ib-insync.readthedocs.io/readme.html



Kind regards
Ray


Re: Forum planning #forum_planning

 

Hi there and many thanks that some people continue the work of erdewit. According suggestion what's interesting for the 'new' forum, I will give my 5 cent.

To my person: I'm new to trading and also ib_async, have medium level of python and pyqt. I tried before with tws-api, but got more troubles than expected. Now I came to similar situations with ib_async.

Unfortunally there are not that large number of examples and receips which could help me. If I'm able to write clean code, of course I will support here as well.

Actually I have some troubles with async routines and callback. I'm sure all the mentioned functions in the doc have similar structures to call and receive. So, it would be helpfull (not just for me) to have a general instruction for each categorie and how to read the doc and set it up as a function. Further it would be great to have a small full functional code which shows how to init IB correctly and how to setup async processes, awaits and callbacks. There were some snippets in the old forum, but I havn't taken any...

One further idea is to sort functions and to create a toolbox from the receips.

Thanks for your attention

Hans


Re: Merci

 

I'm looking for the entire archive. Can you put the raw files somewhere? We can all use Python here after all.


Re: ib_tool on GitHub

 

开云体育

I do that with clean up.? So I but an app for that.? It's a little python app that will search any drive or folder including network folders and servers.





-------- Original message --------
From: "Patrick Dufour via groups.io" <info@...>
Date: 2024-06-05 11:49 a.m. (GMT-08:00)
Subject: Re: [ib-async] ib_tool on GitHub

Mel, There is so many other examples i want to create. You know as me the recurring requests from beginners. This fall i hope i will have time to send you a bunch of them.

From the one i have posted, i think there is 2 that could be interesting:

  • The one that explain how to run many services in the same loop: HTTP server, socket io and a GUI module like PyQT5. (in 2021, maybe)
  • The other ones are how to run ib_async with Sanic. i cleaned up my test folder and my emails during Christmas holidays. i don't find them.


Re: ib_tool on GitHub

 

Mel, There is so many other examples i want to create. You know as me the recurring requests from beginners. This fall i hope i will have time to send you a bunch of them.

From the one i have posted, i think there is 2 that could be interesting:

  • The one that explain how to run many services in the same loop: HTTP server, socket io and a GUI module like PyQT5. (in 2021, maybe)
  • The other ones are how to run ib_async with Sanic. i cleaned up my test folder and my emails during Christmas holidays. i don't find them.


ib_tool on GitHub

 

I am cleaning up my ib_tools and I have added this code from the old forum as requested. Message #6484 1a. Re: Async event handling problem with orderStatusEvent From: Patrick Dufour Date: Tue, 29 Jun 2021 Sample Algo Template:

If there are any code samples you feel would be good to put on there as well let me know. I do need to clean up the code as it is all using ib_insyc still.

Mel


Re: accessing advancing / declining issues

 

I did a bit of looking into this, here is some basic code to start with: You can change the AD-AMEX & AMEX to AD-NYSE & NYSE The marketDataType(3) gives me delayed data since I'm not subscribed to that index data. The code below gave the the same numbers as shown for Advancing Issues and Declining Issues as seen in the Market Statistics tab. I'll check on getting the other numbers.

sym = 'AD-AMEX' ex = 'AMEX'

contract = Contract(secType='IND', symbol=sym, exchange=ex, currency='USD') ib.qualifyContracts(contract) ib.reqMarketDataType(3) data = ib.reqMktData(contract) ib.sleep(2)

AdvIssuses = data.bid DecIssuses = data.ask print(AdvIssuses) print(DecIssuses)

Cheers, Mel


Re: Sponsorship of group

 

You know, I've always wanted to learn the guitar, so if the old case in the corner contains one that could work as well.


Re: Merci

 

开云体育

Yes it is still being worked on.? Was there something in particular you were looking for?

Mel





-------- Original message --------
From: "mbaker via groups.io" <mbaker@...>
Date: 2024-06-02 3:43 a.m. (GMT-08:00)
Subject: Re: [ib-async] Merci

I also came here looking for the archive. There's a thread back in March of someone saying they have a copy but no actual archive anywhere that I could find. /g/twsapi/message/52652


Re: Merci

 

I also came here looking for the archive. There's a thread back in March of someone saying they have a copy but no actual archive anywhere that I could find. /g/twsapi/message/52652


Re: Sponsorship of group

 

开云体育

Yes FP is helping me with that.? I'll probably set up storage for it on my GitHub or possibly in the files section here if it isn't too big.

Mel





-------- Original message --------
From: "Sdoof via groups.io" <olivier.vanparys@...>
Date: 2024-06-01 9:18 a.m. (GMT-08:00)
Subject: Re: [ib-async] Sponsorship of group

Thanks Mel for carrying this forward. WIll that also cover the archive transfer from the old ib_insync group?