Link to home
Create AccountLog in
Avatar of gbcbr
gbcbrFlag for Cyprus

asked on

Error IndexOutOfBoundsException: Index: 0, Size: 0

I have unexpected problem with old code after rearranging one big code into few different classes.
Before this code worked perfect without any complaining to Array.
public class AlgoTrade {

    MarketDataSnapshot incomingQuote;
    double inX[] = new double[3];
    double Avg = 0;

    public void parseMarketDataSnapshot(ITransportable message, boolean printMarketData) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, FieldNotFound, Exception {

        if (message instanceof MarketDataSnapshot) {
            incomingQuote = (MarketDataSnapshot) message;

            if (printMarketData || incomingQuote.getMDReqID() != null) {
                try {

                    miniBot(message, incomingQuote.getInstrument().getSymbol(), incomingQuote.getAskOpen(), incomingQuote.getBidOpen(), incomingQuote.getOpenTimestamp());

                } catch (NotDefinedException ex) {
                    Logger.getLogger(DBFXConnect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }
    
    ISide side = null;

    public void miniBot(ITransportable message, String symbol, double askOpen, double bidOpen, UTCTimestamp openTimestamp)
            throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, FieldNotFound, NotDefinedException, Exception {

        if ("USD/JPY".equalsIgnoreCase(symbol.trim())) {

            Avg = (askOpen + bidOpen) / 2;
            inX[1] = Avg;
            

            System.out.println("USD/JPY   " + askOpen + " ask : bid " + bidOpen + "  " + openTimestamp);

            if (Avg > 0) {
                System.out.println("message SLOSELL[1] : " + message);

                side = SideFactory.SELL;
                setSLO(message, side);
            }
        }
    }
    public List accounts = new ArrayList();

    public void setSLO(ITransportable message, ISide side) throws NotDefinedException, Exception {

        final String cem = Util.getCurrentlyExecutingMethod();
        CollateralReport acct = (CollateralReport) accounts.get(0);
        incomingQuote = (MarketDataSnapshot) message;
        System.out.println("MDS message  " + message);
        setAll(side);
    }
    double start;
    double stopPx;
    OrderSingle orderSingle;
    private String mRequestId;
    IGateway fxcmGateway;

    public void setAll(ISide side) throws NotDefinedException, Exception {

        final String cem = Util.getCurrentlyExecutingMethod();
        CollateralReport acct = (CollateralReport) accounts.get(0);

        if (side == SideFactory.BUY) {
            start = incomingQuote.getBidOpen();
            stopPx = incomingQuote.getBidClose();
        } else if (side == SideFactory.SELL) {
            start = incomingQuote.getAskOpen();
            stopPx = incomingQuote.getAskClose();
        }

        if (true) {
            orderSingle = MessageGenerator.generateOpenOrder(
                    incomingQuote.getQuoteID(),
                    start,
                    acct.getAccount(),
                    acct.getQuantity(),
                    side,
                    incomingQuote.getInstrument().getSymbol(), cem);

            orderSingle.setPrice(start);
            orderSingle.setStopPx(stopPx);
            orderSingle.setTimeInForce(TimeInForceFactory.IMMEDIATE_OR_CANCEL);
            orderSingle.setOrdType(OrdTypeFactory.MARKET);
            System.out.println("orderSingle.getTransactTime() = " + orderSingle.getTransactTime());
            System.out.println("orderSingle.getQuoteID() = " + orderSingle.getQuoteID());
            System.out.println("side = " + side.toString());
            System.out.println("orderSingle.getPrice() = " + orderSingle.getPrice());
            System.out.println("orderSingle.getStopPx() = " + incomingQuote.getQuoteID());
            System.out.println("");
            System.out.println("start = " + start);
            System.out.println("orderSingle.getOrdType() = " + orderSingle.getOrdType());
            mRequestId = fxcmGateway.sendMessage(orderSingle);
        }
    }
}

Open in new window

This is output from this code:
30.12.2010 13:44:25 lionfx_algo.trade.DBFXConnect$1 messageArrived
SEVERE: null
USD/JPY   81.529 ask : bid 81.509  20101230-11:44:25
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.RangeCheck(ArrayList.java:547)
        at java.util.ArrayList.get(ArrayList.java:322)
        at lionfx_algo.trade.AlgoTrade.setSLO(AlgoTrade.java:94)
message SLOSELL[1] : MarketDataSnapshot{QuoteID='Q-EU0094524-USDJPY-178798029',Instrument={2,USD/JPY}, Time=11:44:25, Date=20101230, Interval=FXCMTimingInterval:Tick (0), Complete=true, MDReqID='null', TradingSessionID='FXCM', ...............'}}}
        at lionfx_algo.trade.AlgoTrade.miniBot(AlgoTrade.java:84)
        at lionfx_algo.trade.AlgoTrade.parseMarketDataSnapshot(AlgoTrade.java:54)
        at lionfx_algo.trade.DBFXConnect$1.messageArrived(DBFXConnect.java:97)
        at com.fxcm.internal.transport.FXCMGateway.update(FXCMGateway.java:769)
        at com.fxcm.messaging.util.fix.FIXUserSession$BackToUserQueue.run(FIXUserSession.java:607)
        at java.lang.Thread.run(Thread.java:680)

Open in new window

at lionfx_algo.trade.AlgoTrade.setSLO(AlgoTrade.java:94) >>>>>CollateralReport acct = (CollateralReport) accounts.get(0); at setSLO method.
And this is output from original code:
 
message SLOSELL : MarketDataSnapshot{QuoteID='Q-EU0094524-EURJPY-179574327',Instrument={10,EUR/JPY}, Time=12:00:17, Date=20101230, Interval=FXCMTimingInterval:Tick (0),...........}}}
=> COLLATERAL REPORT  CollateralReport{mAccount='00779442', .........}
108.183 ask : bid 108.148
orderSingle.getTransactTime() = 20101230-12:00:20
orderSingle.getQuoteID() = Q-EU0094524-EURJPY-179576036
side = SideFactory:Sell (2)
orderSingle.getPrice() = 108.148
orderSingle.getStopPx() = Q-EU0094524-EURJPY-179576036
start = 108.148
orderSingle.getOrdType() = OrdType:Stop Limit (4)
=>

Open in new window

Why it shows Error IndexOutOfBoundsException if I didn't change any array parameters?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

>>CollateralReport acct = (CollateralReport) accounts.get(0);

You're assuming that accounts isn't empty -- that's your problem
Avatar of gbcbr

ASKER

But when I start old code it doesn't see any problem.
How to check status of accounts in this case?
For the moment, you could throw an Exception
if (accounts.size() < 1) {
    throw new RuntimeException("accounts is empty");
}

Open in new window

Avatar of gbcbr

ASKER

Maybe this happen because I have
>private static List accounts = new ArrayList();
into previous class, so it's open to arrays?
If so, how to solve it?
your old code must be initializing the array list (accounts). you can place the code in try catch block or simply to check the status just write System.out.println(accounts.isEmpty());

Run the code i just posted and let me know what happens
Avatar of gbcbr

ASKER

public List accounts = new ArrayList();

    public void setSLO(ITransportable message, ISide side) throws NotDefinedException, Exception {

        if (accounts.size() < 1) {
            throw new RuntimeException("accounts is empty");
        }

        final String cem = Util.getCurrentlyExecutingMethod();
        CollateralReport acct = (CollateralReport) accounts.get(0);
        incomingQuote = (MarketDataSnapshot) message;
        System.out.println("MDS message  " + message);
        setAll(side);
    }

Open in new window


30.12.2010 14:33:55 lionfx_algo.trade.DBFXConnect$1 messageArrived
SEVERE: null
java.lang.RuntimeException: accounts is empty

Open in new window

OK - so you need to find out why it's empty in one case and not the other
Avatar of gbcbr

ASKER

This I'm doing last 3 days
Avatar of gbcbr

ASKER

I check both of these ways in old and new codes.
Result the same :
'accounts is empty' and 'true'
with one big difference: old code after these messages starts working as before and new one generate the same error and doesn't work.
the class file you have given is not initializing the accounts list anywhere.

so there can be only one probability that it is being initialized from somewhere else. Without adding values to accounts list your code wont' run. so check your old code and see it it is setting accounts a value somewhere.
>>This I'm doing last 3 days

How? You need to trace the history of 'accounts' in a debugger
Avatar of gbcbr

ASKER

You mean that
public List accounts = new ArrayList();
doesn't initialize ArrayList in this class?
Into old code I have only one place mentioned 'accounts'
 
else if (message instanceof CollateralReport) {
                    // got a response to our request for accounts
                    CollateralReport cr = (CollateralReport) message;
                    System.out.println("=> COLLATERAL REPORT  " + message);
                    if (accountMassID.equals(cr.getRequestID())) {
                        //System.out.println("client: reply = " + cr);
                        accounts.add(cr);

Open in new window

but I don't think that it has any relation to this problem
there it is

accounts.add(cr);

add values from the new code and it should work.
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
>>I have only one place mentioned 'accounts'

There are two conditions determining whether accounts gets added to there - check them both
my mistake. sorry for the confusion

>>the class file you have given is not initializing the accounts list anywhere.

there i wanted to say adding values to the list and not to initialize it. obviously it would have been a NullPointerException in that case.

>>Without adding values to accounts list your code wont' run.
this is what i wanted to say.
Avatar of gbcbr

ASKER

Thank you
Not quite sure why you accepted that answer gbcbr - it doesn't say anything different essentially from what i mentioned earlier. If you have determined why the List is empty in one case and not the other (it really goes without saying that one codebase fills it and the other doesn't) then you should state that for the benefit of future visitors
Avatar of gbcbr

ASKER

I told you many times that I'm not an expert, I use Java for my needs only, so I need practical advises, not theoretical.
Please compare
>>>OK - so you need to find out why it's empty in one case and not the other
and
>>>before calling get() to an arraylist you must give it some values to fetch from, else getting element  will cause error. That is what happening to your code. old code is feeding accounts with some values prior to fetching them back. your new code is not doing so. it is not feeding any values and trying to get them.
I new that I have to find solution for the problem, but I'm NOT AN EXPERT and I don't know how, this is the reason why I ask expert to give me practical advises.
Anyway
Merry Christmas and Happy New Year
>>Please compare

Yes, one is an expanded version of the other. Both those particular sets of comments are theoretical.

Let me put it another way: are both apps now working? If so, what did you do to get the failing one working?