Keyboard Shortcuts
Likes
- Twsapi
- Messages
Search
Adding timezone to request
Just a heads-up that, starting with TWS 10.18, the following errors/warnings started to trigger when requesting historical data:
2174 : Warning: You submitted request with date-time attributes without explicit time zone. Please switch to use yyyymmdd-hh:mm:ss in UTC or use instrument time zone, like US/Eastern. Implied time zone functionality will be removed in the next API release 10314 : End Date/Time: The date, time, or time-zone entered is invalid. The correct format is yyyymmdd hh:mm:ss xxx where yyyymmdd and xxx are optional. E.g.: 20031126 15:59:00 US/Eastern Note that there is a space between the date and time, and between the time and time-zone. If no date is specified, current date is assumed. If no time-zone is specified, local time-zone is assumed(deprecated). You can also provide yyyymmddd-hh:mm:ss time is in UTC. Note that there is a dash between the date and time in UTC notation. The API documentation seems to already reflect these changes. -- |
||||
Re: Short positions with API v10.xx
No worries. You will still be able to short positions with TWS API 10.18 (or any of the version 10 APIs for that matter). Version 10 TWS APIs introduce a Decimal data type for various size fields so that you don't loose a shirt on crypto trades when simple calculations in double procession math such as 1.123 + 1.456 go wrong as early as the third position to the right of the decimal point (or decimal comma, depending on your locale). Some languages (such as Java) have built-in Decimal data types while C++ does not. Decimal in the C++ API is typedefed as "unsigned long long" for the storage of the Decimals only. Just check the Decimal.h file and you will see that the type handles values from -Infinity to +Infinity and calculates 1.123 + 1.456 correctly as 2.579. You will have to use the various math methods, though, such as add(), sub(), mul(), ... And there are methods to convert between double, string, and Decimal. ´³¨¹°ù²µ±ð²Ô |
||||
Short positions with API v10.xx
I'm upgrading my c++ API to 10.18 and I realized that with the new Decimal type, positions are represented as unsigned long long, where they were double before (9.81).? This would mean that short positions are now represented as positive numbers, no? If so, which callback lets me know I have a short position with the new API?? This specifically applies to the position() and updatePortfolio() callbacks.?
This seems like a pretty dumb question - I'm digging through the reference guide to find the answer - but I'm stumped.? Thoughts? T. |
||||
Re: Market of Euronext-Amsterdam (AEB) but somehow it stopped
Hi Loic,
does not work on my side :-( on Aug, 30th support wrote: We are still working on this issue, hopefully it should be resolved soon. I will continue to monitor this for you and let you know when it is resolved.My suggestion: the more support tickets IB gets the higher the pressure for them to solve the issue (hopefully) -> open support tickets! br Erich |
||||
Re: Close open positions
I find the following solution for myself. I hope that might help someone else.
I separated the closing positions action in a dedicated "app". In this case the reqPositions() runs only once if required, and then disconnects. class MyCloseApp(EWrapper, EClient): ??? def __init__(self): ??????? EClient.__init__(self, self) ??????? self.nextValidOrderId = None ??????? self.permId2ord = {} ??? def error(self, reqId, errorCode: int, errorString: str, advancedOrderRejectJson = ""): ??????? super().error(reqId, errorCode, errorString, advancedOrderRejectJson) ??????? if advancedOrderRejectJson: ??????????? print("Error. Id: ", reqId, "Code: ", errorCode, "Msg: ", errorString, ???????????????? "AdvancedOrderRejectJson: ", advancedOrderRejectJson) ??????? else: ??????????? print("Error. Id: ", reqId, "Code: ", errorCode, "Msg: ", errorString) ? ??? def nextValidId(self, orderId: int): ??????? super().nextValidId(orderId) ??????? self.nextValidOrderId = orderId ??????? print("NextValidOrderId: ", orderId) ??????? self.start() ??? def nextOrderId(self): ??????? oid = self.nextValidOrderId ??????? self.nextValidOrderId += 1 ??????? return oid ?????? ? ??? def openOrder(self, orderId, contract: Contract, order: Order, orderState): ??????? super().openOrder(orderId, contract, order, orderState) ??????? print("OpenOrder. PermId:", order.permId, "ClientId:", order.clientId, ????????????? "OrderId:", orderId, "Account:", order.account, "Symbol:", contract.symbol, ????????????? "SecType:", contract.secType, "Exchange:", contract.exchange, "Action:", order.action, ????????????? "OrderType:", order.orderType, "TotalQty:", order.totalQuantity, ????????????? "CashQty:", order.cashQty, "LmtPrice:", order.lmtPrice, ????????????? "AuxPrice:", order.auxPrice, "Status:", orderState.status, ????????????? "MinTradeQty:", order.minTradeQty, ????????????? "MinCompeteSize:", order.minCompeteSize, "competeAgainstBestOffset:", ????????????? "UpToMid", order.competeAgainstBestOffset, ????????????? "MidOffsetAtWhole:", order.midOffsetAtWhole, ????????????? "MidOffsetAtHalf:", order.midOffsetAtHalf) ? ??????? order.contract = contract ??????? self.permId2ord[order.permId] = order?? ? ?? ? ??? def orderStatus(self, orderId, status: str, filled: Decimal, remaining: Decimal, ??????????????????? avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, ??????????????????? whyHeld: str, mktCapPrice: float): ??????? super().orderStatus(orderId, status, filled, remaining, avgFillPrice, ??????????????????????????? permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice) ??????? print('OrderStatus. Id:', orderId, 'Status:', status, 'Filled:', filled, ????????????? 'Remaining:', remaining, 'AvgFillPrice:', avgFillPrice, ????????????? 'PermId:', permId, 'ParentId:', parentId, ????????????? 'LastFillPrice:', lastFillPrice, 'ClientId:', clientId, ????????????? 'WhyHeld:', whyHeld, 'MktCapPrice', mktCapPrice) ?? ? ??? def openOrderEnd(self): ??????? super().openOrderEnd() ??????? print("OpenOrderEnd") ???? ? ??? def position(self, account: str, contract: Contract, position: Decimal, avgCost: float): ??????? super().position(account, contract, position, avgCost) ??????? print("Position.", "Account:", account, "Symbol:", contract.symbol, "SecType:", contract.secType, ????????????? "Currency:", contract.currency, "Position:", position, ????????????? "Avg cost:", avgCost) ??????? if position != 0: ??????????? close_order = Order() ??????????? close_order.orderType = 'MKT' ??????????? close_order.totalQuantity = abs(position) ??????????? close_order.action = ('BUY', 'SELL')[position > 0] ?????????? ? ??????????? contract = Contract() ??????????? contract.symbol = "GBP" ??????????? contract.secType = "CASH" ??????????? contract.exchange = "IDEALPRO" ??????????? contract.currency = "USD" ??????????? self.placeOrder(self.nextOrderId(), contract, close_order) ??????????? print('All positions are closed') ??????? else: ??????????? print('No positions to close') ??????????? pass ?????? ? ??? def positionEnd(self): ??????? super().positionEnd() ??????? print("PositionEnd") ??????? self.disconnect() ?? ? ??? def execDetails(self, reqId, contract, execution): ??????? print('ExecDetails: ', reqId, contract.symbol, contract.secType, contract.currency, ????????????? execution.execId, execution.orderId, execution.lastLiquidity) ?????? ? ??? def start(self): ??????? #for_result = 0??? # For testing ??????? #for_result = 'long' # For testing ??????? with open('file.txt') as file: ??????????? prev_order = file.read() ??????? if str(for_result) == prev_order: ??????????? print('no position closing required') ??????????? self.disconnect()??? ? ??????? elif for_result == 0: ??????????? self.disconnect() ??????? else: ??????????? with open('file.txt', 'w') as file: ??????????????? file.write(str(for_result)) ??????????? self.reqGlobalCancel() ??????????? self.reqPositions() ???????????? ? ??? def stop(self): ??????? self.disconnect() def main_close(): ??? app = MyCloseApp() ??? app.connect("localhost", 7497, 1) ??? time.sleep(1) ??? Timer(10, app.stop).start() # Call stop() after 10 seconds to disconnect ??? app.run() if __name__ == "__main__": ??? main_close() |
||||
Re: suggestions for simple GUI : IBAPI - python - windows
Erez Kaplan
Hi Steve
This code is simple and robust, works like a charm, GREAT, just what I was looking for. The only code I added was: def connect_to_TWS(self): Thanks again, Erez |
||||
Re: Erroneous execution details (execDetails) being returned
¿ªÔÆÌåÓýNo, NextValidId occurs once when you connect to the API. It tells you the first unused order ID for the current ClientID. For each new order, you have to then increment the order id in some fashion so that it¡¯s higher than previous order ids. The API does not automatically provide you with order ids. ? If you use the same order id as has been used in a previous order using the same ClientID, placeOrder will simply modify the existing order (if it hasn¡¯t already been filled), not create a new one. ? And note that different ClientIds can create orders with the same order id. So if you had orders with the same order id yesterday and today, they were presumably created under different ClientIDs. ? All of this is explained in the IB API documentation. It¡¯s worth your while reading it and making sure you understand it. ? Richard ? ? From: [email protected] <[email protected]> On Behalf Of ryanabbott22@...
Sent: 01 September 2022 22:04 To: [email protected] Subject: Re: [TWS API] Erroneous execution details (execDetails) being returned ? So it looks like what happened is the orderId got reused for some reason. ExecDetails shows orderId 14100 happening yesterday at 08:36 and today at 08:35. Is it my responsibility to ensure the orderId isn't getting reused? I'm just using the eWrapper.NextValidId which seems to indicate TWS is tracking which orderIds have been used and I shouldn't need to worry about it as long as I'm calling their method, right? |
||||
Re: Erroneous execution details (execDetails) being returned
So it looks like what happened is the orderId got reused for some reason. ExecDetails shows orderId 14100 happening yesterday at 08:36 and today at 08:35. Is it my responsibility to ensure the orderId isn't getting reused? I'm just using the eWrapper.NextValidId which seems to indicate TWS is tracking which orderIds have been used and I shouldn't need to worry about it as long as I'm calling their method, right?
|
||||
Re: Erroneous execution details (execDetails) being returned
You might want to re-read the TWS API Guide sections on and the class, Ryan. There are several cases where you would get multiple callbacks for a single order placed via the API. Here for example a sliver of the
definition:
The six ExecDetails you listed have unique ExecIds but they all end in ".01". That suggests that each ExecDetails describes an order fill:
Also, please observe that the six permIds are unique as well. That suggests that there were a total of 6 fills for 4 orders you places via the API. Have you cross checked the ExecDetails with the TWS Trade History window? These ExecDetails by themselves and without more context (such as what the placed orders looked like and maybe order status updates) do not look erroneous or duplicate to me. There may be more to the story, but does that make sense? ´³¨¹°ù²µ±ð²Ô |
||||
Erroneous execution details (execDetails) being returned
Hey All,
I'm curious if anyone else has experienced problems with the Execution details (execDetails) being returned from the TWS API. I'm using the C# version. Intermittently I've been getting completely erroneous values being returned when orders haven't actually been executed at all and duplicate execution details for the same order Id that differ.? Here's an example: ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.6310667f.01.01, 14098, 1, Added Liquidity, 12044.25, 20220901? 08:23:04permId: 843004273
ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.63106809.01.01, 14101, 1, Added Liquidity, 12044.25, 20220901? 08:27:04permId: 843004608
ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.63106bc1.01.01, 14103, 1, Added Liquidity, 12075.5, 20220901? 08:35:17permId: 843004610
ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.63106c03.01.01, 14100, 1, Added Liquidity, 12082, 20220901? 08:35:40permId: 843004275
ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.630f1c3d.01.01, 14098, 1, Added Liquidity, 12336, 20220831? 08:27:46permId: 916490259
ExecDetails. -1 - NQ, FUT, USD - 0000e1a7.630f2076.01.01, 14100, 1, Added Liquidity, 12368.5, 20220831? 08:36:47permId: 916490261 Any thoughts or helpful advice on how to fix this would be very appreciated! Thanks, Ryan |
||||
libs included in macos version of API 10.17 don't link
I tried to upgrade to 10.17 as the server has stopped handling my requests due to the age of my current API (what the people at IB told me). They suggested moving to 10.17 which has some new stringToDecimal functionality inside a new library however this library does not link on a Mac, not even in the sample makefile which they provided. Am I doing something wrong or is this a bug that will be fixed in the future. TLDR: download 10.17 onto a mac, go to the sample makefile, type make. It fails. -Marcus |
||||
Sell order for Options not going through in Paper trading mode
HI i tried a buy order followed by a sell order for TSLA/SPX options.
THe buy order goes through in about few seconds - the order gets fulfilled and the program also gets a call back ( with orderStatus as fulfilled.) But the sell order dont go through. I am able to see the order in TWS window , but it doesn't get fullfilled for a very long time and on market close the order get cancelled.?? Anyone face similar issues?? Pasting my sample code? for Sell (? Buy Call is also almost exactly same )? contract.symbol("SPX"); contract.secType("OPT");
contract.right("P");
contract.lastTradeDateOrContractMonth("220901");
contract.strike(4190.00);
//Get contract details?
contract = getContractDetails(contract);? // this basically calls m_client.reqContractDetails() //Create new order? Order order = new Order();
order.orderId(orderId);
order.action(Types.Action.SELL);
order.orderType(OrderType.MKT);
order.totalQuantity(1);
?
//Place order
m_client.placeOrder(orderId,contract,order); |
||||