Unify simulation order execution and persist paper accounting

This commit is contained in:
Boki 2026-10-20 21:35:56 -04:00
parent 7dec0be3b4
commit 63c3856797
37 changed files with 3901 additions and 3043 deletions

View file

@ -1,6 +1,7 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { ExecutionService } from '../../services/ExecutionService';
import { ExecutionConflictError } from '../../execution/repository';
import { ExecutionService, UnsupportedExecutionError } from '../../services/ExecutionService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { OrderRequestSchema } from '../../types';
@ -16,12 +17,20 @@ export function createOrderRoutes(container: IServiceContainer): Hono {
app.post('/', async c => {
try {
const body = await c.req.json();
const orderRequest = OrderRequestSchema.parse(body);
const orderRequest = OrderRequestSchema.extend({
clientOrderId: z.string().min(1).max(256),
}).parse(body);
const result = await executionService.submitOrder(orderRequest);
return c.json(result, 201);
} catch (error) {
if (error instanceof ExecutionConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof UnsupportedExecutionError) {
return c.json({ error: error.message }, 503);
}
if (error instanceof z.ZodError) {
return c.json(
{
@ -92,7 +101,9 @@ export function createOrderRoutes(container: IServiceContainer): Hono {
app.post('/batch', async c => {
try {
const body = await c.req.json();
const orders = z.array(OrderRequestSchema).parse(body);
const orders = z
.array(OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }))
.parse(body);
const results = await Promise.allSettled(
orders.map(order => executionService.submitOrder(order))

View file

@ -1,5 +1,6 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import type { OrchestratorServices as IServiceContainer } from '../../types';
@ -9,13 +10,21 @@ const SymbolSchema = z.object({
export function createPositionRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const execution = defined(container.custom?.ExecutionService);
const positionsFromLedger = async () =>
(await execution.getPositions()).map(p => ({
symbol: p.symbol,
quantity: p.quantity,
average_price: p.averagePrice,
realized_pnl: p.realizedPnl,
unrealized_pnl: p.unrealizedPnl,
}));
const modeManager = container.custom?.ModeManager as ModeManager;
// Get all positions
app.get('/', async c => {
try {
const tradingEngine = modeManager.getTradingEngine();
const positions = JSON.parse(tradingEngine.getAllPositions());
const positions = await positionsFromLedger();
return c.json({
mode: modeManager.getCurrentMode(),
@ -35,8 +44,7 @@ export function createPositionRoutes(container: IServiceContainer): Hono {
// Get open positions only
app.get('/open', async c => {
try {
const tradingEngine = modeManager.getTradingEngine();
const positions = JSON.parse(tradingEngine.getOpenPositions());
const positions = (await positionsFromLedger()).filter(p => p.quantity !== 0);
return c.json({
mode: modeManager.getCurrentMode(),
@ -57,10 +65,7 @@ export function createPositionRoutes(container: IServiceContainer): Hono {
app.get('/:symbol', async c => {
try {
const { symbol } = SymbolSchema.parse(c.req.param());
const tradingEngine = modeManager.getTradingEngine();
const positionJson = tradingEngine.getPosition(symbol);
const position = positionJson ? JSON.parse(positionJson) : null;
const position = (await positionsFromLedger()).find(p => p.symbol === symbol);
if (position) {
return c.json({
@ -90,8 +95,9 @@ export function createPositionRoutes(container: IServiceContainer): Hono {
// Get P&L summary
app.get('/pnl/summary', async c => {
try {
const tradingEngine = modeManager.getTradingEngine();
const [realizedPnl = 0, unrealizedPnl = 0] = tradingEngine.getTotalPnl();
const account = await execution.getAccount();
const realizedPnl = account.realizedPnl,
unrealizedPnl = account.unrealizedPnl;
return c.json({
mode: modeManager.getCurrentMode(),
@ -116,8 +122,13 @@ export function createPositionRoutes(container: IServiceContainer): Hono {
// Get risk metrics
app.get('/risk/metrics', async c => {
try {
const tradingEngine = modeManager.getTradingEngine();
const metrics = JSON.parse(tradingEngine.getRiskMetrics());
const account = await execution.getAccount();
const metrics = {
gross_exposure: account.grossExposure,
daily_pnl: account.dailyPnl,
position_count: Object.values(account.positions).filter(p => p.quantity !== 0).length,
limits: account.limits,
};
return c.json({
mode: modeManager.getCurrentMode(),

View file

@ -4,7 +4,7 @@ import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import { ExecutionService } from '../../services/ExecutionService';
import { MarketDataService } from '../../services/MarketDataService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { OrderRequestSchema, type OrchestratorServices as IServiceContainer } from '../../types';
const SubscribeSchema = z.object({
symbols: z.array(z.string()),
@ -102,7 +102,9 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo
// Handle order submission via WebSocket
socket.on('submitOrder', async (order, callback?: Function) => {
try {
const result = await executionService.submitOrder(order);
const result = await executionService.submitOrder(
OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }).parse(order)
);
if (callback) {
callback({ success: true, result });
}
@ -120,8 +122,7 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo
// Handle position queries
socket.on('getPositions', async (callback?: Function) => {
try {
const tradingEngine = modeManager.getTradingEngine();
const positions = JSON.parse(tradingEngine.getAllPositions());
const positions = await executionService.getPositions();
if (callback) {
callback({ success: true, positions });
@ -165,10 +166,12 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo
});
// Forward market data to subscribed clients
marketDataService.on('marketData', data => {
for (const [clientId, subscriptions] of clientSubscriptions) {
if (subscriptions.has(data.data.symbol)) {
io.to(clientId).emit('marketData', data);
marketDataService.on('marketDataBatch', batch => {
for (const data of batch) {
for (const [clientId, subscriptions] of clientSubscriptions) {
if (subscriptions.has(data.data.symbol)) {
io.to(clientId).emit('marketData', data);
}
}
}
});