Example #1
0
  @Override
  public void updateAccountValue(String key, String value, String currency, String accountName) {
    try {
      if (logger.isDebugEnabled())
        logger.debug(
            "updateAccountValue: {} {} {} {}", new Object[] {key, value, currency, accountName});

      if ("AccountCode".equals(key)) {
        synchronized (this) {
          this.accountCode = value;
          notifyAll();
        }
      } else if ("AvailableFunds".equalsIgnoreCase(key)
          && isCurrencyCode(currency)
          && Util.isDouble(value)) {
        portfolio.setCash(currency, Double.parseDouble(value));
      } else if ("BuyingPower".equalsIgnoreCase(key)
          && isCurrencyCode(currency)
          && Util.isDouble(value)) {
        portfolio.setBaseCurrency(currency);
      } else if ("ExchangeRate".equalsIgnoreCase(key)
          && isCurrencyCode(currency)
          && Util.isDouble(value)) {
        portfolio.setExchangeRate(currency, Double.parseDouble(value));
      }

    } catch (Throwable t) {
      logger.error(t.getMessage(), t);
    }
  }
  @Test
  public void shouldReturnTotalValue() {
    Portfolio portfolio = new Portfolio();

    Stock stock = new Stock("Infi", 5);

    portfolio.addStock(stock);

    // Create
    StockMarket stockMarket = EasyMock.createMock(StockMarket.class);

    // Add Expectation
    EasyMock.expect(stockMarket.getPrice("Infi")).andReturn(10);

    EasyMock.replay(stockMarket);

    portfolio.setStockMarket(stockMarket);

    int totalValue = portfolio.getTotalValue();

    Assert.assertEquals("Unexpected portfolio total value", 50, totalValue);

    // Verify
    EasyMock.verify(stockMarket);
  }
  @Test
  public void shouldAddStockToPortfolio() {
    Portfolio portfolio = new Portfolio();

    Stock stock = new Stock("Infi", 5);

    portfolio.addStock(stock);

    Assert.assertNotNull(portfolio.getStocks());
    Assert.assertEquals("Unexpected stock list size", 1, portfolio.getStocks().size());
  }
Example #4
0
  public static void ImportPortfolios(String filename, Map<String, Portfolio> pss)
      throws IOException, ParseException {
    // String filename = "ExportedPortfolios.txt";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line = "";
    while ((line = br.readLine()) != null) {
      List<String> strings = Arrays.asList(line.split("\\|"));
      // System.out.println(strings.get(0)+" "+strings.get(1));
      String name = strings.get(0);
      String pass = decrypt(strings.get(1));

      users.put(name, pass);
      Map<String, Integer> equitie = new HashMap<String, Integer>();
      Map<String, Account> Accountt = new HashMap<String, Account>();
      List<Transaction> trans = new ArrayList<Transaction>();

      for (int i = 2; i < strings.size(); i++) {
        String s = strings.get(i);
        String[] lst = s.split(",");
        if (lst.length >= 3) {
          if (lst[0].equals("e")) {
            equitie.put(lst[1], Integer.parseInt(lst[2]));
          } else if (lst[0].equals("a")) {
            SimpleDateFormat sdf =
                new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
            Date d = sdf.parse(lst[5]);
            Account ac =
                new Account(lst[1], lst[2], Float.parseFloat(lst[3]), Float.parseFloat(lst[4]), d);
            Accountt.put(lst[2], ac);
          } else if (lst[0].equals("t")) {
            SimpleDateFormat sdf =
                new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
            Date d = sdf.parse(lst[4]);
            trans.add(new Transaction(lst[1], lst[2], Float.parseFloat(lst[3]), d));
          } else if (lst[0].equals("b")) {
            SimpleDateFormat sdf =
                new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
            Date d = sdf.parse(lst[4]);
            trans.add(
                new Transaction(
                    lst[0], sEquities.get(lst[1]), Integer.parseInt(lst[2]), lst[3], d));
          }
        }
      }
      Portfolio p = new Portfolio(name, equitie, Accountt);
      p.setTrans(trans);
      pss.put(name, p);
    }
  }
  public Position(Portfolio portfolio, String assetName, int[] quantity, long[] timeMillSec) {

    this.name = assetName;
    this.portfolio = portfolio;

    portfolio.addPosition(assetName, quantity, timeMillSec);
  }
Example #6
0
  // type = bull, bear or noGrowth
  public Simulator(int numberOfSteps, int daysPerStep, boolean seeSteps, String type) {
    this.numberOfSteps = numberOfSteps;
    this.daysPerStep = daysPerStep;
    this.seeSteps = seeSteps;

    Portfolio.getCurrentPortfolio().initPortfolioCopy();
  }
  public Position(Portfolio portfolio, String assetName, int quantity) {

    this.name = assetName;
    this.portfolio = portfolio;

    portfolio.addPosition(assetName, quantity);
  }
Example #8
0
  private void closeOpenOrder(OpenOrder openOrder, double commissionAmount) {
    openOrdersById.remove(openOrder.getOrderId());
    if (Double.isNaN(commissionAmount) || commissionAmount <= 0.0) {
      commissionAmount =
          commission.calculate(openOrder.getQuantityFilled(), openOrder.getAvgFillPrice());
    }
    openOrder.setCommission(commissionAmount);
    logger.info("{} {}", openOrder.isFilled() ? "Filled" : "Partially filled", openOrder);

    Position position = portfolio.getPosition(openOrder.getSymbol());
    double[] values =
        position.update(
            openOrder.getFillDate(),
            openOrder.getQuantityFilled(),
            openOrder.getAvgFillPrice(),
            openOrder.getCommission());

    logTrade(openOrder, position.getQuantity(), values[0], values[1], values[2]);

    for (OrderListener listener : orderListeners) {
      try {
        listener.onOrderFilled(openOrder, position);
      } catch (Throwable t) {
        logger.error(t.getMessage(), t);
      }
    }
  }
  public Position(
      Portfolio portfolio, String assetName, float[] price, int quantity, long[] priceTimeMillSec) {

    this.name = assetName;
    this.portfolio = portfolio;

    portfolio.addPosition(assetName, price, quantity, priceTimeMillSec);
  }
