Include request ID in every request
2
Some API calls, like "reqAllOpenOrders" don't have any parameters. .NET implementation. public void reqAllOpenOrders() { var VERSION = 1; if (!CheckConnection()) return; var paramsList = new BinaryWriter(new MemoryStream()); var lengthPos = prepareBuffer(paramsList); paramsList.AddParameter(OutgoingMessages.RequestAllOpenOrders); paramsList.AddParameter(VERSION); CloseAndSend(paramsList, lengthPos, EClientErrors.FAIL_SEND_OORDER); } Some API calls, e.g. "reqAccountSummary", have parameter "reqId". public void reqAccountSummary(int reqId, string group, string tags) { var VERSION = 1; if (!CheckConnection()) return; if (!CheckServerVersion(reqId, MinServerVer.ACCT_SUMMARY, " It does not support account summary requests.")) return; var paramsList = new BinaryWriter(new MemoryStream()); var lengthPos = prepareBuffer(paramsList); try { paramsList.AddParameter(OutgoingMessages.RequestAccountSummary); paramsList.AddParameter(VERSION); paramsList.AddParameter(reqId); paramsList.AddParameter(group); paramsList.AddParameter(tags); } catch (EClientException e) { wrapper.error(reqId, e.Err.Code, e.Err.Message + e.Text, ""); return; } CloseAndSend(reqId, paramsList, lengthPos, EClientErrors.FAIL_SEND_REQACCOUNTDATA); } This socket writer uses "paramList" to add parameters to the request. If I want to include parameter "reqId" in those requests that currently don't have it, will socket parse "extended" message correctly and will it include this request ID in the response?
|
TradingHours and LiquidHours empty for secType='BOND'
5
If I run the same code for a STK('AAPL') and a BOND('530715AD3') when I print the contract details I get the hours for both for the STK and both are empty for the BOND. Yet I check that bond in TWS and it shows 20:00 - 17:00 for the hours. Any suggestions? Mel
|
Receiving Point & Figure data?
Is it possible to receive Point & Figure historical data via the TWS API? I imagine that I could generate the Point & Figure Xs and Os from the regular historical data, but I would rather just receive the data ready-made. Thanks.
|
Login Failed after clicking "Re-login" on "Re-login is required" dialogue
15
I have been running TWS in paper mode, and I am getting encountered with "Re-login is required" dialogue daily (Screenshot attached below). I am guessing this happens around IB daily reset time as I saw a few people mentioning this in other topics in this same group. Anyway, once I click on "Re-login" on this dialogue, it throws me a "Login Failed" dialogue, mentioning passwords are case sensitive and some other details. I am attaching screenshot of that dialogue below too. Can someone please explain me these things that: Why in the first place is that re-login is required dialogue thrown? What's the point of enabling auto-restart functionality then when everyday at IB server reset time relogin is required due to connection losses. Why login is failing on clicking re-login? What password is it talking about as I am just clicking re-login, not providing any password at all as it isn't asking for. How does authentication work during re-login? Does it read a token or something from some file etc? Any help would be great. Thanks!
|
anything to wait and confirm the order is done (python)?
2
i have been using ib_insync for long time and now switch to use the official ib api. can anyone tell the usual practice for waiting the order to fill and receive a "done" call back ? in ib_insync, there is something like below while not trade.isDone(): ib.waitOnUpdate() this loop can wait for the trade until it is finished. in ib api doc, there is "filled" parameter in orderstatus, what come up with my mind is to continuously update this parameter until a filled indication. but any good and efficient way to do so?
|
Possible race condition with tickByTickBidAsk(...) Callback
11
Hello all, i noticed some malfunction in my code that is simply not explainable regarding the tickByTickBidAsk(...)-Callback function. In my code i have a candle / bar that is constructed with the bid / ask price. It is ONE OBJECT that is changed by MAYBE ( ? ) two tickByTickBidAsk(...) executions at the same time. Could the following be the case: Is it possible that one execution is somewhere in the middle and the other one starts to execute the callback ? If this is possible, what would be an appropriate strategy using mutexes or something like that ? Do i have to lock all callbacks in that case ? regards, Simon
|
Historical data on AVGO
3
Hello everybody, I'm looking for AVGO historical data from 2010. I'm able to recover from 2016. Before the ticket was BRCM but if I try to recover the historcal data for BRCM I obtain error "200 Nessuna descrizione di titoli trrovata per la richiesta" (translated "200 No stock descriptions found for the request"). Is there a a way to recover this data? I'm using IB4m library from matlab this way: ... contract = com.ib.client.Contract(); contract.exchange('SMART'); contract.primaryExch('ISLAND'); contract.currency('USD'); contract.secType('STK'); contract.symbol('BRCM'); id=1000000; ... session.eClientSocket.reqHistoricalData(id,contract,ibkrData.endDateTime, ibkrData.durationString,ibkrData.barSizeSetting,'TRADES',1,1,false,[]); ... Thank you in advace
|
difference between reqPnLSingle and reqPnL (python API)
2
based on my understanding in the official doc, reqPnLSingle can only accept individual account number as below app.reqPnLSingle(12,"Uxxxxxxxx","",8314) however, i got no response from python API. anyone know why? for reqPnL, it accept both individual account number and "All" aggregating all accounts as below app.reqPnL(12, "All", "") i can successfully execute this and returned the pnl number to me.
|
How to use CompleteableFuture in Java for TWS Callbacks?
2
Hi All, Does anyone in the group have some insight as to how to use CompleteableFuture to account for instances where TWS does not send server callback? For example, if I use reqHistoricalData for a bar that does not exist--e.g. there were no trades on Black Friday for a thinly traded stock--TWS never returns a Bar object. How would one use Completeable Future (or other) for the program to recognize that TWS never sent a callback? Thank you,
|
what is the usual practice for a new order id?
2
from IB official doc https://interactivebrokers.github.io/tws-api/order_submission.html 1 def nextValidId(self, orderId: int): 2 super().nextValidId(orderId) 3 4 logging.debug("setting nextValidOrderId: %d", orderId) 5 self.nextValidOrderId = orderId 6 print("NextValidId:", orderId) it said that when we call app.reqIds(-1), the next order id will be given to app.nextValidOrderId so we can use app.nextValidOrderId to place the next order. but i found that i need to wait a second like time.sleep(1) after running app.reqIds(-1) i guess it needs 1s to wait for the update for app.nextValidOrderId? any good practice to place consecutive order without waiting?
|
is it possible to find all raw fills in open position?
4
i know that i can get the open position's average filled price in updatePortfolio() function. is it possible to further break down the average price like finding all of the fill records so that i can verify the average price calculated by the system? i know i can get this information in execution detail if i save the price records every time after executing the trade. but it would be convenient if i know this information using one request instead of saving it each time. and as i know, IB use FIFO, so IB will close my earlier position first within a ticker? thanks!
|
Fetch options greeks for specific contracts
3
Hey! I would just like to create a script using Java that would fetch options greeks for specific hard-coded contracts, and then notify me (probably through a Discord bot) when they reach certain values since they don't provide alerts based on greeks. I started working things out with the TWS API, but I'm trying to figure out a way to have the same functionnality by using a small cloud instance and not having to RDP, login TWS, fire up my code over and over every day. So I stumbled upon the Client Portal API which seems to be exacly what I want : - Web-based gateway - No need to run TWS However, it seems like the only way to get options greeks is with the Market Data snapshot (https://ibkrcampus.com/ibkr-api-page/cpapi-v1/#md-snapshot), and I do recall reading in a couple of places that there is a per-request price for live snapshot data which I would like not to pay. Is there another way around? I feel kind of stuck into between for a high ram VM and using RDP over and over, and paying for snapshot data. I feel like there probably is a pretty good working solution, but I can't seem to find it. P.S. I don't care if my data is 15 minutes delayed, as I don't actually do automated trades based on it! Thanks!
|
How to change the logging level
2
I am trying to get more detailed logging to the console. I have done it before and seen details like ``` 4948305328 connState: None -> 0 Connecting to 127.0.0.1:4001 w/ id:1 4948305328 connState: 0 -> 1 ``` I can't seem to get it working now. I have even tried changing the client.py source file like this: ``` logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # << new line ``` and I still can't get it to log more details.
|
Why do I have periods of live TickByTick market data showing no updates? When I check the historical ticks for the same period I find there were updates that I should have received.
6
Hi Team, I have been experiencing an issue with live TickByTick market data from the TWS API in Python. My trading software uses the reqTickByTickData function to request level I BidAsk (book) and AllLast (trades) data for a set of 3 front-month futures contracts, and receives ticks for these requests by implementing the tickByTickBidAsk and tickByTickAllLast methods. While this initially works perfectly, throughout the day I have tracked hundreds of instances of one or more of these requests missing live ticks for a prolonged period of time (10s of seconds or sometimes even minutes). However, when I fetch historical ticks for the same contracts in the same time window as one of these outages (using the reqHistoricalTicks function) and I am provided with plenty of ticks/updates. So why do the live ticks sometimes work and sometimes go missing? During these outages, I can see the top of book prices changing and trades occurring for these instruments live with my TWS GUI. I have checked TWS logs thoroughly and confirmed that no ticks are being logged for the request ID in question during these outages, so I don't believe the problem lies in how my software handles received ticks. I have purchased quote boosters for my account to ensure that the number of Level I TickByTick requests I am making falls below the number of "market depth lines" available to my account, and I cannot see any TWS log lines indicating that I have breached my limit of these requests. The frequency of these outages also seems to depend on the time of day - I detect significantly more of these outages in the afternoons of my trading sessions than the mornings. Has anyone else experienced an issue like this and can point me towards a solution? I have seen the frequency of these live TickByTick outages reduce marginally by changing my "Global Configuration -> General -> Current Region" setting to a closer region, but the issue still persists. Thanks, J
|
C# - TWS API - Connection Closed Handling
11
Hey, I'm new to TWS API, but I'm losing my mind, so need some help regarding how to handle, if IB Gateway is closed/restarted while connected to it. I'm using 10.19 TWS API and IB Gateway - but also tried with 10.30 So far I managed to connect successfully: - connect to IB Gateway - get Historical Bars from any ticker from US and using historicalDataEnd I know when its finished(have subscription for it) - scan the market and get data about the contracts - get real time 5 sec bars and build it into any interval bar I want with an aggregator So I think I got the basics down with these, and I get the responses I'd expect. And the errors are coming through as well, like (-1 2104 Market data farm connection is OK:eufarm) for now just writing it out to console. But here starts the confusion of mine about connection lost (I test with manually closing IBGateway or by setting the auto restart), and my application gets no notification about this event at all. I checked the documentation on Old Docs and New Docs both write the same thing: In C# it is caught and sent to IBApi::EWrapper::error with errorCode -1. The client application needs to handle this error message and use it to indicate that an exception has been thrown in the socket connection. Associated functions such as IBApi::EWrapper::connectionClosed and IBApi::EClient::IsConnected functions are not called automatically by the API code but need to be handled at the API client-level According to this, an error should arrive telling me the connection did indeed close, but I do not. And I'm lost. I have an IBClient class that implements EWrapper. And I know its setup correctly since all reqHistoricalData, reqContractDetails, reqScannerSubscription, reqRealTimeBars are working nicely, and other errors are arriving. This is the simple setup for now to start the connection, and how the errors are simply written out to console, I put breakpoints everywhere, and nothing when IBGateway closes. public void error(Exception e) => Console.WriteLine(e); public void error(string str) => Console.WriteLine(str); public void error(int id, int errorCode, string errorMsg, string advancedOrderRejectJson) => Console.WriteLine($"{id} {errorCode} {errorMsg} {advancedOrderRejectJson}"); public IBClient() { ClientSocket = new EClientSocket(this, _signal); ClientSocket.eConnect(host, port, clientId); _reader = new EReader(ClientSocket, _signal); _reader.Start(); new Thread(() => { while (ClientSocket.IsConnected()) { _signal.waitForSignal(); _reader.processMsgs(); } }) { IsBackground = true }.Start(); } Also checked ClientSocket.IsConnected(), and it remains true after closing IBG. And checked connectionClosed it's not called. So my question is, does this error arrive at all? Or there is no real msg to tell me that IBG is closed and therefore the connection is lost. Of so do I need to implement a heartbeat background process to handle this? Thanks, Saph
|
reqCompletedOrders timeframe
3
Hi, Is there a limit to the orders that can retrieved from reqCompletedOrders? I have previously placed an order in a simulated account. It was a small USD JPY purchase. I can confirm this a couple ways. First, it shows up in the ledger with a call from: reqAccountSummary(9003, "All", "$LEDGER:JPY") Second, reqIds triggers nextValidId with a value of 2. Today, when I call reqCompletedOrders(apiOnly=False) I only get completedOrdersEnd being triggered. Shouldn't I be able to see completedOrder being triggered with data from last week?
|
Direct routing for SPX options through API?
2
Hi there, I've been trying without luck to send a Stop Loss order for an SPX option contract (not spread nor combo) through the API directly to the CBOE exchange so this way I hope the order will be resting in the exchange and it will suffer (maybe) less slippage than routing it through SMART. When I try it through TWS I can set the CBOE exchange and after confirming a precaution of higher trade fees (I've not found anything on this) then the order is placed and the exchange shown on Dest column is CBOE But through the API I've tried setting exchange and primaryExchange to CBOE and the order Dest always is changed to SMART My goal is to get out of an option position as fast as possible and routing directly to the exchange seems the way to go Any thoughts on this? Thank you
|
DDE Server
3
I appreciate that this may be an topic (depreciated) topic. I have been using successfully DDESocketbridge and excel 2010 for some time - the last reliable version of Java being Version 8 update 371 - after this issues start to arise - i.e. wont work at all. After this update the DDE socket will only work with a newly rebooted machine (as in power off cold reboot - not ctrl/del) Works fine until you either close excel or TWS reboots at night Closing the java window or restarting TWS from scratch does nothing - in that excel hangs as soon as you try to connect (put the function in a cell) Clearly windows is keeping a list/pointer/link to active DDE processes and this is now broken Is it possible to refresh the windows side of things without a cold reboot. Running windows 10 (OS Build 19045.4529) on a AMD ryzen 95950x with 128gb ram Just to reiterate - everything was stable until the java update (and any potential windows updates around the same time) and changing excel is not really something I want to consider. Thank you P
|
Get latest quotes without affecting subscription
5
What if I'd like to make two separate methods. 1. One that creates permanent subscription to receive quotes until cancelled void CreateSubscription(string symbol) { client.reqTickByTickData(0, new Contract { Symbol = symbol, SecType = "STK" }, "BidAsk", 0, true); } 2. One that returns latest quote for the same instrument on demand only once Task<TickByTickBidAskModel> GetLastPrice(string symbol) { var id = 1000; var source = new TaskCompletionSource<TickByTickBidAskModel>(); client.tickByTickBidAsk += quote => { sourceTrySetResult(quote); client.cancelTickByTickData(id); }; client.reqTickByTickData(1000, new Contract { Symbol = symbol, SecType = "STK" }, "BidAsk", 0, true); return await source.Task; } Issues 1. If I call "CreateSubscription" and then "GetLastPrice", there is a chance that callback will receive a quote requested by "CreateSubscription", and not by "GetLastPrice". 2. If I cancel subscription in "GetLastPrice", it will cancel subscription in "CreateSubscription". Question How do I make two methods independent and not breaking each other? 1. I could make different requests, e.g. "reqMarketData" to create permanent subscription and "reqTickByTickData" to get data only once. 2. I could have 2 instances of a client, one for subscription and one that handles single requests. Would any of these be the correct approach or is there a better way?
|
reqTickByTickData() - how to keep tape in-line with current L2
2
Hi all, I'm getting started with IBApi and as a starter am trying to replicate the data-feed of TWS' T&S window. Unless I'm mistaken, the transaction color (red, green, white) depends on where the transaction price lands on the spread - e.g. transaction at current best bid would be colored red. How would one decide where on the spread given transaction lies? I see two options: with reqTickByTickData(), consume also tickByTickBidAsk(), which I believe shows the first rows of L2 data, i.e. top of the book; explicitly request L2 data via reqMarketDepth() and compare each tickByTick transaction price to the first ask&bid rows. Prefer the 2nd option, but how can we associate given tickByTickAllLast() tick record with current top of the book? L2 updates come in row-by-row and their updates appear to be considerably slower than that of the tape. This gives me the impression the top of the book is already out of date at the time of tick-by-tick callback. To state my problem in short: how can we know the up-to-date top of the book at the time when processing given tickByTickAllLast() callback so it can be determined where in the spread the transaction took place? Thanks!
|