robust trading quotes management for nseindia. the quote data is inmemory and order should be evaluated and executed and monitoring of stoploss and target.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's design a robust in-memory trading quotes management system for NSEIndia, focusing on order evaluation, execution (simulated), and stop-loss/target monitoring.
Core Requirements:
In-Memory Quote Data: Fast access to the latest tick data.
Order Evaluation: Decide if an order can be triggered based on current quotes.
Order Execution (Simulated): Mark orders as executed, update positions.
Stop-Loss (SL) Monitoring: Trigger SL orders when price moves adversely.
Robustness: Handle concurrent operations, potential data issues, and provide clear state management.
Key Components:
QuoteManager:
Stores the latest quotes for all subscribed instruments.
Provides methods to update and retrieve quotes.
Likely uses a ConcurrentHashMap<String, Quote> where String is the instrument symbol (e.g., "RELIANCE-EQ").
OrderManager:
Manages all active orders.
Stores orders with their status (PENDING, ACTIVE, TRIGGERED, EXECUTED, CANCELLED, REJECTED).
Handles order placement, cancellation, and modification.
Stores List<Order> or ConcurrentHashMap<String, Order> (orderId -> Order).
PositionManager:
Tracks current open positions for each instrument.
Calculates P&L (realized and unrealized).
Updates based on executed trades.
Likely uses ConcurrentHashMap<String, Position>.
TradeEngine:
The core logic unit.
Receives quote updates from QuoteManager.
Evaluates active orders in OrderManager against new quotes.
Triggers order execution (simulated).
Monitors stop-loss and target prices for active positions/orders.
ExecutionService (Simulated):
Simulates order fills. For simplicity, we can assume market orders fill at LTP, and limit orders fill if the market price crosses the limit price.
Updates order status to EXECUTED.
Notifies PositionManager to update positions.
Logs trades.
NotificationService:
(Optional but good) Sends alerts for executed orders, SL/TP hits, errors.
Data Structures:
java
Core Logic Implementation (Conceptual):
1. QuoteManager
java
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
class QuoteManager {
private final Map<String, Quote> latestQuotes = new ConcurrentHashMap<>();
private final TradeEngine tradeEngine; // Dependency
public QuoteManager(TradeEngine tradeEngine) {
this.tradeEngine = tradeEngine;
}
public void updateQuote(Quote quote) {
latestQuotes.put(quote.symbol, quote);
// Notify the trade engine about the new quote
tradeEngine.onQuoteUpdate(quote);
}
public Quote getQuote(String symbol) {
return latestQuotes.get(symbol);
}
}
2. OrderManager
java
3. PositionManager
java
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
class PositionManager {
private final Map<String, Position> positions = new ConcurrentHashMap<>();
public synchronized void updatePosition(String symbol, OrderSide side, int quantity, double price) {
Position position = positions.computeIfAbsent(symbol, Position::new);
position.update(side, quantity, price);
System.out.println("Position updated for " + symbol + ": Net Qty " + position.netQuantity + " @ Avg " + position.averagePrice);
}
public Position getPosition(String symbol) {
return positions.get(symbol);
}
public void calculateUnrealizedPnl(QuoteManager quoteManager) {
for (Map.Entry<String, Position> entry : positions.entrySet()) {
String symbol = entry.getKey();
Position position = entry.getValue();
Quote quote = quoteManager.getQuote(symbol);
if (quote != null && position.netQuantity != 0) {
position.updateUnrealizedPnl(quote.ltp);
// System.out.println("Symbol: " + symbol + " UnP&L: " + position.unrealizedPnl);
}
}
}
}
4. ExecutionService (Simulated)
java
5. TradeEngine (The heart of the system)
java
Main Application Flow (Conceptual):
java
Robustness Considerations & Enhancements:
Concurrency:
ConcurrentHashMap for quote storage.
CopyOnWriteArrayList or careful synchronization for activeOrders if modifications are less frequent than reads. For high-frequency order changes, ConcurrentHashMap<OrderId, Order> might be better.
The TradeEngine uses a single-threaded executor for quote processing. This serializes the evaluation logic per symbol update, preventing race conditions during order evaluation for a given quote.
All shared data structures (PositionManager, OrderManager) need to be thread-safe if accessed by multiple threads (e.g., UI thread placing orders, quote thread processing).
Error Handling:
Proper try-catch blocks.
Logging framework (Log4j, SLF4j).
Handle cases where quote data might be missing (e.g., no bid/ask, only LTP).
State Management:
Clear OrderStatus enum and transitions.
Ensure atomicity when updating order status and positions.
NSE Specifics:
Market Hours: Logic to accept/reject orders outside market hours.
Order Types: Support for AMO (After Market Orders), GTT (Good Till Triggered - though these are often broker-level).
Tick Sizes: Price validation against tick sizes.
Circuit Limits: Awareness of price bands.
Contract Expiry (F&O): If dealing with derivatives.
Persistence (Beyond "in-memory"):
For true robustness against crashes, you'd need to persist active orders and positions (e.g., to a database or file) and reload on startup. Event Sourcing is a good pattern here.
The request specifically says "in-memory", so this is an extension.
Idempotency:
Ensure that processing the same quote update multiple times (if it can happen due to source issues) doesn't lead to duplicate actions.
Order Matching Logic for SL/TP:
When a main order (e.g., BUY LIMIT) is filled, its associated SL and TP orders (if any, like in a bracket order) need to become active. The current handles this.
This detailed design provides a solid foundation. The implementation can be refined based on the exact features and performance requirements. The key is modularity and clear separation of concerns.
// Simplified Quote structure
class Quote {
String symbol;
double ltp; // Last Traded Price
double bidPrice;
double askPrice;
long timestamp;
// Potentially: bidQty, askQty, volume, open, high, low, close
public Quote(String symbol, double ltp, double bidPrice, double askPrice) {
this.symbol = symbol;
this.ltp = ltp;
this.bidPrice = bidPrice;
this.askPrice = askPrice;
this.timestamp = System.currentTimeMillis();
}
// Getters
}
enum OrderType { LIMIT, MARKET, STOP_LOSS_LIMIT, STOP_LOSS_MARKET, TARGET_LIMIT, TARGET_MARKET }
enum OrderSide { BUY, SELL }
enum OrderStatus { PENDING_NEW, ACTIVE, PENDING_TRIGGER, TRIGGERED, EXECUTED, CANCELLED, REJECTED, EXPIRED }
class Order {
String orderId;
String symbol;
OrderType type;
OrderSide side;
int quantity;
double price; // Limit price for LIMIT orders
double triggerPrice; // For SL/SL-M orders
Double stopLossPrice; // Price level to trigger a sell (for BUY position) or buy (for SELL position)
Double targetPrice; // Price level to trigger a sell (for BUY position) or buy (for SELL position)
OrderStatus status;
long placedTimestamp;
long executedTimestamp;
int executedQuantity;
double executedPrice; // Average executed price
// Constructor, getters, setters
public Order(String symbol, OrderType type, OrderSide side, int quantity, double price, double triggerPrice) {
this.orderId = java.util.UUID.randomUUID().toString();
this.symbol = symbol;
this.type = type;
this.side = side;
this.quantity = quantity;
this.price = price;
this.triggerPrice = triggerPrice;
this.status = OrderStatus.PENDING_NEW; // Or ACTIVE if directly placed
this.placedTimestamp = System.currentTimeMillis();
}
public void setStopLoss(double sl) { this.stopLossPrice = sl; }
public void setTarget(double tp) { this.targetPrice = tp; }
}
class Position {
String symbol;
int netQuantity; // Positive for long, negative for short
double averagePrice;
double unrealizedPnl;
double realizedPnl;
// Constructor, methods to update position, calculate P&L
public Position(String symbol) {
this.symbol = symbol;
}
public synchronized void update(OrderSide side, int quantity, double price) {
// Complex logic for calculating average price and P&L
if (side == OrderSide.BUY) {
if (netQuantity < 0 && netQuantity + quantity > 0) { // Closing short and going long
realizedPnl += (-netQuantity) * (averagePrice - price); // Profit on short
averagePrice = price; // New base for long
} else if (netQuantity < 0) { // Adding to short or reducing short
realizedPnl += Math.min(-netQuantity, quantity) * (averagePrice - price);
if (netQuantity + quantity < 0) { // still short or more short
// avg price for short doesn't change this way, it's avg sell price
}
} else { // Adding to long or new long
averagePrice = ((averagePrice * netQuantity) + (price * quantity)) / (netQuantity + quantity);
}
netQuantity += quantity;
} else { // SELL
if (netQuantity > 0 && netQuantity - quantity < 0) { // Closing long and going short
realizedPnl += (netQuantity) * (price - averagePrice); // Profit on long
averagePrice = price; // New base for short
} else if (netQuantity > 0) { // Adding to long or reducing long
realizedPnl += Math.min(netQuantity, quantity) * (price - averagePrice);
if (netQuantity - quantity > 0) { // still long or less long
// avg price for long doesn't change this way, it's avg buy price
}
} else { // Adding to short or new short
averagePrice = ((averagePrice * Math.abs(netQuantity)) + (price * quantity)) / (Math.abs(netQuantity) + quantity);
}
netQuantity -= quantity;
}
if (netQuantity == 0) averagePrice = 0;
}
public void updateUnrealizedPnl(double currentMarketPrice) {
if (netQuantity > 0) { // Long position
unrealizedPnl = (currentMarketPrice - averagePrice) * netQuantity;
} else if (netQuantity < 0) { // Short position
unrealizedPnl = (averagePrice - currentMarketPrice) * Math.abs(netQuantity);
} else {
unrealizedPnl = 0;
}
}
}
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
class OrderManager {
// Using CopyOnWriteArrayList for thread-safe iteration and modification
// For very high order volumes, consider ConcurrentHashMap<String, Order> for active orders
// and separate lists for pending (SL/TP not yet part of an open position)
private final List<Order> activeOrders = new CopyOnWriteArrayList<>();
private final List<Order> pendingBracketOrders = new CopyOnWriteArrayList<>(); // SL/TP for orders not yet executed
public synchronized String placeOrder(Order order) {
// Basic validation
if (order.quantity <= 0) {
order.status = OrderStatus.REJECTED;
return "Rejected: Invalid quantity";
}
// If it's a bracket order (main order with SL/TP), SL/TP are initially PENDING
if (order.type == OrderType.LIMIT || order.type == OrderType.MARKET) {
if (order.stopLossPrice != null || order.targetPrice != null) {
// Keep these separate until main order executes
pendingBracketOrders.add(order); // The main order itself
} else {
activeOrders.add(order);
}
order.status = OrderStatus.ACTIVE; // Or PENDING_NEW if it needs exchange ack
} else if (order.type == OrderType.STOP_LOSS_LIMIT || order.type == OrderType.STOP_LOSS_MARKET) {
order.status = OrderStatus.PENDING_TRIGGER; // Waiting for trigger price
activeOrders.add(order);
}
// Log placement
System.out.println("Order placed: " + order.orderId + " for " + order.symbol);
return order.orderId;
}
public List<Order> getActiveOrdersBySymbol(String symbol) {
return activeOrders.stream()
.filter(o -> o.symbol.equals(symbol) &&
(o.status == OrderStatus.ACTIVE || o.status == OrderStatus.PENDING_TRIGGER))
.collect(Collectors.toList());
}
public Order getOrder(String orderId) {
return activeOrders.stream().filter(o -> o.orderId.equals(orderId)).findFirst()
.orElseGet(() -> pendingBracketOrders.stream().filter(o -> o.orderId.equals(orderId)).findFirst().orElse(null));
}
public synchronized void updateOrderStatus(String orderId, OrderStatus status, double executedPrice, int executedQuantity) {
Order order = getOrder(orderId);
if (order != null) {
order.status = status;
if (status == OrderStatus.EXECUTED) {
order.executedPrice = executedPrice;
order.executedQuantity = executedQuantity; // Handle partial fills if needed
order.executedTimestamp = System.currentTimeMillis();
System.out.println("Order executed: " + orderId + " @ " + executedPrice);
// If this was a main order from a bracket, activate its SL/TP
if (pendingBracketOrders.contains(order)) {
activateBracketLegs(order);
}
}
}
}
private void activateBracketLegs(Order mainOrder) {
pendingBracketOrders.remove(mainOrder);
if (mainOrder.stopLossPrice != null) {
Order slOrder = new Order(mainOrder.symbol,
OrderType.STOP_LOSS_MARKET, // Or SL-LIMIT
mainOrder.side == OrderSide.BUY ? OrderSide.SELL : OrderSide.BUY,
mainOrder.executedQuantity,
0, // Market SL
mainOrder.stopLossPrice);
slOrder.status = OrderStatus.PENDING_TRIGGER;
activeOrders.add(slOrder);
System.out.println("Activated SL order for " + mainOrder.orderId + ": " + slOrder.orderId);
}
if (mainOrder.targetPrice != null) {
Order tpOrder = new Order(mainOrder.symbol,
OrderType.LIMIT, // Target is usually a limit order
mainOrder.side == OrderSide.BUY ? OrderSide.SELL : OrderSide.BUY,
mainOrder.executedQuantity,
mainOrder.targetPrice,
0); // No trigger for limit
tpOrder.status = OrderStatus.ACTIVE;
activeOrders.add(tpOrder);
System.out.println("Activated TP order for " + mainOrder.orderId + ": " + tpOrder.orderId);
}
}
public synchronized void cancelOrder(String orderId) {
Order order = getOrder(orderId);
if (order != null && (order.status == OrderStatus.ACTIVE || order.status == OrderStatus.PENDING_TRIGGER)) {
order.status = OrderStatus.CANCELLED;
// Potentially remove from activeOrders list if not needed for history in this list
System.out.println("Order cancelled: " + orderId);
}
}
}
class SimulatedExecutionService {
private final OrderManager orderManager;
private final PositionManager positionManager;
public SimulatedExecutionService(OrderManager orderManager, PositionManager positionManager) {
this.orderManager = orderManager;
this.positionManager = positionManager;
}
public void executeOrder(Order order, Quote currentQuote) {
double executionPrice = 0;
boolean canExecute = false;
switch (order.type) {
case MARKET:
executionPrice = (order.side == OrderSide.BUY) ? currentQuote.askPrice : currentQuote.bidPrice;
if (executionPrice == 0) executionPrice = currentQuote.ltp; // Fallback if no bid/ask
canExecute = true;
break;
case LIMIT:
if (order.side == OrderSide.BUY && currentQuote.askPrice <= order.price && currentQuote.askPrice > 0) {
executionPrice = Math.min(order.price, currentQuote.askPrice); // Buy at ask or limit, whichever is better/available
canExecute = true;
} else if (order.side == OrderSide.SELL && currentQuote.bidPrice >= order.price && currentQuote.bidPrice > 0) {
executionPrice = Math.max(order.price, currentQuote.bidPrice); // Sell at bid or limit
canExecute = true;
}
break;
case STOP_LOSS_MARKET: // Already triggered by TradeEngine
case TARGET_MARKET: // Already triggered
executionPrice = (order.side == OrderSide.BUY) ? currentQuote.askPrice : currentQuote.bidPrice;
if (executionPrice == 0) executionPrice = currentQuote.ltp;
canExecute = true;
break;
case STOP_LOSS_LIMIT: // Already triggered by TradeEngine, now acts as a LIMIT
if (order.side == OrderSide.BUY && currentQuote.askPrice <= order.price && currentQuote.askPrice > 0) {
executionPrice = Math.min(order.price, currentQuote.askPrice);
canExecute = true;
} else if (order.side == OrderSide.SELL && currentQuote.bidPrice >= order.price && currentQuote.bidPrice > 0) {
executionPrice = Math.max(order.price, currentQuote.bidPrice);
canExecute = true;
}
break;
// TARGET_LIMIT is handled like a normal LIMIT order once active
}
if (canExecute && executionPrice > 0) { // Ensure valid execution price
orderManager.updateOrderStatus(order.orderId, OrderStatus.EXECUTED, executionPrice, order.quantity);
positionManager.updatePosition(order.symbol, order.side, order.quantity, executionPrice);
// Here, if this was a main leg of a OCO (One-Cancels-Other) like SL/TP, cancel the other leg.
// This logic can be complex and depends on how you group SL/TP orders.
// For simplicity, we assume SL and TP are separate orders that become active after main order execution.
} else if (order.type == OrderType.STOP_LOSS_LIMIT && order.status == OrderStatus.TRIGGERED) {
// SL-Limit triggered but price not favorable, remains TRIGGERED (waiting for limit price)
System.out.println("SL-Limit order " + order.orderId + " triggered, waiting for limit price " + order.price);
}
}
}
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class TradeEngine {
private final OrderManager orderManager;
private final PositionManager positionManager; // For SL/TP on open positions
private final SimulatedExecutionService executionService;
private final QuoteManager quoteManager; // To get latest quotes if needed elsewhere
// Use a single-threaded executor to process quote updates sequentially to avoid race conditions on order evaluation
private final ExecutorService quoteProcessingExecutor = Executors.newSingleThreadExecutor();
public TradeEngine(OrderManager orderManager, PositionManager positionManager,
SimulatedExecutionService executionService, QuoteManager quoteManager) {
this.orderManager = orderManager;
this.positionManager = positionManager;
this.executionService = executionService;
this.quoteManager = quoteManager; // Self-reference can be tricky, ensure QuoteManager is fully constructed
}
public void onQuoteUpdate(Quote quote) {
quoteProcessingExecutor.submit(() -> processQuote(quote));
}
private void processQuote(Quote quote) {
// System.out.println("Processing quote for " + quote.symbol + ": " + quote.ltp);
List<Order> relevantOrders = orderManager.getActiveOrdersBySymbol(quote.symbol);
for (Order order : relevantOrders) {
if (order.status != OrderStatus.ACTIVE && order.status != OrderStatus.PENDING_TRIGGER && order.status != OrderStatus.TRIGGERED) {
continue; // Already processed or not ready
}
boolean trigger = false;
// 1. Evaluate Pending Triggers (SL, SL-M)
if (order.status == OrderStatus.PENDING_TRIGGER) {
if (order.type == OrderType.STOP_LOSS_LIMIT || order.type == OrderType.STOP_LOSS_MARKET) {
if (order.side == OrderSide.SELL) { // This is a SL for a long position
if (quote.ltp <= order.triggerPrice) {
trigger = true;
System.out.println("SL Triggered (SELL): " + order.orderId + " for " + quote.symbol + " at LTP " + quote.ltp);
}
} else { // OrderSide.BUY - This is a SL for a short position
if (quote.ltp >= order.triggerPrice) {
trigger = true;
System.out.println("SL Triggered (BUY): " + order.orderId + " for " + quote.symbol + " at LTP " + quote.ltp);
}
}
}
// Add other triggerable order types if any (e.g. Trailing SL)
if (trigger) {
order.status = OrderStatus.TRIGGERED;
// For SL-Market, it can be executed immediately.
// For SL-Limit, it becomes a limit order waiting for its limit price.
if (order.type == OrderType.STOP_LOSS_MARKET) {
executionService.executeOrder(order, quote);
} else if (order.type == OrderType.STOP_LOSS_LIMIT) {
// Now it's a limit order, check if it can be filled immediately
executionService.executeOrder(order, quote); // Will check limit condition
}
}
}
// 2. Evaluate Active Limit Orders / Triggered SL-Limit orders
else if (order.status == OrderStatus.ACTIVE || (order.status == OrderStatus.TRIGGERED && order.type == OrderType.STOP_LOSS_LIMIT)) {
if (order.type == OrderType.LIMIT || (order.type == OrderType.STOP_LOSS_LIMIT && order.status == OrderStatus.TRIGGERED) || order.type == OrderType.TARGET_LIMIT) {
executionService.executeOrder(order, quote); // Will check limit price conditions
}
}
// 3. Evaluate Market Orders (should ideally be handled immediately on placement if possible, or here)
else if (order.status == OrderStatus.ACTIVE && order.type == OrderType.MARKET) {
executionService.executeOrder(order, quote);
}
}
// 4. Check SL/TP based on open positions (if SL/TP are not separate orders but attached to positions)
// This is a common alternative: SL/TP are not orders but attributes of a position.
// The current design with SL/TP as separate orders is also valid and often used by brokers.
// If SL/TP are attributes of a Position object:
Position position = positionManager.getPosition(quote.symbol);
if (position != null && position.netQuantity != 0) {
// Check position-level SL/TP if they are not managed by dedicated orders
// Example:
// if (position.stopLossPrice != null &&
// ((position.netQuantity > 0 && quote.ltp <= position.stopLossPrice) ||
// (position.netQuantity < 0 && quote.ltp >= position.stopLossPrice))) {
// // Create and execute market order to close position
// }
// Similar for targetPrice.
// This part is less relevant if SL/TP orders are explicitly created as above.
}
// Update P&L for all positions with the new quote
positionManager.calculateUnrealizedPnl(quoteManager);
}
public void shutdown() {
quoteProcessingExecutor.shutdown();
try {
if (!quoteProcessingExecutor.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) {
quoteProcessingExecutor.shutdownNow();
}
} catch (InterruptedException e) {
quoteProcessingExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
public class TradingSystem {
public static void main(String[] args) throws InterruptedException {
// 1. Initialization
OrderManager orderManager = new OrderManager();
PositionManager positionManager = new PositionManager();
SimulatedExecutionService executionService = new SimulatedExecutionService(orderManager, positionManager);
// TradeEngine needs QuoteManager, and QuoteManager needs TradeEngine (for callback)
// Break circular dependency during construction:
TradeEngine tradeEngine = new TradeEngine(orderManager, positionManager, executionService, null);
QuoteManager quoteManager = new QuoteManager(tradeEngine);
// Now set the quoteManager in tradeEngine if it needs direct access (optional)
// tradeEngine.setQuoteManager(quoteManager); // If TradeEngine needs to access QuoteManager directly
System.out.println("Trading System Initialized.");
// 2. Simulate User Placing Orders
// Example: Buy RELIANCE with SL and TP (Bracket Order)
Order relianceBuyOrder = new Order("RELIANCE-EQ", OrderType.LIMIT, OrderSide.BUY, 10, 2850.00, 0);
relianceBuyOrder.setStopLoss(2800.00); // SL price for the position once order executes
relianceBuyOrder.setTarget(2950.00); // TP price for the position once order executes
orderManager.placeOrder(relianceBuyOrder);
Order infySellSLOrder = new Order("INFY-EQ", OrderType.STOP_LOSS_MARKET, OrderSide.SELL, 5, 0, 1400.00);
// This SL order is for an existing long position (not shown how it was created).
// It's already an active SL order.
orderManager.placeOrder(infySellSLOrder);
// 3. Simulate Market Data Feed (Quote Updates)
// In a real system, this comes from NSE's API (e.g., WebSocket)
Thread quoteFeedThread = new Thread(() -> {
try {
quoteManager.updateQuote(new Quote("RELIANCE-EQ", 2860.00, 2859.90, 2860.00)); // LTP, Bid, Ask
Thread.sleep(100);
quoteManager.updateQuote(new Quote("INFY-EQ", 1450.00, 1449.80, 1450.00));
Thread.sleep(100);
// Reliance order might get filled
System.out.println("\n--- Tick: RELIANCE about to fill ---");
quoteManager.updateQuote(new Quote("RELIANCE-EQ", 2850.00, 2849.90, 2850.00));
Thread.sleep(200); // Allow processing
System.out.println("\n--- Tick: RELIANCE hits TP ---");
quoteManager.updateQuote(new Quote("RELIANCE-EQ", 2950.00, 2949.95, 2950.00));
Thread.sleep(200);
System.out.println("\n--- Tick: INFY hits SL ---");
quoteManager.updateQuote(new Quote("INFY-EQ", 1399.00, 1399.00, 1399.10));
Thread.sleep(200);
System.out.println("\n--- Tick: Another RELIANCE quote (after TP) ---");
quoteManager.updateQuote(new Quote("RELIANCE-EQ", 2955.00, 2954.95, 2955.00));
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
quoteFeedThread.start();
quoteFeedThread.join(); // Wait for simulation to finish
// 4. Shutdown
tradeEngine.shutdown();
System.out.println("\n--- Final Positions ---");
Position reliancePos = positionManager.getPosition("RELIANCE-EQ");
if (reliancePos != null) {
System.out.println("RELIANCE: Qty=" + reliancePos.netQuantity + " AvgP=" + reliancePos.averagePrice + " RealizedP&L=" + reliancePos.realizedPnl + " UnRealizedP&L=" + reliancePos.unrealizedPnl);
}
Position infyPos = positionManager.getPosition("INFY-EQ");
if (infyPos != null) {
System.out.println("INFY: Qty=" + infyPos.netQuantity + " AvgP=" + infyPos.averagePrice + " RealizedP&L=" + infyPos.realizedPnl + " UnRealizedP&L=" + infyPos.unrealizedPnl);
}
System.out.println("\n--- All Orders ---");
orderManager.activeOrders.forEach(o -> System.out.println(o.orderId + " " + o.symbol + " " + o.type + " " + o.side + " Q" + o.quantity + " P" + o.price + " TrigP" + o.triggerPrice + " St:" + o.status + " ExecP:" + o.executedPrice));
orderManager.pendingBracketOrders.forEach(o -> System.out.println(o.orderId + " " + o.symbol + " " + o.type + " " + o.side + " Q" + o.quantity + " P" + o.price + " TrigP" + o.triggerPrice + " St:" + o.status + " ExecP:" + o.executedPrice));
System.out.println("Trading System Shutdown.");
}
}
OrderManager.activateBracketLegs
If SL and TP are active for the same position (OCO - One Cancels Other), when one leg (e.g., TP) executes, the other leg (SL) must be automatically cancelled. This needs careful handling, possibly by linking these orders or having the TradeEngine manage such cancellations post-execution.
Partial Fills:
The current simulation assumes full fills. Real markets have partial fills. Order and Position would need to handle this (e.g., remainingQuantity).
Scalability:
For a very large number of symbols and orders, consider distributing the TradeEngine logic, perhaps sharding by symbol.
Offload P&L calculation or other non-critical tasks to separate threads/services.
Testing:
Thorough unit tests for each component.
Integration tests for the overall workflow.
Simulate various market scenarios (fast markets, gaps, etc.).