TradeSimulator.java
01 package examples.webapp.pubsub.stock;
02 
03 import java.text.NumberFormat;
04 import java.util.Random;
05 
06 import org.json.JSONObject;
07 
08 public class TradeSimulator {
09   public void simulateTrade(Stock stock) {
10     Random random = new Random();
11     double baseGaussian = random.nextGaussian();
12     double gaussian = (baseGaussian*0.2 0.8*random.nextGaussian())/300;
13     double change = 0;
14     if(stock.getPrice()>=stock.getOpenPrice()) {
15       change = stock.getPrice() * gaussian;
16     else {
17       change = stock.getPrice() * gaussian / (1-gaussian);
18     }
19     double percent = (stock.getPrice() - stock.getOpenPrice() + change100 / stock.getOpenPrice();
20     if (change>&& percent>&& Math.random()<percent/10 
21       || change<&& percent<&& Math.random()<percent/-10) {
22       stock.setPrice(stock.getPrice() - change);
23     else {
24       stock.setPrice(stock.getPrice() + change);
25     }
26     stock.setQuantity(Math.round(Math.random() 10000));
27     stock.setTimestamp(System.currentTimeMillis());
28   }
29 }
30 
31 class Stock {
32   
33   private String symbol;
34   private double openPrice;
35   private double price;
36   private long quantity;
37   private long timestamp;
38   
39   Stock(String symbol) {
40     this.symbol = symbol;
41     this.openPrice = Math.random()*70 10;
42     this.price = this.openPrice;
43     this.quantity = 0;
44   }
45   public double getOpenPrice() {
46     return openPrice;
47   }
48   public void setOpenPrice(double openPrice) {
49     this.openPrice = openPrice;
50   }
51   public double getPrice() {
52     return price;
53   }
54   public void setPrice(double price) {
55     this.price = price;
56   }
57   public long getQuantity() {
58     return quantity;
59   }
60   public void setQuantity(long quantity) {
61     this.quantity = quantity;
62   }
63   public String getSymbol() {
64     return symbol;
65   }
66   public void setSymbol(String symbol) {
67     this.symbol = symbol;
68   }
69   public long getTimestamp() {
70     return timestamp;
71   }
72   public void setTimestamp(long timestamp) {
73     this.timestamp = timestamp;
74   }
75   public JSONObject toJSONObject() {
76     JSONObject obj = new JSONObject();
77     obj.put("symbol", symbol);
78     obj.put("openPrice", formatPrice(openPrice));
79     obj.put("price", formatPrice(price));
80     obj.put("quantity", quantity);
81     obj.put("timestamp", timestamp);
82     return obj;
83   }
84   public String getFormatedPrice() {
85     return formatPrice(price);
86   }
87   public String getFormatedOpenPrice() {
88     return formatPrice(openPrice);
89   }
90   private String formatPrice(double price) {
91     NumberFormat formater = NumberFormat.getNumberInstance();
92     formater.setMinimumFractionDigits(2);
93     formater.setMaximumFractionDigits(2);
94     return formater.format(price);
95   }
96 }