refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -1,67 +0,0 @@
import { Hono } from 'hono';
import { z } from 'zod';
import {
correlationRequestSchema,
dateRangeSchema,
optimizationRequestSchema,
predictionRequestSchema,
} from '../../contracts/analytics';
import { AnalyticsServiceError } from '../../services/analytics-error';
import type { OrchestratorServices } from '../../types';
export function createAnalyticsRoutes(container: OrchestratorServices): Hono {
const app = new Hono();
const service = () => {
const analytics = container.custom?.AnalyticsService;
if (!analytics) {
throw new AnalyticsServiceError('unavailable');
}
return analytics;
};
app.onError((error, c) => {
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid analytics request', details: error.issues }, 400);
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid JSON body' }, 400);
}
if (error instanceof AnalyticsServiceError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
container.logger.error('Analytics request failed', { name: error.name });
return c.json({ error: 'Analytics request failed' }, 500);
});
app.get('/performance/:portfolioId', async c => {
const range = dateRangeSchema.parse({
startDate: c.req.query('start_date'),
endDate: c.req.query('end_date'),
});
return c.json(
await service().getPerformanceMetrics(
c.req.param('portfolioId'),
new Date(range.startDate),
new Date(range.endDate)
)
);
});
app.post('/optimize', async c => {
return c.json(
await service().optimizePortfolio(optimizationRequestSchema.parse(await c.req.json()))
);
});
app.get('/risk/:portfolioId', async c =>
c.json(await service().getRiskMetrics(c.req.param('portfolioId')))
);
app.get('/regime', async c =>
c.json({ regime: await service().detectMarketRegime(), timestamp: new Date().toISOString() })
);
app.post('/correlation', async c => {
const { symbols } = correlationRequestSchema.parse(await c.req.json());
return c.json({ symbols, matrix: await service().calculateCorrelationMatrix(symbols) });
});
app.post('/predict', async c => {
const { modelId, features } = predictionRequestSchema.parse(await c.req.json());
return c.json(await service().predictWithModel(modelId, features));
});
return app;
}

View file

@ -1,140 +0,0 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { ExecutionConflictError } from '../../execution/repository';
import { ExecutionService, UnsupportedExecutionError } from '../../services/ExecutionService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { OrderRequestSchema } from '../../types';
const OrderIdSchema = z.object({
orderId: z.string(),
});
export function createOrderRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const executionService = container.custom?.ExecutionService as ExecutionService;
// Submit new order
app.post('/', async c => {
try {
const body = await c.req.json();
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(
{
error: 'Invalid order request',
details: error.errors,
},
400
);
}
container.logger.error('Error submitting order:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to submit order',
},
500
);
}
});
// Cancel order
app.delete('/:orderId', async c => {
try {
const { orderId } = OrderIdSchema.parse(c.req.param());
const success = await executionService.cancelOrder(orderId);
if (success) {
return c.json({ message: 'Order cancelled successfully' });
} else {
return c.json({ error: 'Order not found or already filled' }, 404);
}
} catch (error) {
container.logger.error('Error cancelling order:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to cancel order',
},
500
);
}
});
// Get order status
app.get('/:orderId', async c => {
try {
const { orderId } = OrderIdSchema.parse(c.req.param());
const status = await executionService.getOrderStatus(orderId);
if (status) {
return c.json(status);
} else {
return c.json({ error: 'Order not found' }, 404);
}
} catch (error) {
container.logger.error('Error getting order status:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get order status',
},
500
);
}
});
// Batch order submission
app.post('/batch', async c => {
try {
const body = await c.req.json();
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))
);
const response = results.map((result, index) => ({
order: orders[index],
result: result.status === 'fulfilled' ? result.value : { error: result.reason },
}));
return c.json(response, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid batch order request',
details: error.errors,
},
400
);
}
container.logger.error('Error submitting batch orders:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to submit batch orders',
},
500
);
}
});
return app;
}

View file

@ -4,10 +4,10 @@ import {
paperActivationSchema,
paperHaltSchema,
PaperRuntimeError,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
} from '@stock-bot/stock-config/paper-runtime';
import { ExecutionConflictError } from '../../execution/canonical-paper';
import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
export function createPaperDeploymentHostRoutes(

View file

@ -1,6 +1,6 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { getCredentialHttpPrincipal } from '@stock-bot/di/http-security';
import {
paperActivationSchema,
paperConnectionSchema,
@ -8,10 +8,10 @@ import {
paperHaltSchema,
PaperRuntimeError,
type PaperReadiness,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
} from '@stock-bot/stock-config/paper-runtime';
import { ExecutionConflictError } from '../../execution/canonical-paper';
import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
import type { OrchestratorServices } from '../../types';

View file

@ -1,150 +0,0 @@
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';
const SymbolSchema = z.object({
symbol: z.string(),
});
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 positions = await positionsFromLedger();
return c.json({
mode: modeManager.getCurrentMode(),
positions,
});
} catch (error) {
container.logger.error('Error getting positions:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get positions',
},
500
);
}
});
// Get open positions only
app.get('/open', async c => {
try {
const positions = (await positionsFromLedger()).filter(p => p.quantity !== 0);
return c.json({
mode: modeManager.getCurrentMode(),
positions,
});
} catch (error) {
container.logger.error('Error getting open positions:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get open positions',
},
500
);
}
});
// Get position for specific symbol
app.get('/:symbol', async c => {
try {
const { symbol } = SymbolSchema.parse(c.req.param());
const position = (await positionsFromLedger()).find(p => p.symbol === symbol);
if (position) {
return c.json({
mode: modeManager.getCurrentMode(),
position,
});
} else {
return c.json(
{
error: 'Position not found',
symbol,
},
404
);
}
} catch (error) {
container.logger.error('Error getting position:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get position',
},
500
);
}
});
// Get P&L summary
app.get('/pnl/summary', async c => {
try {
const account = await execution.getAccount();
const realizedPnl = account.realizedPnl,
unrealizedPnl = account.unrealizedPnl;
return c.json({
mode: modeManager.getCurrentMode(),
pnl: {
realized: realizedPnl,
unrealized: unrealizedPnl,
total: realizedPnl + unrealizedPnl,
},
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error getting P&L:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get P&L',
},
500
);
}
});
// Get risk metrics
app.get('/risk/metrics', async c => {
try {
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(),
risk: metrics,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error getting risk metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get risk metrics',
},
500
);
}
});
return app;
}

