开云体育

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

Building 1min chart from start of the day and continue in real time

 

Hello,
I am pretty new to this API, I would like to build a "chart" (list of bars) of? 1min bars for the day.

When I start the software I want it to collect the history from start of the day (including premarket) until now and then keep collecting or building 1min bars in real time.

Can someone direct me to the process of doing so ?

Thank you all !


Minor issue

Jacky
 

The reported start in an end historical data seems to the difference between given end time and duration and as a consequence does not take into account weekend days whereas the data itself is in accordance with the request.


Re: where to put logic that sets trading mode to "close out positions only" (c++)

 

I haven't use this one yet but this seems like what you are looking for, no?



"Beginning with API v973.03, requests can be made to receive real time updates about the daily P&L and unrealized P&L for an account, or for individual positions. Financial Advisors can also request P&L figures for 'All' subaccounts, or for a portfolio model. In API v973.05+/TWS v968+ this is further extended to include realized P&L information at the account or individual position level."
?
"These newer P&L API functions demonstrated below return the data which is displayed in the TWS Portfolio Window in current versions of TWS (v963+). As such, the P&L values are calculated based on the reset schedule specified in TWS Global Configuration (by default an instrument-specific reset schedule) and this setting affects values sent to the associated API functions as well. Also in TWS, P&L data from virtual forex positions will be included in the account P&L if and only if the Virtual Fx section of the Account Window is expanded."

P&L subscription requests for accounts

Subscribe using the??function:

  • m_pClient->reqPnL(7001, "DUD00029", "");
  • Introducing broker accounts with less than 50 subaccounts can receive aggregate PnL for all subaccounts by specifying 'All' as the account code.
  • With requests for advisor accounts with many subaccounts and/or positions can take several seconds for aggregated P&L to be computed and returned.
  • For account P&L data the TWS setting "Prepare portfolio PnL data when downloading positions" must be checked.

Updates are sent to?

  • void TestCppClient::pnl(int reqId, double dailyPnL, double unrealizedPnL, double realizedPnL) {
    printf("PnL. ReqId: %d, daily PnL: %g, unrealized PnL: %g, realized PnL: %g\n", reqId, dailyPnL, unrealizedPnL, realizedPnL);
    }

Cancel unnecessary subscriptions with the??function:

  • m_pClient->cancelPnL(7001);
    ?


Re: where to put logic that sets trading mode to "close out positions only" (c++)

 

That's a bummer. Do the callbacks that give order information still work? I've been relying on orderStatus() callback. Because I need fill information too.


Re: where to put logic that sets trading mode to "close out positions only" (c++)

Nick
 

开云体育

The reason it isn't suitable is the same reason you started the thread. It fires whenever it fires and it can't be relied upon to trigger critical application actions.

I know it's more work to do it another way but if account updates aren't giving you what you need then what other choice do you have?


On 2/11/2020 11:46 PM, tbrown122387@... wrote:

To maintain all the accounting state is a lot of work, at least to do it properly. There’s nothing pre-made to do this? Why isn’t this suitable?


Re: where to put logic that sets trading mode to "close out positions only" (c++)

 

To maintain all the accounting state is a lot of work, at least to do it properly. There’s nothing pre-made to do this? Why isn’t this suitable?


Re: where to put logic that sets trading mode to "close out positions only" (c++)

Nick
 

Portfolio updates are not the tool for what you want.

I would suggest monitoring prices via one of the live streams and storing the latest price. Also have a routine that wakes up at a specific interval (timers are often used for this) and evaluate your exit conditions there.

To be thorough you might also want to detect when prices haven't updated for longer than is normal so you can raise an alarm or take some corrective action.

On 2/11/2020 7:57 PM, tbrown122387@... wrote:
I'm sitting here wondering why TestCppClient::updatePortfolio wasn't called. Clearly it's a very important segment of code (see below). If a maximum loss is exceeded, or if it's close to the end of the day, everything stops trading. Well, trading is only conducted to close positions.


where to put logic that sets trading mode to "close out positions only" (c++)

 

I'm sitting here wondering why TestCppClient::updatePortfolio wasn't called. Clearly it's a very important segment of code (see below). If a maximum loss is exceeded, or if it's close to the end of the day, everything stops trading. Well, trading is only conducted to close positions.

Looking at the documentation (), this function should be called every three minutes, or if there is a position change, as long as I call

m_pClient->reqAccountUpdates(true, "U150462");

earlier on (I do).? It would be a lot nicer if it was called more often. Where does everyone else put this logic? Next time I'll write more stuff out to the log file (and not delete the program's output).


void TestCppClient::updatePortfolio(const Contract& contract, double position,
??????????????????????????????????? double marketPrice, double marketValue, double averageCost,
??????????????????????????????????? double unrealizedPNL, double realizedPNL, const std::string& accountName){

??? // set state
??? m_upnl = unrealizedPNL;
??? m_rpnl = realizedPNL;

??? // criterion 1 to stop trading
??? bool maxLossExceeded = m_upnl + m_rpnl < m_maxLoss;

??? // criterion 2 to stop trading: within 5 minutes of 4:15PM EST
??? // NB: ignoring IB-provided functions and relying on my server's date/time
??? std::time_t t = std::time(0);
??? std::tm* now = std::localtime(&t);
??? bool endOfDayNear = (now->tm_min >= 10) && (now->tm_hour >= 16);

??? // turn off trading if either is true
??? if( maxLossExceeded || endOfDayNear ) {
??????? std::cout << "TURNING OFF TRADING OPERATIONS\n";
??????? m_trading = false;
??? }
}


