+ if (dtxt!=null) dtxt.println(yarrgresult);
+ }
+ return true;
+ }
+
+ private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
+ // if (dtxt!=null) dtxt.println("ARBITRAGE?");
+ int profit = 0;
+ SortedSet<int[]> buys = arb_bs.get(0);
+ SortedSet<int[]> sells = arb_bs.get(1);
+ while (true) {
+ int[] buy, sell;
+ try {
+ // NB "sell" means they sell, ie we buy
+ sell = sells.last();
+ buy = buys.first();
+ } catch (NoSuchElementException e) {
+ break;
+ }
+
+ int unitprofit = buy[0] - sell[0];
+ int count = buy[1] < sell[1] ? buy[1] : sell[1];
+ // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
+ // +" => x"+count+" @"+unitprofit);
+
+ if (unitprofit <= 0)
+ break;
+
+ profit += count * unitprofit;
+ buy[1] -= count;
+ sell[1] -= count;
+ if (buy[1]==0) buys.remove(buy);
+ if (sell[1]==0) sells.remove(sell);
+ }
+ // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
+ return profit;
+ }
+
+ private class arbitrageOfferComparator implements Comparator {
+ public int compare(Object o1, Object o2) {
+ int p1 = ((int[])o1)[0];
+ int p2 = ((int[])o2)[0];
+ return p2 - p1;
+ }
+ }
+
+ private @SuppressWarnings("unchecked")
+ void calculateArbitrage(ArrayList<ArrayList<String>> data) {
+ int arbitrage = 0;
+ ArrayList<SortedSet<int[]>> arb_bs = null;
+ String lastcommod = null;
+ Comparator compar = new arbitrageOfferComparator();
+
+ for (ArrayList<String> row : data) {
+ String thiscommod = row.get(0);
+ // if (dtxt!=null) dtxt.println("ROW "+row.toString());
+ if (lastcommod == null || !thiscommod.equals(lastcommod)) {
+ if (lastcommod != null)
+ arbitrage += calculateArbitrageCommodity(arb_bs);
+ // if (dtxt!=null) dtxt.println("ROW rdy");
+ arb_bs = new ArrayList<SortedSet<int[]>>(2);
+ arb_bs.add(0, new TreeSet<int[]>(compar));
+ arb_bs.add(1, new TreeSet<int[]>(compar));
+ // if (dtxt!=null) dtxt.println("ROW init");
+ lastcommod = thiscommod;
+ }
+ for (int bs = 0; bs < 2; bs++) {
+ String pricestr = row.get(bs*2 + 2);
+ if (pricestr == null)
+ continue;
+ int[] entry = new int[2];
+ // if (dtxt!=null) dtxt.println("ROW BS "+bs);
+ entry[0] = parseQty(pricestr);
+ entry[1] = parseQty(row.get(bs*2 + 3));
+ arb_bs.get(bs).add(entry);
+ }
+ }
+ arbitrage += calculateArbitrageCommodity(arb_bs);
+ if (arbitrage != 0) {
+ arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
+ } else {
+ arbitrageResult.setText("no arbitrage");