Keyboard Shortcuts
Likes
- Twsapi
- Messages
Search
Re: Time is a reserved name in VBA
开云体育That’s not quite right. ? ‘Time’ is NOT a VBA function: it’s a property of the VBA DateTime module (you can see this using the ObjectBrowser). It returns a variant with a vbDate variant type. ? Property names CAN be re-used as variable names (unlike method names, which cannot: Dim Len as String will fail). ? Your little function doesn’t illustrate anything: it will return the vbDate variant returned by the Time property. It doesn’t even use Time (or time) as a variable. ? You say ‘Notice that the Time will be changed to time’. This is nothing to do with conflicts. It’s because VBA (and indeed VB6, but fortunately not VB.Net) are very bad at managing name spellings. If you declare a variable or a method or property called ‘MyName’ somewhere, and then declare something else called ‘myname’ anywhere within the same project or module, then the original ‘MyName’ will be displayed as ‘myname’ (though the actual code won’t be changed). ? It seems that the VBA/VB6 compilers have a single name table that doesn’t record the context of a name declaration (and remember VBA and VB6 are case-insensitive) . Thus when ‘myname’ is declared, the original table entry for ‘MyName’ is overwritten with ‘myname’, and that’s what you’ll see everywhere, even on the original ‘MyName’ declaration. ? This is one of the most annoying features of VBA/VB6, especially where you have references to other components that use the same names with different capitalisation, in which case what you see will depend on the order of the references to these other components. ? I don’t think this actually ‘needs to be fixed’: after all it’s been like this for well over 20 years – if it were a real problem, someone would have fixed it by now. Are you able to point to any specific instances that you think don’t work properly? ? And no, IB Developers don’t appear to monitor this group. There used to be an IB staff member in the group, which was actually very helpful due to his insider knowledge, but no longer (at least, not that we know of). ? If you really think you need to bring this to IB’s attention, you can either raise a ticket on your Account Management page, or get access to the GitHub repository and raise an issue. But I can more or less guarantee that you won’t get any traction on this: far too much work for zero benefit. ? Richard |
Time is a reserved name in VBA
The Excel versions of the API frequently use the variable 'time'.? Declaring it as string or as long in numerous places.? It is also in the TWSlib in at least five places.
This is a problem because 'Time' is a built-in VBA function (which returns the current system time) and is part of the VBA standard library and cannot be redefined without causing conflicts.? In other words Time is a reserved name in VBA.
?
To verify this problem, one can create a module in an Excel workbook that is using the API and enter a simple function like this:
Option Explicit
Function testTimeProblem()
? ? testTimeProblem = Time End Function ?
Notice that the Time will be changed to time...? Which is an indication of the problem.
This needs to be fixed.? How do I report this problem to IB Developers or do they monitor this Group?? ?
Thanks!
?
?
|
Clarification on Identifying Order Status Callback for Modified Orders
Hello Folks, While sending a modification request for an existing confirmed order, I am receiving the following callbacks related to that specific order ID:
Upon sending the order modification request and subsequently receiving the OrderStatus callback, how can I ensure that the OrderStatus callback pertains to the modified order? In the example above, it was not related to the modified order. Thanks. |
Re: Cancel on Client Disconnect/Logout
toggle quoted message
Show quoted text
|
Cancel on Client Disconnect/Logout
Hi,
Is there any option in the TWS application to automatically cancel all open orders (an event triggered automatically by the TWS application) when the client disconnects? Or is there a specific field we can set when sending orders via the TWS API to achieve this?
Thank you.
|
Re: Not receiving previous close price from ReqMktData
Not sure what to tell you, but maybe this is one for IBKR to look into. It does not feel like there is anything your client does wrong. Here a few thoughts:
I record "Close" ticks but don't really use them. But I am getting them a few times a day:
And it does not feel like I am missing "Close" ticks, but I can't say that for sure. One thing I do, though, is that I request "the kitchen sink" during reqMktData() instrument subscription calls. My tick list for stocks looks like this "100, 101, 104, 105, 106, 165, 220, 221, 232, 233, 236, 258, 292, 293, 294, 295, 318, 375, 411, 456, 460, 577, 586, 587, 588, 595, 614, 619, 623" You should not have to specify any of these to get the "Close" tick reliably. But maybe it helps if the issue is HMDS query related. 闯ü谤驳别苍
?
?
?
On Tue, Jan 28, 2025 at 12:23 PM, ds-avatar wrote:
|
Fee Rate for opening a short position
Where does the fee rate show up? Is it folded into the commision charge? How can that be determined through the API?
?
If I understand the fee rate correctly then taking for example I open a short position on NVDA that amounts to $10,000.
The fee rate for today = .41%
The fee then amounts to $10,000 * .41% =? $41.00/365 = $0.11 cents for one day if I close the position before market closing?
?
Assuming I'm correct where does this fee show up? is it folded into the commision fee?
?
If I repeat the same transaction 5 times during day trading does that amount to $0.11 * 5? = $0.55?
?
Can that be determined in an API call?
? |
Re: Not receiving previous close price from ReqMktData
For the contrast, I'm also attaching another API session log from today where the #9 tick was reported immediately after ReqMktData call, as expected.
?
Unfortunately the fact that the tick is reported sometimes does not mitigate the issue of it not being reported some of the other times when the API trading program is regularly relying on it to make data driven decisions, and for my trading it is absolutely crucial.
?
--
Best, DS |
Not receiving previous close price from ReqMktData
I'm not regularly receiving tick #9 today through the API after calling ReqMktData for one particular stock. Admittedly, this is not the first time I ran into this bug for any random stock, but today this it's repeats frequently (most of the time, indeed) with one particular stock. So I managed to log this problem with ease and now I have not one, but two API log excerpts running for at least 5 minutes during regular trading hours with lots of ticks coming in from ReqMktData, but not the Close Price tick.
?
The stock in question is XNYS:ATR, {Type='STK';LocalSymbol='ATR';PrimaryExchange='NYSE';Symbol='ATR';Exchange='SMART';Currency='USD';ContractId='4651'}. Its last closing price yesterday was 158.46 and it is displayed in TWS no problem in the respective Previous Close column, but is apparently not getting reliably reported through the API.
?
I ask the group to see my logs to help decide how to go about this issue.
?
I'm attaching the two decoded TWS API log text excerpts with everything before the respective REQ_CONTRACT_DATA and REQ_MKT_DATA calls removed due to representing sensitive account data and up to the point of API connection closing (about 5 minutes each), with a few short clarifying comments denoted with the starting symbol #.?
--
Best, DS |
Re: reqHistoricalTicks() & batching vs. reqTickByTick() vs. reqHistoricalData(), Backtesting vs. Realtime execution
I assume you are talking about grouping TickByTick real time data into 1second candles? You would not use your tick arrival timestamp, but the 1second resolution timestamp IBKR provides with each TickByTick update you receive. So you'd simply group the ticks bz the same timestamp. I work under the assumption that ticks arrive in order (I have never detected anything that pointed to the contrary) so that it is straight forward to make an OHLVC candle for each group of ticks., HistoricalTickByTick data also come with a 1second resolution timestamp, but may contain additional "non reportable" trades compared to the real-time feed for the same period. But they are tagged to that you could filter those out. 闯ü谤驳别苍 ? On Tue, Jan 28, 2025 at 10:54 AM, Sdoof wrote:
|
Re: reqHistoricalTicks() & batching vs. reqTickByTick() vs. reqHistoricalData(), Backtesting vs. Realtime execution
Good question. See for yourself when calling reqTickByTick(), try converting the time from an epoch to a timestamp with the format -> 'hh:mm:ss.ms'. Then call reqHistoricalTicks() and see a comparison to try and bridge the gap with how they are doing this and try to decipher if its doing a ceiling, floor, or truncation based on the summed tick size/prices, etc. I have not messed around with that yet, but may try later when I get the time. I will post my results here when I do assuming you do not find out yourself. If you do try it, posting your results would be appreciated. Hopefully I am understanding your question correctly. |
Re: reqHistoricalTicks() & batching vs. reqTickByTick() vs. reqHistoricalData(), Backtesting vs. Realtime execution
Very insightful discussion, when rounding to the 1 second, does it means that any tick with a "real" timestamp with be rounded to the second based on of +/-500ms or is it more of a ceiling/floor/truncation method? In other words assuming 2 ticks scenario: if a real tick timestamp is 11h05mn48.5001 (hh:mn:ss.ms) will the corresponding IBKR timestamp be 11h05mn49s? (1st arrival) if a real tick timestamp is 11h05mn49.4999 (hh:mn:ss.ms) will the corresponding IBKR timestamp be 11h05mn49s? (2nd arrival) |
Re: C++ preventing EReader reading when socket is closed
On restarting the TWS Application manually from TWS Application drop down menu while TWS API process is up & running?
TWS Api replies with Connection Closed callback via Updated source code void Connect() {
? if (m_pClient && m_pClient->isConnected())? ?m_pClient->eDisconnect(); ?
? bool bRes = m_pClient->eConnect((const char*)host_ip.c_str(), host_port,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientId, m_extraAuth); ? bool connection_result = m_pClient->isConnected();
? if (bRes && connection_result) {
? ? printf("Connected to %s:%d clientId:%d\n", m_pClient->host().c_str(), ? ? ? ? ? ?m_pClient->port(), clientId); ? ?? ? ? if (m_pClient && m_pClient->isConnected()) {
? ? ? m_pReader = std::unique_ptr<EReader>(new EReader(m_pClient, &m_osSignal)); ? ? ? if (m_pReader)? m_pReader->start(); ? ? ? ?else { ? ? ? ? std::cout << "Failed to create EReader instance\n"; ? ? ? ? exit(1); ? ? ? } ? ? } else { ? ? ? std::cout << "Client is not connected. Cannot create EReader\n"; ? ? ? exit(1); ? ? } ? } else {
? ? printf("Cannot connect to %s:%d clientId:%d\n", m_pClient->host().c_str(), ? ? ? ? ? ?m_pClient->port(), clientId); ? ? exit(1);
? } ? return;
} void connectionClosed() { ?std::this_thread::sleep_for(std::chrono::seconds(30)); ?Connect();?? }
Response received on simulating above mentioned activity |
Re: C++ preventing EReader reading when socket is closed
It is hard to follow what you are doing from the above code, however, you should not be calling "stop()" yourself. This is a function that is supposed to be internal to the API.
?
I see you are resetting your EReader object pointer in your code. Why? If the object is disconnected properly then this should not be required and the object can be directly reused.
?
Anyway, based on this error:
EReader::processMsgs (this=0x0) at IBUtilsCode/EReader.cpp (Segmentation Fault) ?
?
it looks like you are trying to de-reference the EReader object pointer when it has already been set to nullptr somewhere in your code.
?
?
?
? |
Re: Improvements to Intraday Momentum Strategies Using Parameter Optimization and Different Exit Strategies
Dear Akos,
?
thanks for sharing, a pity you couldn't replicate the returns of the Zarattini paper. Regarding your paper, looks promising but I would need to test it first out-of-sample.?
?
Kr, Trados |
Re: C++ preventing EReader reading when socket is closed
Hello David Armour,
I have been encountering a similar issue regarding the TWS application.
My goal is to simulate scenarios where the TWS application experiences a freeze or requires a restart due to memory-related issues, and to ensure a smooth failover to minimize disruptions.
To test this, I manually restart the TWS application after it has been successfully launched and logged in. Once both the TWS application and TWS API are up and running, I initiate a manual restart directly from within the TWS application itself to observe how the reconnection process behaves.
For handling reconnections after such restarts, I have been using the following pieces of code:
printf("Connection Closed\n");
void CBOEEngine::Connect() {
std::cout << "Connect to TWS called\n";
dbglogger_ << "Connect to TWS called\n";
dbglogger_ << "TRYING CONNECTING TO HOST_IP " << host_ip << " HOST_PORT " << host_port << " WITH CLIENT ID "
<< clientId << "\n";
//Disconnect is already connected
if (m_pClient && m_pClient->isConnected()) {
DBGLOG_CLASS_FUNC_LINE << "CLIENT ALREADY CONNECTED DISCONNECTING CLIENT & TRYING\n" << DBGLOG_ENDL_FLUSH;
m_pClient->eDisconnect();
}
//std::this_thread::sleep_for(std::chrono::seconds(1));
if (m_pReader) {
DBGLOG_CLASS_FUNC_LINE << "Deleting previous reader instance\n" << DBGLOG_ENDL_FLUSH;
m_pReader->stop();
m_pReader.reset();
}
//std::this_thread::sleep_for(std::chrono::seconds(1));
DBGLOG_CLASS_FUNC_LINE << "After disconnection request connection_result: " << m_pClient->isConnected() << DBGLOG_ENDL_FLUSH;
//! [connect]
bool bRes = m_pClient->eConnect((const char*)host_ip.c_str(), host_port, clientId, m_extraAuth);
//std::this_thread::sleep_for(std::chrono::seconds(1));
bool connection_result = m_pClient->isConnected();
DBGLOG_CLASS_FUNC_LINE << "bRes: " << bRes << " connection_result: " << connection_result << DBGLOG_ENDL_FLUSH;
if (bRes && connection_result) {
printf("Connected to %s:%d clientId:%d\n", m_pClient->host().c_str(), m_pClient->port(), clientId);
//! [ereader]
if(!m_pReader)
dbglogger_ << "Reader class instance is destroyed\n";
if (m_pClient && m_pClient->isConnected()) {
m_pReader = std::unique_ptr<EReader>(new EReader(m_pClient, &m_osSignal));
if (m_pReader) {
m_pReader->start();
} else {
dbglogger_ << "Failed to create EReader instance\n";
exit(1);
}
} else {
dbglogger_ << "Client is not connected. Cannot create EReader\n";
exit(1);
}
//! [ereader]
p_engine_listener_->OnConnect(true);
is_connected = true;
} else {
dbglogger_ << "CONNECTION FAILED " << host_ip << " HOST_PORT " << host_port << " @ CLIENT ID " << clientId << "\n";
dbglogger_ << "RETRY "
<< "\n";
printf("Cannot connect to %s:%d clientId:%d\n", m_pClient->host().c_str(), m_pClient->port(), clientId);
exit(1);
}
return;
// return bRes;
}
m_pClient->eDisconnect();
void EClientSocket::eDisconnect(bool resetState)
{
if ( m_fd >= 0 )
// close socket
SocketClose( m_fd);
m_fd = -1;
if (resetState) {
eDisconnectBase();
}
}
?
?
m_pReader->stop();
void EReader::stop() {
if (m_hReadThread) {
m_isAlive = false;
#if defined(IB_POSIX)
if (!pthread_equal(pthread_self(), m_hReadThread))
pthread_join(m_hReadThread, NULL);
#elif defined(IB_WIN32)
if (!(GetCurrentThreadId() == GetThreadId(m_hReadThread)))
WaitForSingleObject(m_hReadThread, INFINITE);
#endif
}
}
However, during the reconnection process, I frequently encounter the following errors EReader::processMsgs (this=0x0) at IBUtilsCode/EReader.cpp (Segmentation Fault) Connection Errors? Msg Not connected Socket is closed. Interestingly, I do not experience these issues when I manually turn off the internet connection and then re-enable it after some time. In such cases, the reconnection process appears to handle the disconnection more gracefully without triggering segmentation faults or socket closure errors. Current Setup:
|
Re: C++ preventing EReader reading when socket is closed
You are running an old version. There was a bug in the Windows version which was corrected on 5 Sep 2024 and release in the "latest" version.
?
Version 10.30.1t was released back in July 2024.
?
If you do not want to install the full latest version 10.33 you can simply modify the stop() function as follows:
?
?
There is a detailed explanation for the hang in the bug fix documentation: |
Re: C++ preventing EReader reading when socket is closed
My IB Gateway version is latest stable 10.30.1t, API version is latest stable 10.30.01 running on Windows. I replicated this on the sample TestCppClientStatic (debug, both win32 and x64). 1) start IB gateway, 2) start TestCppClientStatic, 3) shutdown IB gateway, 4) the program hangs. After putting a breakpoint at m_pEReader->stop() in void EClientSocket::eDisconnect(bool resetState), it seems the hang happened at WaitForSingleObject in EReader::stop(). See call stack below.
?
--hang here --> WaitForSingleObject(m_hReadThread, INFINITE); > ? ?TestCppClientStatic.exe!EReader::stop() Line 70 ? ?C++ ? ? ?TestCppClientStatic.exe!EClientSocket::eDisconnect(bool resetState) Line 241 ? ?C++ ? ? ?TestCppClientStatic.exe!EClientSocket::onClose() Line 370 ? ?C++ ? ? ?TestCppClientStatic.exe!EClientSocket::receive(char * buf, unsigned int sz) Line 274 ? ?C++ ? ? ?TestCppClientStatic.exe!EReader::onReceive() Line 191 ? ?C++ ? ? ?TestCppClientStatic.exe!EReader::processNonBlockingSelect() Line 173 ? ?C++ ? ? ?TestCppClientStatic.exe!EReader::readToQueue() Line 93 ? ?C++ ? ? ?TestCppClientStatic.exe!EReader::readToQueueThread(void * lpParam) Line 85 ? ?C++ |