-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock.java
More file actions
420 lines (373 loc) · 15.3 KB
/
stock.java
File metadata and controls
420 lines (373 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Code for Stock Trading Simuation in Java
// Authored by: Anshuman Sinha
import java.util.*;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
class Stock {
String stockName;
double price;
List<Double> priceHistory = new ArrayList<>();
public Stock(String stockName, double price) {
this.stockName = stockName;
this.price = price;
priceHistory.add(price);
}
public void updatePrice(double newPrice) {
this.price = newPrice;
priceHistory.add(newPrice);
}
public double calculateSMA(int period) {
if (priceHistory.size() < period) return -1; // Not enough data
double sum = 0;
for (int i = priceHistory.size() - period; i < priceHistory.size(); i++) {
sum += priceHistory.get(i);
}
return sum / period;
}
public double calculateEMA(int period) {
if (priceHistory.size() < period) return -1; // Not enough data
double k = 2.0 / (period + 1);
double ema = priceHistory.get(priceHistory.size() - period); // Starting point for EMA
for (int i = priceHistory.size() - period + 1; i < priceHistory.size(); i++) {
ema = priceHistory.get(i) * k + ema * (1 - k);
}
return ema;
}
}
class User {
String username;
String password;
double balance;
double marginBalance;
double debt;
Map<String, Integer> portfolio = new HashMap<>();
List<String> transactionHistory = new ArrayList<>();
public User(String username, String password, double balance) {
this.username = username;
this.password = password;
this.balance = balance;
this.marginBalance = balance * 2; // 2x margin
this.debt = 0;
}
public void addToPortfolio(String stockSymbol, int quantity) {
portfolio.put(stockSymbol, portfolio.getOrDefault(stockSymbol, 0) + quantity);
}
public void removeFromPortfolio(String stockSymbol, int quantity) {
if (portfolio.containsKey(stockSymbol)) {
int currentQuantity = portfolio.get(stockSymbol);
if (currentQuantity > quantity) {
portfolio.put(stockSymbol, currentQuantity - quantity);
} else {
portfolio.remove(stockSymbol);
}
}
}
}
class Order {
String stockSymbol;
double price;
int quantity;
String orderType; // "buy", "sell", "short", "cover", "limit"
public Order(String stockSymbol, double price, int quantity, String orderType) {
this.stockSymbol = stockSymbol;
this.price = price;
this.quantity = quantity;
this.orderType = orderType;
}
}
public class AdvancedStockTradingSystem {
static Scanner scanner = new Scanner(System.in);
static Map<String, Stock> market = new ConcurrentHashMap<>();
static Map<String, User> users = new HashMap<>();
static PriorityQueue<Order> buyOrders = new PriorityQueue<>(Comparator.comparingDouble(o -> -o.price)); // Max heap
static PriorityQueue<Order> sellOrders = new PriorityQueue<>(Comparator.comparingDouble(o -> o.price)); // Min heap
static List<Order> stopLossOrders = new ArrayList<>();
static List<Order> takeProfitOrders = new ArrayList<>();
static List<String> newsFeed = new ArrayList<>();
static Timer marketTimer = new Timer();
public static void main(String[] args) {
initializeMarket();
startMarketSimulation();
while (true) {
System.out.println("1. Register\n2. Login\n3. Exit");
int choice = scanner.nextInt();
if (choice == 1) {
registerUser();
} else if (choice == 2) {
User user = loginUser();
if (user != null) {
displayUserMenu(user);
}
} else if (choice == 3) {
System.out.println("Exiting...");
break;
}
}
}
static void initializeMarket() {
market.put("AAPL", new Stock("AAPL", 150));
market.put("TSLA", new Stock("TSLA", 800));
market.put("GOOG", new Stock("GOOG", 2800));
market.put("MSFT", new Stock("MSFT", 300));
// Initialize some news
newsFeed.add("Apple announces new iPhone.");
newsFeed.add("Tesla achieves record sales.");
newsFeed.add("Google acquires AI startup.");
newsFeed.add("Microsoft launches new Surface product.");
}
static void registerUser() {
System.out.println("Enter username:");
String username = scanner.next();
System.out.println("Enter password:");
String password = scanner.next();
users.put(username, new User(username, password, 10000)); // Initial balance of $10,000
System.out.println("User registered successfully!");
}
static User loginUser() {
System.out.println("Enter username:");
String username = scanner.next();
System.out.println("Enter password:");
String password = scanner.next();
if (users.containsKey(username) && users.get(username).password.equals(password)) {
System.out.println("Login successful!");
return users.get(username);
} else {
System.out.println("Invalid username or password.");
return null;
}
}
static void displayUserMenu(User user) {
while (true) {
System.out.println("\n1. View Portfolio\n2. View Market\n3. Buy Stock\n4. Sell Stock\n5. Add Funds");
System.out.println("6. Margin Trading\n7. Short Selling\n8. Place Limit Order\n9. Market News");
System.out.println("10. Market Analytics\n11. Transaction History\n12. View Technical Indicators\n13. Logout");
int choice = scanner.nextInt();
switch (choice) {
case 1:
viewPortfolio(user);
break;
case 2:
viewMarket();
break;
case 3:
buyStock(user);
break;
case 4:
sellStock(user);
break;
case 5:
addFunds(user);
break;
case 6:
marginTrading(user);
break;
case 7:
shortSelling(user);
break;
case 8:
placeLimitOrder(user);
break;
case 9:
displayMarketNews();
break;
case 10:
displayMarketAnalytics();
break;
case 11:
viewTransactionHistory(user);
break;
case 12:
viewTechnicalIndicators(user);
break;
case 13:
System.out.println("Logging out...");
return;
}
}
}
// New Functionalities
static void marginTrading(User user) {
System.out.println("\nEnter stock symbol to buy on margin:");
String stockSymbol = scanner.next();
System.out.println("Enter quantity:");
int quantity = scanner.nextInt();
Stock stock = market.get(stockSymbol);
if (stock != null) {
double totalPrice = stock.price * quantity;
if (user.marginBalance >= totalPrice) {
user.marginBalance -= totalPrice;
user.debt += totalPrice;
user.addToPortfolio(stockSymbol, quantity);
System.out.println("Bought " + quantity + " shares of " + stockSymbol + " on margin for $" + totalPrice);
} else {
System.out.println("Insufficient margin balance.");
}
} else {
System.out.println("Stock not found.");
}
}
static void shortSelling(User user) {
System.out.println("\nEnter stock symbol to short sell:");
String stockSymbol = scanner.next();
System.out.println("Enter quantity:");
int quantity = scanner.nextInt();
Stock stock = market.get(stockSymbol);
if (stock != null) {
double totalPrice = stock.price * quantity;
user.balance += totalPrice; // User receives money for selling
user.debt += totalPrice; // User now has debt (needs to cover later)
System.out.println("Short sold " + quantity + " shares of " + stockSymbol + " for $" + totalPrice);
} else {
System.out.println("Stock not found.");
}
}
static void placeLimitOrder(User user) {
System.out.println("\nEnter stock symbol:");
String stockSymbol = scanner.next();
System.out.println("Enter quantity:");
int quantity = scanner.nextInt();
System.out.println("Enter limit price:");
double limitPrice = scanner.nextDouble();
System.out.println("Enter order type (buy/sell):");
String orderType = scanner.next();
Order order = new Order(stockSymbol, limitPrice, quantity, orderType);
if (orderType.equals("buy")) {
buyOrders.add(order);
} else if (orderType.equals("sell")) {
sellOrders.add(order);
}
System.out.println("Limit order placed for " + quantity + " shares of " + stockSymbol + " at $" + limitPrice);
}
static void displayMarketNews() {
System.out.println("\nMarket News:");
for (String news : newsFeed) {
System.out.println(news);
}
}
static void displayMarketAnalytics() {
Stock topPerformer = null;
Stock worstPerformer = null;
for (Stock stock : market.values()) {
if (topPerformer == null || stock.price > topPerformer.price) {
topPerformer = stock;
}
if (worstPerformer == null || stock.price < worstPerformer.price) {
worstPerformer = stock;
}
}
System.out.println("\nMarket Analytics:");
System.out.println("Top Performer: " + topPerformer.stockName + " at $" + topPerformer.price);
System.out.println("Worst Performer: " + worstPerformer.stockName + " at $" + worstPerformer.price);
}
static void viewTransactionHistory(User user) {
System.out.println("\nTransaction History:");
for (String transaction : user.transactionHistory) {
System.out.println(transaction);
}
}
static void viewTechnicalIndicators(User user) {
System.out.println("\nEnter stock symbol:");
String stockSymbol = scanner.next();
Stock stock = market.get(stockSymbol);
if (stock != null) {
System.out.println("Enter period for SMA:");
int smaPeriod = scanner.nextInt();
double sma = stock.calculateSMA(smaPeriod);
System.out.println("Simple Moving Average (SMA) for " + stockSymbol + " over " + smaPeriod + " periods: $" + sma);
System.out.println("Enter period for EMA:");
int emaPeriod = scanner.nextInt();
double ema = stock.calculateEMA(emaPeriod);
System.out.println("Exponential Moving Average (EMA) for " + stockSymbol + " over " + emaPeriod + " periods: $" + ema);
} else {
System.out.println("Stock not found.");
}
}
// Existing Functionalities
static void viewPortfolio(User user) {
System.out.println("\nPortfolio:");
double totalValue = 0;
for (Map.Entry<String, Integer> entry : user.portfolio.entrySet()) {
String stockSymbol = entry.getKey();
int quantity = entry.getValue();
Stock stock = market.get(stockSymbol);
totalValue += stock.price * quantity;
System.out.println(stockSymbol + ": " + quantity + " shares at $" + stock.price);
}
System.out.println("Total Portfolio Value: $" + totalValue);
}
static void viewMarket() {
System.out.println("\nMarket:");
for (Stock stock : market.values()) {
System.out.println(stock.stockName + ": $" + stock.price);
}
}
static void buyStock(User user) {
System.out.println("\nEnter stock symbol to buy:");
String stockSymbol = scanner.next();
System.out.println("Enter quantity:");
int quantity = scanner.nextInt();
Stock stock = market.get(stockSymbol);
if (stock != null) {
double totalPrice = stock.price * quantity;
if (user.balance >= totalPrice) {
user.balance -= totalPrice;
user.addToPortfolio(stockSymbol, quantity);
user.transactionHistory.add("Bought " + quantity + " shares of " + stockSymbol + " at $" + stock.price);
System.out.println("Bought " + quantity + " shares of " + stockSymbol + " for $" + totalPrice);
} else {
System.out.println("Insufficient balance.");
}
} else {
System.out.println("Stock not found.");
}
}
static void sellStock(User user) {
System.out.println("\nEnter stock symbol to sell:");
String stockSymbol = scanner.next();
System.out.println("Enter quantity:");
int quantity = scanner.nextInt();
if (user.portfolio.containsKey(stockSymbol) && user.portfolio.get(stockSymbol) >= quantity) {
Stock stock = market.get(stockSymbol);
double totalPrice = stock.price * quantity;
user.balance += totalPrice;
user.removeFromPortfolio(stockSymbol, quantity);
user.transactionHistory.add("Sold " + quantity + " shares of " + stockSymbol + " at $" + stock.price);
System.out.println("Sold " + quantity + " shares of " + stockSymbol + " for $" + totalPrice);
} else {
System.out.println("Insufficient shares in portfolio.");
}
}
static void addFunds(User user) {
System.out.println("\nEnter amount to add:");
double amount = scanner.nextDouble();
user.balance += amount;
System.out.println("Added $" + amount + " to your account. New balance: $" + user.balance);
}
// Order matching engine and market simulator
static void matchOrders() {
while (!buyOrders.isEmpty() && !sellOrders.isEmpty()) {
Order buyOrder = buyOrders.peek();
Order sellOrder = sellOrders.peek();
if (buyOrder.price >= sellOrder.price) {
int tradedQuantity = Math.min(buyOrder.quantity, sellOrder.quantity);
System.out.println("Matched order for " + tradedQuantity + " shares at $" + sellOrder.price);
buyOrders.poll();
sellOrders.poll();
} else {
break;
}
}
}
static void startMarketSimulation() {
TimerTask task = new TimerTask() {
public void run() {
Random rand = new Random();
for (Stock stock : market.values()) {
double change = rand.nextDouble() * 10 - 5; // Simulate price changes between -5 to +5
stock.updatePrice(stock.price + change);
}
}
};
marketTimer.scheduleAtFixedRate(task, 0, 5000); // Update every 5 seconds
}
}