Re: Error. Id: -1, Code: 509, Msg: Exception caught while reading socket

 

I am using c++.

Deleaker, I'll keep that in mind, thanks.

Yeah, I realize this question probably doesn't have enough information to be answered. I was just putting it out there to see if there was a typical solution, or if anyone had any familiarity. It's interesting, because it doesn't show up in the documentation: https://interactivebrokers.github.io/tws-api/message_codes.html


Orders on both sides (BUY and SELL) of the same contract

Jos van de Werken
 

Hello all,

?

I’ve built a program trading option combos. I protect those option positions with a group of four SELL-orders with all kind of price and time conditions. (in an OCA group)

?

When I try to extend this position by placing more BUY-orders I always get the message “This account cannot have open orders(including Combo) on both sides of the same US Option contract in related accounts.”

The problem can also occur when option combos overlap with each other.


?

The only solution I found to solve this issue is to cancel the SELL-orders, place the new BUY-orders, wait till they get filled and place again all SELL-orders.

?

There are a lot of disadvantages to this approach:

  • I would always have my safety-SELL-orders in place, regardless of
  1. the well-being of computer
  2. the presence my internet-connection
  3. other (BUY) orders getting filled or not
  • The SELL-orders with complex price and time conditions have been calculated in a certain situation. Afterwards it’s hard to restore these orders as they were. After cancelling the SELL-orders I have to remember them as they were to restore them again. It might be unsafe to cancel them, I’ve to rely on a lot of components (software, hardware, power supply, market accepting the BUY orders) to be able to restore the,

?

Does anyone know an easy solution or workaround for this issue? Is it possible to pause the SELL-orders and activate them again later? Or are the other ideas to bypass this problem?

?

Thanks.

Jos


Apparent roll-back of TWS "Latest" build -- is legacy DDE API order submission still broken for everyone else?

 

TWS "Latest" auto-installed a version 978.1j this morning, which sounds like a roll back of the 979.3e "Latest" build that broke everything (including order submission via Excel legacy DDE API).
I was hopeful that order submission functionality would be restored with this roll-back, but while several of the other bugs the update to 979.3e caused seem to have been fixed, I still don't seem to be able to submit orders via (legacy) DDE.
Can anyone else check and confirm:
- Did your "Latest" build also get rolled back to 978.1j?
- If so and you used the legacy DDE order submission, is that working for you?
?


Re: Error. Id: -1, Code: 509, Msg: Exception caught while reading socket

 

What programming language are you using?

Generally speaking the errors 509 and 504 "exception caught while reading socket" happen when your program stomps on the memory space in error. The fastest way to fix that is to remember exactly what you changed recently, if it was working fine before. But, I have encountered situations where it was not a recent mistake, but an old one that took a long time to appear. Fun, right?

Hopefully you can figure out what's wrong by looking at your code closely. But, another way is to periodically exercise your code in extreme situations if need be, to try to make it break. If it takes weeks to figure out where the problem is and you're still stuck, that's when I have turned to 3rd party tools (one example was a program called deleaker) which pad your program with protected memory space and will tell you when that space becomes violated, and then you can set breakpoints at memory addresses and trace backwards.


Re: realtimeBar subscription stops during the trading session

 

Just FYI, I've contacted the API Support and here the answer I've got:

''' The existing request may not have terminated. When bust event occurs please try using cancelRealTimeBars() then call reqRealTimeBars() again. '''

Will update my application and test it for few days - will update after that.


Re: PACEAPI questions

 

ticket opened: and it was fixed in:


Definitive list of Exchange codes

 

Where can I find a definitive list of Exchange Codes returned by?tickByTickAllLast?

Thanks.


FYI: C++ multi-threaded crash in eConnectImpl - gethostbyname (linux)

 

Hello, this is just FYI.? ? My process started crashing recently when it tried to connect to TWS.? I have two threads each running its own instance of the ib client.? To fix, I had modified EClientSocket::eConnectImpl()? from using gethostbyname() call to using gethostbyname_r() call to resolve the issue.? To be clear -? If you only have a single instance of ib client, you don't need to worry about this. Hope it will be helpful to someone.?


Error. Id: -1, Code: 509, Msg: Exception caught while reading socket

 

Any idea what causes this?

I also get this one:

Error. Id: -1, Code: 509, Msg: Exception caught while reading socket - Numerical result out of range


I found this similar thread: /g/twsapi/topic/4047617#33752

But I couldn't follow it to a solution.


Re: TWS API earning dates..

 

Robbo: still valid if subscribed to Horizon Wall Streets as Josh pointed out.

C# example:

public void fundamentalData(int reqId, string data)
{
try
{
string ticker = XMLstringExtract(data, "Ticker");
data = XMLstringExtract(data, "EarningsList");
string date = XMLstringExtract(data, "Date");
string confirmed = XMLstringExtract(data, "Etype");
Log("Next " + ticker + " Earnings: " + date + " " + confirmed);
}


Re: reqHistoricalData - Stock Tickers

 

If IB meets your needs, then that's great, but in addition to the other suggestions you could try IQFeed.?


Re: reqHistoricalData - Stock Tickers

 

You might also look at these providers: