Using all open prices in multi-instrument strategies
A strategy dealing with several instruments will receive several
onOpen() callback invocations related to the same
date, one for each instrument.
In the implementation, one can access the list of bars using
getBarSeries().
It is also possible to access the list of bars corresponding to
another instrument (or other bar frequency) using
getBarsFor(Instrument i, BarType type).
Since version 2.0, the barSeries list also contains the last
openPrice, in addition to the list of closed bars. This allows to
check how many instruments have received an open price for the
current (not closed yet) bar:
@Override
public void onOpen(OpenPrice openPrice) {
if (getNbOpenBars(Daily) == getPortfolio().getInstruments().size()) {
// do something only when all open prices are available for the current bar
}
}
private int getNbOpenBars(BarType type) {
int nbOpen = 0;
for (Tradeable instrument : getPortfolio().getInstruments()) {
BarSeries barsForInstrument = getBarsFor(instrument, type);
if (barsForInstrument.hasNewOpen()) {
nbOpen++;
}
}
return nbOpen;
}
Similarily, it is possible in the onClose() method
to check how many closed bars are available since the number of
available open prices will decrease for each close. In , all close
prices are available when the number of available open prices is
zero :
@Override
public void onClose(Bar bar) {
if (getNbOpenBars() == 0) {
// do something only when all close prices are available for the current bar
}
}
In the onOpen implementation, the strategy can then
retrieve all instrument open prices using
getBarsFor(instrument,
BarType.Daily).getLastOpen().
In the onClose implementation, use
getBarsFor(instrument, BarType.Daily).getLastBar() to
get all instruments bar information.