Source code

    001/*
    002# Licensed Materials - Property of IBM
    003# Copyright IBM Corp. 2015
    004 */
    005package vwap;
    006
    007import static java.math.BigDecimal.ZERO;
    008import static java.math.MathContext.DECIMAL64;
    009
    010import java.math.BigDecimal;
    011
    012public class VWapT extends Ticker {
    013    private static final long serialVersionUID = 1L;
    014    BigDecimal minPrice;
    015    BigDecimal maxPrice;
    016    BigDecimal avgPrice = ZERO;
    017    BigDecimal vwap = ZERO;
    018
    019    transient BigDecimal totalVolume = ZERO;
    020    transient int count;
    021
    022    VWapT(Trade trade) {
    023        super(trade);
    024    }
    025
    026    void newTrade(Trade trade) {
    027
    028        BigDecimal price = trade.price;
    029        BigDecimal volume = trade.volume;
    030
    031        if (ZERO.equals(volume))
    032            return;
    033
    034        minPrice = (minPrice == null) ? price : minPrice.min(price);
    035        maxPrice = (maxPrice == null) ? price : maxPrice.max(price);
    036        avgPrice = avgPrice.add(price, DECIMAL64);
    037        totalVolume = totalVolume.add(volume, DECIMAL64);
    038        vwap = vwap.add(price.multiply(volume, DECIMAL64), DECIMAL64);
    039        count++;
    040    }
    041
    042    VWapT complete() {
    043        if (count == 0)
    044            return null;
    045        vwap = vwap.divide(totalVolume, DECIMAL64);
    046        avgPrice = avgPrice.divide(new BigDecimal(count), DECIMAL64);
    047        return this;
    048    }
    049
    050    public String toString() {
    051        return "VWAP: " + getTicker() + " vwap=" + vwap + " avgPrice="
    052                + avgPrice + " minPrice=" + minPrice + " maxPrice=" + maxPrice;
    053    }
    054}