Example #10
0
  public Position(
      Portfolio portfolio, String assetName, double[] price, int quantity, long timeStepMilliSec) {

    this.name = assetName;
    this.portfolio = portfolio;

    portfolio.addPosition(assetName, price, quantity, timeStepMilliSec);
  }
Example #11
0
 public PositionView createPositionView(Portfolio portfolio, Integer instrumentId) {
   Double lastPrice = mapStockPrices.get(instrumentId);
   if (lastPrice == null) return null;
   Position position = portfolio.getPosition(instrumentId);
   return new PositionView(
       portfolio.pmId,
       instrumentId,
       position.quantity,
       lastPrice,
       position.calculateProfitLoss(lastPrice));
 }
Example #12
0
  public Position(Portfolio portfolio, String assetName, int[] quantity, String[] timeMillSec) {

    this.name = assetName;
    this.portfolio = portfolio;

    long[] time = new long[timeMillSec.length];

    int i = 0;
    for (String e : timeMillSec) {
      time[i++] = Timestamp.valueOf(e).getTime();
    }

    portfolio.addPosition(assetName, quantity, time);
  }
Example #13
0
 @Override
 public void updatePortfolio(
     Contract contract,
     int qty,
     double marketPrice,
     double marketValue,
     double averageCost,
     double unrealizedPNL,
     double realizedPNL,
     String accountName) {
   try {
     if (logger.isDebugEnabled())
       logger.debug(
           "updatePortfolio: {} {} {} {} {} {} {} {}",
           new Object[] {
             Util.toString(contract),
             qty,
             marketPrice,
             marketValue,
             averageCost,
             unrealizedPNL,
             realizedPNL,
             accountName
           });
     if (qty != 0) {
       Symbol symbol = toSymbol(contract);
       double costBasis =
           averageCost
               / (contract.m_multiplier != null ? Integer.parseInt(contract.m_multiplier) : 1);
       Position position = new Position(symbol, qty, costBasis, 0.0);
       portfolio.setPosition(symbol, position);
       logger.info(
           "Updated {}, last: {}, unrealized pnl: {}",
           new Object[] {position, marketPrice, position.getProfitLoss(marketPrice)});
     }
   } catch (Throwable t) {
     logger.error(t.getMessage(), t);
   }
 }
Example #14
0
 public Metric setPositionQuantity(int[] quantity, String[] timeMillesc) {
   return portfolio.setPositionQuantity(name, quantity, timeMillesc);
 }
Example #15
0
 public void removePositionPrice() {
   portfolio.removePositionPrice(name);
 }
Example #16
0
  public static void ExportPortfolios() throws FileNotFoundException, UnsupportedEncodingException {
    String filename = "xp.txt";
    Iterator it = users.entrySet().iterator();
    PrintWriter writer = new PrintWriter(filename, "UTF-8");
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();

      writer.print(pair.getKey() + "|" + encrypt((String) pair.getValue()));
      writer.print("|");
      Portfolio p = portfolios.get(pair.getKey());
      Map<String, Integer> equitiess = p.getEquities();
      Iterator it1 = equitiess.entrySet().iterator();
      while (it1.hasNext()) {
        Map.Entry e = (Map.Entry) it1.next();
        writer.print("e," + e.getKey() + "," + e.getValue() + "|");
      }
      Map<String, Account> accountss = p.getAccounts();
      Iterator it2 = accountss.entrySet().iterator();
      while (it2.hasNext()) {
        Map.Entry a = (Map.Entry) it2.next();
        Date d = ((Account) a.getValue()).getDateAdded();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
        String da = sdf.format(d);
        writer.print(
            "a,"
                + ((Account) a.getValue()).getType()
                + ","
                + ((Account) a.getValue()).getName()
                + ","
                + (((Account) a.getValue()).getInitialAmount()
                    + ","
                    + (((Account) a.getValue()).getCurrentAmount())
                    + ","
                    + da
                    + "|"));
      }
      for (Transaction tr : p.getTrans()) {
        if (tr.getType().equals("t")) {
          Date d = tr.getDate();
          SimpleDateFormat sdf =
              new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
          String da = sdf.format(d);
          writer.print(
              "t," + tr.getA1() + "," + tr.getA2() + "," + tr.getAmount() + "," + da + "|");
        } else {
          Date d = tr.getDate();
          SimpleDateFormat sdf =
              new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
          String da = sdf.format(d);
          writer.print(
              tr.getType()
                  + ","
                  + tr.getEquity().getTicker()
                  + ","
                  + tr.getNumber()
                  + ","
                  + tr.getA1()
                  + da
                  + "|");
        }
      }
      writer.println();
    }
    writer.close();
  }
Example #17
0
 public void removePositionQuantity() {
   portfolio.removePositionQuantity(name);
 }
Example #18
0
 public void setPositionQuantity(int quantity) {
   portfolio.setPositionQuantity(name, quantity);
 }
Example #19
0
 public Metric setPositionQuantity(double[] quantityD, long[] timeMillesc) {
   return portfolio.setPositionQuantity(name, quantityD, timeMillesc);
 }