View file

@ -1,198 +0,0 @@
import { Socket, Server as SocketIOServer } from 'socket.io';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import { ExecutionService } from '../../services/ExecutionService';
import { MarketDataService } from '../../services/MarketDataService';
import { OrderRequestSchema, type OrchestratorServices as IServiceContainer } from '../../types';
const SubscribeSchema = z.object({
symbols: z.array(z.string()),
dataTypes: z.array(z.enum(['quote', 'trade', 'bar'])).optional(),
});
const UnsubscribeSchema = z.object({
symbols: z.array(z.string()),
});
export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceContainer): void {
const marketDataService = container.custom?.MarketDataService as MarketDataService;
const executionService = container.custom?.ExecutionService as ExecutionService;
const modeManager = container.custom?.ModeManager as ModeManager;
// Track client subscriptions
const clientSubscriptions = new Map<string, Set<string>>();
io.on('connection', (socket: Socket) => {
container.logger.info(`WebSocket client connected: ${socket.id}`);
clientSubscriptions.set(socket.id, new Set());
// Send initial connection info
socket.emit('connected', {
mode: modeManager.getCurrentMode(),
timestamp: new Date().toISOString(),
});
// Handle market data subscriptions
socket.on('subscribe', async (data, callback?: Function) => {
try {
const { symbols, dataTypes: _dataTypes } = SubscribeSchema.parse(data);
const subscriptions = defined(clientSubscriptions.get(socket.id));
for (const symbol of symbols) {
await marketDataService.subscribeToSymbol(symbol);
subscriptions.add(symbol);
}
container.logger.debug(`Client ${socket.id} subscribed to: ${symbols.join(', ')}`);
if (callback) {
callback({ success: true, symbols });
}
} catch (error) {
container.logger.error('Subscription error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Subscription failed',
});
}
}
});
// Handle unsubscribe
socket.on('unsubscribe', async (data, callback?: Function) => {
try {
const { symbols } = UnsubscribeSchema.parse(data);
const subscriptions = defined(clientSubscriptions.get(socket.id));
for (const symbol of symbols) {
subscriptions.delete(symbol);
// Check if any other clients are subscribed
let othersSubscribed = false;
for (const [clientId, subs] of clientSubscriptions) {
if (clientId !== socket.id && subs.has(symbol)) {
othersSubscribed = true;
break;
}
}
if (!othersSubscribed) {
await marketDataService.unsubscribeFromSymbol(symbol);
}
}
container.logger.debug(`Client ${socket.id} unsubscribed from: ${symbols.join(', ')}`);
if (callback) {
callback({ success: true, symbols });
}
} catch (error) {
container.logger.error('Unsubscribe error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Unsubscribe failed',
});
}
}
});
// Handle order submission via WebSocket
socket.on('submitOrder', async (order, callback?: Function) => {
try {
const result = await executionService.submitOrder(
OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }).parse(order)
);
if (callback) {
callback({ success: true, result });
}
} catch (error) {
container.logger.error('Order submission error:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Order submission failed',
});
}
}
});
// Handle position queries
socket.on('getPositions', async (callback?: Function) => {
try {
const positions = await executionService.getPositions();
if (callback) {
callback({ success: true, positions });
}
} catch (error) {
container.logger.error('Error getting positions:', error);
if (callback) {
callback({
success: false,
error: error instanceof Error ? error.message : 'Failed to get positions',
});
}
}
});
// Handle disconnection
socket.on('disconnect', async () => {
container.logger.info(`WebSocket client disconnected: ${socket.id}`);
// Unsubscribe from all symbols for this client
const subscriptions = clientSubscriptions.get(socket.id);
if (subscriptions) {
for (const symbol of subscriptions) {
// Check if any other clients are subscribed
let othersSubscribed = false;
for (const [clientId, subs] of clientSubscriptions) {
if (clientId !== socket.id && subs.has(symbol)) {
othersSubscribed = true;
break;
}
}
if (!othersSubscribed) {
await marketDataService.unsubscribeFromSymbol(symbol);
}
}
}
clientSubscriptions.delete(socket.id);
});
});
// Forward market data to subscribed clients
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);
}
}
}
});
// Forward order updates to all clients
executionService.on('orderUpdate', update => {
io.emit('orderUpdate', update);
});
// Forward fills to all clients
executionService.on('fill', fill => {
io.emit('fill', fill);
});
// Mode change notifications
modeManager.on('modeChanged', config => {
io.emit('modeChanged', {
mode: config.mode,
timestamp: new Date().toISOString(),
});
});
container.logger.info('WebSocket handlers initialized');
}