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:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,172 +0,0 @@
|
|||
import {
|
||||
factorStatistics,
|
||||
finite,
|
||||
formatStatistic,
|
||||
performanceAnalysis,
|
||||
type EquityPoint,
|
||||
} from '@stock-bot/calculations/analytics';
|
||||
|
||||
export interface Trade {
|
||||
entryTime: Date;
|
||||
exitTime: Date;
|
||||
symbol: string;
|
||||
side: 'long' | 'short';
|
||||
entryPrice: number;
|
||||
exitPrice: number;
|
||||
quantity: number;
|
||||
commission: number;
|
||||
pnl: number;
|
||||
returnPct: number;
|
||||
holdingPeriod: number;
|
||||
mae: number;
|
||||
mfe: number;
|
||||
}
|
||||
type Analysis = ReturnType<typeof performanceAnalysis>;
|
||||
type CoreMetrics = Analysis['metrics'];
|
||||
/** Legacy report facade: percentage fields remain percentage points; the pure core uses fractions. */
|
||||
export type PerformanceMetrics = CoreMetrics;
|
||||
export type FactorAttribution = ReturnType<typeof factorStatistics>;
|
||||
export interface DrawdownAnalysis {
|
||||
maxDrawdown: number;
|
||||
maxDrawdownDuration: number;
|
||||
currentDrawdown: number;
|
||||
drawdownPeriods: {
|
||||
start: Date;
|
||||
end: Date;
|
||||
depth: number;
|
||||
duration: number;
|
||||
recovery: number | null;
|
||||
}[];
|
||||
underwaterCurve: { date: Date; drawdown: number }[];
|
||||
}
|
||||
|
||||
const percentageFields = [
|
||||
'totalReturn',
|
||||
'annualizedReturn',
|
||||
'cagr',
|
||||
'volatility',
|
||||
'downVolatility',
|
||||
'var95',
|
||||
'cvar95',
|
||||
'winRate',
|
||||
] as const;
|
||||
|
||||
/** Compatibility facade over pure, shared math; observations are detached and cache invalidation is explicit. */
|
||||
export class PerformanceAnalyzer {
|
||||
private equityCurve: EquityPoint[] = [];
|
||||
private trades: Trade[] = [];
|
||||
private benchmarkReturns?: number[];
|
||||
private analysis?: Analysis;
|
||||
constructor(private readonly initialCapital = 100000) {
|
||||
if (finite(initialCapital) <= 0) {
|
||||
throw new Error('Initial capital must be positive');
|
||||
}
|
||||
}
|
||||
addEquityPoint(date: Date, value: number): void {
|
||||
const timestamp = finite(date.getTime());
|
||||
finite(value);
|
||||
const last = this.equityCurve[this.equityCurve.length - 1];
|
||||
if (last && timestamp < last.timestamp) {
|
||||
throw new Error('Equity observations must be ordered');
|
||||
}
|
||||
if (last?.timestamp === timestamp) {
|
||||
last.value = value;
|
||||
} else {
|
||||
this.equityCurve.push({ timestamp, value });
|
||||
}
|
||||
this.analysis = undefined;
|
||||
}
|
||||
addTrade(trade: Trade): void {
|
||||
finite(trade.pnl);
|
||||
finite(trade.holdingPeriod);
|
||||
if (trade.holdingPeriod < 0) {
|
||||
throw new Error('Holding period must be nonnegative');
|
||||
}
|
||||
this.trades.push(structuredClone(trade));
|
||||
this.analysis = undefined;
|
||||
}
|
||||
setBenchmark(returns: number[]): void {
|
||||
for (const value of returns) {
|
||||
finite(value);
|
||||
}
|
||||
this.benchmarkReturns = [...returns];
|
||||
this.analysis = undefined;
|
||||
}
|
||||
private evaluate(): Analysis {
|
||||
this.analysis ??= performanceAnalysis(
|
||||
this.equityCurve,
|
||||
this.trades,
|
||||
this.initialCapital,
|
||||
this.benchmarkReturns
|
||||
);
|
||||
return this.analysis;
|
||||
}
|
||||
getAnalysis(): Analysis {
|
||||
return structuredClone(this.evaluate());
|
||||
}
|
||||
analyze(): PerformanceMetrics {
|
||||
const metrics = { ...this.evaluate().metrics };
|
||||
for (const field of percentageFields) {
|
||||
const value = metrics[field];
|
||||
if (value !== null) {
|
||||
metrics[field] = finite(value * 100);
|
||||
}
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
analyzeDrawdowns(): DrawdownAnalysis {
|
||||
const equity = this.evaluate().equity;
|
||||
return {
|
||||
maxDrawdown: equity.maxDrawdown,
|
||||
maxDrawdownDuration: equity.maxDrawdownDuration,
|
||||
currentDrawdown: equity.currentDrawdown,
|
||||
drawdownPeriods: equity.periods.map(period => ({
|
||||
...period,
|
||||
start: new Date(period.start),
|
||||
end: new Date(period.end),
|
||||
})),
|
||||
underwaterCurve: equity.underwater.map(point => ({
|
||||
date: new Date(point.timestamp),
|
||||
drawdown: point.value,
|
||||
})),
|
||||
};
|
||||
}
|
||||
calculateFactorAttribution(benchmark: number[]): FactorAttribution {
|
||||
return factorStatistics(this.evaluate().equity.dailyReturns, benchmark);
|
||||
}
|
||||
exportReport(metrics: PerformanceMetrics = this.analyze()): string {
|
||||
const number = (value: number | null, scale = 1) => formatStatistic(value, 2, scale);
|
||||
return [
|
||||
'# Performance Report',
|
||||
'',
|
||||
'## Summary Statistics',
|
||||
'- Total Return: ' + number(metrics.totalReturn) + '%',
|
||||
'- Annualized Return: ' +
|
||||
number(metrics.annualizedReturn) +
|
||||
(metrics.annualizedReturn === null ? '' : '%'),
|
||||
'- CAGR: ' + number(metrics.cagr) + (metrics.cagr === null ? '' : '%'),
|
||||
'- Volatility: ' + number(metrics.volatility) + (metrics.volatility === null ? '' : '%'),
|
||||
'- Max Drawdown: ' + number(metrics.maxDrawdown, 100) + '%',
|
||||
'- Sharpe Ratio: ' + number(metrics.sharpeRatio),
|
||||
'- Sortino Ratio: ' + number(metrics.sortinoRatio),
|
||||
'',
|
||||
'## Trade Analysis',
|
||||
'- Total Trades: ' + metrics.totalTrades,
|
||||
'- Win Rate: ' + number(metrics.winRate) + '%',
|
||||
'- Profit Factor: ' + number(metrics.profitFactor),
|
||||
'- Average Win: $' + number(metrics.avgWin),
|
||||
'- Average Loss: $' + number(metrics.avgLoss),
|
||||
'- Expectancy: $' + number(metrics.expectancy),
|
||||
'',
|
||||
'## Risk Metrics',
|
||||
'- VaR (95%): ' + number(metrics.var95) + (metrics.var95 === null ? '' : '%'),
|
||||
'- CVaR (95%): ' + number(metrics.cvar95) + (metrics.cvar95 === null ? '' : '%'),
|
||||
'- Downside Volatility: ' +
|
||||
number(metrics.downVolatility) +
|
||||
(metrics.downVolatility === null ? '' : '%'),
|
||||
'- Tail Ratio: ' + number(metrics.tailRatio),
|
||||
'- Skewness: ' + number(metrics.skewness),
|
||||
'- Kurtosis: ' + number(metrics.kurtosis),
|
||||
].join('\n');
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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');
|
||||
}
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { amount, decimal } from '../execution/model';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { StrategyManager } from '../strategies/StrategyManager';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { BacktestMarket } from './BacktestMarket';
|
||||
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
||||
import { BacktestReport } from './BacktestReport';
|
||||
import type { LegacyBacktestExecutionEngine } from './execution-engine';
|
||||
import { closedTradesSchema } from './native-result';
|
||||
import { backtestStrategies } from './strategy-plan';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
export type { BacktestResult } from './typescript-result';
|
||||
const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const;
|
||||
|
||||
/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */
|
||||
export class BacktestEngine extends EventEmitter implements LegacyBacktestExecutionEngine {
|
||||
private playback?: BacktestPlayback;
|
||||
private active?: Promise<BacktestResult>;
|
||||
private completedReport?: BacktestReport;
|
||||
private closing = false;
|
||||
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'error'>;
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>;
|
||||
strategies: Pick<StrategyManager, 'initializeStrategies' | 'onMarketData'>;
|
||||
execution: Pick<ExecutionService, 'getAccount'>;
|
||||
getTradingEngine: () => TradingEngine;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||
if (this.closing || this.active) {
|
||||
throw new Error(
|
||||
this.closing ? 'Backtest engine is shutting down' : 'Backtest already running'
|
||||
);
|
||||
}
|
||||
const config = parseBacktestRequest(input);
|
||||
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
|
||||
this.playback = playback;
|
||||
this.completedReport = undefined;
|
||||
const work = this.execute(config, playback, resolver);
|
||||
this.active = work;
|
||||
try {
|
||||
return await work;
|
||||
} finally {
|
||||
playback.finish();
|
||||
this.active = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async execute(
|
||||
config: BacktestConfig,
|
||||
playback: BacktestPlayback,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<BacktestResult> {
|
||||
const plan = backtestStrategies(config, 'typescript');
|
||||
const { logger, storage, strategies: strategyManager, execution } = this.dependencies;
|
||||
logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||
const dataset = await playback.read(() =>
|
||||
resolveDataset(storage, config, resolver, playback.signal)
|
||||
);
|
||||
playback.assertRunning();
|
||||
const dataManager = new DataManager(storage);
|
||||
dataManager.inspectDataset(dataset);
|
||||
const strategies = plan.map(({ name, parameters, index }) => ({
|
||||
id: name + '-' + index,
|
||||
name,
|
||||
enabled: true,
|
||||
parameters,
|
||||
symbols: config.symbols,
|
||||
allocation: 1 / plan.length,
|
||||
}));
|
||||
await strategyManager.initializeStrategies(strategies);
|
||||
playback.assertRunning();
|
||||
const trading = this.dependencies.getTradingEngine();
|
||||
const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash);
|
||||
const report = new BacktestReport(config, config.runId ?? randomUUID());
|
||||
await playback.process(
|
||||
dataset.bars,
|
||||
bar => bar.timestamp,
|
||||
async bar => {
|
||||
trading.advanceTime(bar.timestamp);
|
||||
const data = {
|
||||
type: 'bar' as const,
|
||||
data: bar,
|
||||
eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'),
|
||||
};
|
||||
market.process(data);
|
||||
await strategyManager.onMarketData(data);
|
||||
report.record(bar.timestamp, (await execution.getAccount()).equity);
|
||||
},
|
||||
progress => this.publishProgress(progress)
|
||||
);
|
||||
playback.assertRunning();
|
||||
const closedTrades = closedTradesSchema.parse(JSON.parse(trading.getClosedTrades()));
|
||||
const account = await execution.getAccount();
|
||||
playback.assertRunning();
|
||||
const positions = Object.values(account.positions)
|
||||
.filter(position => position.quantity !== 0)
|
||||
.map(position => {
|
||||
const quote = account.quotes[position.symbol];
|
||||
const currentPrice = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice;
|
||||
return {
|
||||
...position,
|
||||
currentPrice,
|
||||
unrealizedPnl: amount(
|
||||
decimal(currentPrice).minus(position.averagePrice).times(position.quantity)
|
||||
),
|
||||
};
|
||||
});
|
||||
const result = report.complete(
|
||||
dataset,
|
||||
closedTrades,
|
||||
positions,
|
||||
dataManager.getDataQualityReport()
|
||||
);
|
||||
this.completedReport = report;
|
||||
logger.info('TypeScript backtest completed', { trades: result.trades.length });
|
||||
return result;
|
||||
}
|
||||
|
||||
private publishProgress(progress: PlaybackProgress): void {
|
||||
try {
|
||||
this.emit('progress', progress);
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error('Backtest progress observer failed', { error });
|
||||
}
|
||||
}
|
||||
|
||||
async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise<string> {
|
||||
if (this.active) {
|
||||
throw new Error('Cannot export an unfinished backtest');
|
||||
}
|
||||
return defined(this.completedReport, 'No completed backtest report is available').export(
|
||||
format
|
||||
);
|
||||
}
|
||||
async pauseBacktest(): Promise<void> {
|
||||
this.playback?.pause();
|
||||
}
|
||||
async resumeBacktest(): Promise<void> {
|
||||
this.playback?.resume();
|
||||
}
|
||||
async stopBacktest(): Promise<void> {
|
||||
this.playback?.stop();
|
||||
}
|
||||
async shutdown(): Promise<void> {
|
||||
this.closing = true;
|
||||
await this.stopBacktest();
|
||||
await this.active?.catch(() => {});
|
||||
}
|
||||
setSpeedMultiplier(speed: number | null): void {
|
||||
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
|
||||
throw new Error('Backtest speed must be positive or null');
|
||||
}
|
||||
this.playback?.setSpeed(speed);
|
||||
}
|
||||
getStatus() {
|
||||
return (
|
||||
this.playback?.getStatus() ?? {
|
||||
isRunning: false,
|
||||
isPaused: false,
|
||||
progress: 0,
|
||||
currentTime: 0,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
import type { TradingEngine } from '@stock-bot/engine';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import type { MarketData, MarketMicrostructure } from '../types';
|
||||
import { MarketSimulator } from './MarketSimulator';
|
||||
|
||||
export type BacktestMarketPort = Pick<
|
||||
TradingEngine,
|
||||
'updateQuote' | 'updateTrade' | 'setMicrostructure'
|
||||
>;
|
||||
|
||||
/** Market projection only: orders and financial accounting still go through ExecutionService. */
|
||||
export class BacktestMarket {
|
||||
private readonly simulator = new MarketSimulator();
|
||||
private readonly microstructures = new Map<string, MarketMicrostructure>();
|
||||
|
||||
constructor(
|
||||
private readonly engine: BacktestMarketPort,
|
||||
symbols: string[],
|
||||
datasetHash: string
|
||||
) {
|
||||
this.simulator.resetWithSeed(Number.parseInt(datasetHash.slice(0, 8), 16));
|
||||
this.loadMarketMicrostructure(symbols);
|
||||
}
|
||||
|
||||
process(data: MarketData): void {
|
||||
// Process through market simulator for realistic orderbook
|
||||
const orderbook = this.simulator.processMarketData(data);
|
||||
|
||||
if (orderbook) {
|
||||
// Update trading engine with simulated orderbook
|
||||
if (orderbook.bids.length > 0 && orderbook.asks.length > 0) {
|
||||
this.engine.updateQuote(
|
||||
orderbook.symbol,
|
||||
at(orderbook.bids, 0).price,
|
||||
at(orderbook.asks, 0).price,
|
||||
at(orderbook.bids, 0).size,
|
||||
at(orderbook.asks, 0).size
|
||||
);
|
||||
}
|
||||
|
||||
// Set microstructure in trading core for realistic fills
|
||||
const microstructure = this.microstructures.get(orderbook.symbol);
|
||||
if (microstructure && this.engine.setMicrostructure) {
|
||||
this.engine.setMicrostructure(orderbook.symbol, microstructure);
|
||||
}
|
||||
} else {
|
||||
// Fallback to simple processing
|
||||
switch (data.type) {
|
||||
case 'quote':
|
||||
this.engine.updateQuote(
|
||||
data.data.symbol,
|
||||
data.data.bid,
|
||||
data.data.ask,
|
||||
data.data.bidSize,
|
||||
data.data.askSize
|
||||
);
|
||||
break;
|
||||
|
||||
case 'trade':
|
||||
this.engine.updateTrade(
|
||||
data.data.symbol,
|
||||
data.data.price,
|
||||
data.data.size,
|
||||
data.data.side
|
||||
);
|
||||
break;
|
||||
|
||||
case 'bar': {
|
||||
const spread = data.data.high - data.data.low;
|
||||
const spreadBps = (spread / data.data.close) * 10000;
|
||||
const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000;
|
||||
|
||||
this.engine.updateQuote(
|
||||
data.data.symbol,
|
||||
data.data.close - halfSpread,
|
||||
data.data.close + halfSpread,
|
||||
data.data.volume / 100,
|
||||
data.data.volume / 100
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private loadMarketMicrostructure(symbols: string[]): void {
|
||||
// In real implementation, would load from database
|
||||
// For now, create reasonable defaults based on symbol characteristics
|
||||
for (const symbol of symbols) {
|
||||
const microstructure: MarketMicrostructure = {
|
||||
symbol,
|
||||
avgSpreadBps: 3,
|
||||
dailyVolume: 10_000_000,
|
||||
avgTradeSize: 100,
|
||||
volatility: 0.2,
|
||||
tickSize: 0.01,
|
||||
lotSize: 1,
|
||||
intradayVolumeProfile: this.generateIntradayProfile(),
|
||||
};
|
||||
|
||||
this.microstructures.set(symbol, microstructure);
|
||||
this.simulator.setMicrostructure(symbol, microstructure);
|
||||
}
|
||||
}
|
||||
|
||||
private generateIntradayProfile(): number[] {
|
||||
// U-shaped intraday volume pattern
|
||||
const profile = new Array(24).fill(0);
|
||||
const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM
|
||||
|
||||
tradingHours.forEach((hour, idx) => {
|
||||
if (idx === 0 || idx === tradingHours.length - 1) {
|
||||
// High volume at open and close
|
||||
profile[hour] = 0.2;
|
||||
} else if (idx === 1 || idx === tradingHours.length - 2) {
|
||||
// Moderate volume
|
||||
profile[hour] = 0.15;
|
||||
} else {
|
||||
// Lower midday volume
|
||||
profile[hour] = 0.1;
|
||||
}
|
||||
});
|
||||
|
||||
// Normalize
|
||||
const sum = profile.reduce((a, b) => a + b, 0);
|
||||
return profile.map(v => v / sum);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
import { BacktestCancelledError } from './execution-engine';
|
||||
|
||||
export interface PlaybackProgress {
|
||||
processed: number;
|
||||
total: number;
|
||||
remaining: number;
|
||||
currentTime: Date;
|
||||
currentDate: string;
|
||||
progress: number;
|
||||
}
|
||||
|
||||
/** One run's cursor and interruptible controls; independent of trading, storage and reporting. */
|
||||
export class BacktestPlayback {
|
||||
private readonly controller = new AbortController();
|
||||
private wake?: () => void;
|
||||
private running = true;
|
||||
private paused = false;
|
||||
private processed = 0;
|
||||
private total = 0;
|
||||
private started = false;
|
||||
|
||||
constructor(
|
||||
private currentTime: number,
|
||||
private speed: number | null
|
||||
) {
|
||||
this.validateSpeed(speed);
|
||||
}
|
||||
|
||||
private validateSpeed(speed: number | null): void {
|
||||
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
|
||||
throw new Error('Backtest speed must be positive or null');
|
||||
}
|
||||
}
|
||||
|
||||
assertRunning(): void {
|
||||
if (!this.running) {
|
||||
throw new BacktestCancelledError();
|
||||
}
|
||||
this.controller.signal.throwIfAborted();
|
||||
}
|
||||
|
||||
get signal(): AbortSignal {
|
||||
return this.controller.signal;
|
||||
}
|
||||
|
||||
/** Only race side-effect-free reads; late reads must never resume execution. */
|
||||
async read<T>(load: () => Promise<T>): Promise<T> {
|
||||
this.assertRunning();
|
||||
const { signal } = this.controller;
|
||||
signal.throwIfAborted();
|
||||
let rejectAbort!: (reason: unknown) => void;
|
||||
const aborted = new Promise<never>((_resolve, reject) => {
|
||||
rejectAbort = reject;
|
||||
});
|
||||
const onAbort = () => rejectAbort(signal.reason);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
try {
|
||||
const work = Promise.resolve().then(() => {
|
||||
this.assertRunning();
|
||||
return load();
|
||||
});
|
||||
return await Promise.race([work, aborted]);
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
private async wait(ms?: number): Promise<void> {
|
||||
this.assertRunning();
|
||||
await new Promise<void>(resolve => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const done = () => {
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.wake = undefined;
|
||||
resolve();
|
||||
};
|
||||
this.wake = done;
|
||||
if (ms !== undefined) {
|
||||
timer = setTimeout(done, ms);
|
||||
}
|
||||
});
|
||||
this.assertRunning();
|
||||
}
|
||||
|
||||
private async ready(): Promise<void> {
|
||||
this.assertRunning();
|
||||
while (this.paused) {
|
||||
await this.wait();
|
||||
}
|
||||
}
|
||||
|
||||
async process<T>(
|
||||
events: readonly T[],
|
||||
timestamp: (event: T) => number,
|
||||
consume: (event: T) => Promise<void>,
|
||||
progress: (value: PlaybackProgress) => void
|
||||
): Promise<void> {
|
||||
this.assertRunning();
|
||||
if (this.started) {
|
||||
throw new Error('Backtest playback has already started');
|
||||
}
|
||||
this.started = true;
|
||||
this.total = events.length;
|
||||
// Frozen inputs are already validated and ordered. A cursor avoids copying and shifting history.
|
||||
for (const event of events) {
|
||||
await this.ready();
|
||||
if (this.speed !== null) {
|
||||
await this.wait(1000 / this.speed);
|
||||
}
|
||||
await this.ready();
|
||||
this.currentTime = timestamp(event);
|
||||
await consume(event);
|
||||
this.processed++;
|
||||
this.assertRunning();
|
||||
const interval = this.speed === null ? 100 : Math.max(1, Math.floor(10 / this.speed));
|
||||
if (this.processed < this.total && this.processed % interval === 0) {
|
||||
progress(this.progress());
|
||||
}
|
||||
// Let cancellation, lease heartbeats and other accounts run even at unlimited speed.
|
||||
if (this.speed === null && this.processed % 100 === 0) {
|
||||
await this.wait(0);
|
||||
}
|
||||
}
|
||||
this.assertRunning();
|
||||
progress(this.progress());
|
||||
this.assertRunning();
|
||||
}
|
||||
|
||||
private progress(): PlaybackProgress {
|
||||
return {
|
||||
processed: this.processed,
|
||||
total: this.total,
|
||||
remaining: this.total - this.processed,
|
||||
currentTime: new Date(this.currentTime),
|
||||
currentDate: new Date(this.currentTime).toISOString(),
|
||||
progress:
|
||||
this.total > 0
|
||||
? this.processed === this.total
|
||||
? 100
|
||||
: Math.min(99, Math.round((this.processed / this.total) * 100))
|
||||
: 0,
|
||||
};
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
if (!this.running) {
|
||||
return;
|
||||
}
|
||||
this.paused = true;
|
||||
this.wake?.();
|
||||
}
|
||||
resume(): void {
|
||||
this.paused = false;
|
||||
this.wake?.();
|
||||
}
|
||||
stop(): void {
|
||||
this.controller.abort(new BacktestCancelledError());
|
||||
this.paused = false;
|
||||
this.wake?.();
|
||||
}
|
||||
finish(): void {
|
||||
this.running = false;
|
||||
this.paused = false;
|
||||
this.wake?.();
|
||||
}
|
||||
setSpeed(speed: number | null): void {
|
||||
this.validateSpeed(speed);
|
||||
this.speed = speed;
|
||||
this.wake?.();
|
||||
}
|
||||
getStatus() {
|
||||
return {
|
||||
isRunning: this.running,
|
||||
isPaused: this.paused,
|
||||
progress: this.progress().progress,
|
||||
currentTime: this.currentTime,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,230 +0,0 @@
|
|||
import { at, defined } from '@stock-bot/invariants';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { ClosedTrade } from './native-result';
|
||||
import { formatReport, type ReportExport } from './report-format';
|
||||
import type { BacktestResult, OHLCBar } from './typescript-result';
|
||||
|
||||
/** Run-local observations and a detached completed report; never reads services or financial state. */
|
||||
export class BacktestReport {
|
||||
private readonly equityCurve: { timestamp: number; value: number }[];
|
||||
private performanceAnalyzer?: PerformanceAnalyzer;
|
||||
private snapshot?: ReportExport;
|
||||
private readonly config: BacktestConfig;
|
||||
|
||||
constructor(
|
||||
config: BacktestConfig,
|
||||
private readonly backtestId: string
|
||||
) {
|
||||
this.config = structuredClone(config);
|
||||
const start = Date.parse(config.startDate);
|
||||
this.equityCurve = [{ timestamp: start, value: config.initialCapital }];
|
||||
this.performanceAnalyzer = new PerformanceAnalyzer(config.initialCapital);
|
||||
this.performanceAnalyzer.addEquityPoint(new Date(start), config.initialCapital);
|
||||
}
|
||||
|
||||
record(timestamp: number, equity: number): void {
|
||||
if (this.snapshot) {
|
||||
throw new Error('Backtest report is already finalized');
|
||||
}
|
||||
if (!Number.isFinite(timestamp) || !Number.isFinite(equity)) {
|
||||
throw new Error('Invalid backtest equity observation');
|
||||
}
|
||||
const last = defined(this.equityCurve[this.equityCurve.length - 1]);
|
||||
if (timestamp < last.timestamp) {
|
||||
throw new Error('Out-of-order backtest equity observation');
|
||||
}
|
||||
defined(this.performanceAnalyzer).addEquityPoint(new Date(timestamp), equity);
|
||||
if (last.timestamp === timestamp) {
|
||||
last.value = equity;
|
||||
} else {
|
||||
this.equityCurve.push({ timestamp, value: equity });
|
||||
}
|
||||
}
|
||||
|
||||
complete(
|
||||
dataset: HistoricalDataset,
|
||||
trades: ClosedTrade[],
|
||||
finalPositions: BacktestResult['positions'],
|
||||
dataQuality: unknown,
|
||||
completedAt = new Date().toISOString()
|
||||
): BacktestResult {
|
||||
if (this.snapshot) {
|
||||
throw new Error('Backtest report is already finalized');
|
||||
}
|
||||
const closedTrades = structuredClone(trades);
|
||||
const performance = this.calculatePerformance(closedTrades);
|
||||
const analysis = defined(this.performanceAnalyzer).getAnalysis();
|
||||
const result: BacktestResult = {
|
||||
// Identification
|
||||
backtestId: this.backtestId,
|
||||
status: 'completed' as const,
|
||||
completedAt,
|
||||
|
||||
// Configuration used
|
||||
config: {
|
||||
name: this.config.name || 'Backtest',
|
||||
strategy: this.config.strategy,
|
||||
symbols: this.config.symbols,
|
||||
startDate: this.config.startDate,
|
||||
endDate: this.config.endDate,
|
||||
initialCapital: this.config.initialCapital,
|
||||
commission: this.config.commission ?? 0.001,
|
||||
slippage: this.config.slippage ?? 0.0001,
|
||||
dataFrequency: this.config.dataFrequency || '1d',
|
||||
},
|
||||
|
||||
// Performance metrics (frontend-ready)
|
||||
metrics: {
|
||||
totalReturn: performance.totalReturn,
|
||||
sharpeRatio: performance.sharpeRatio,
|
||||
maxDrawdown: performance.maxDrawdown,
|
||||
winRate: performance.winRate,
|
||||
totalTrades: performance.totalTrades,
|
||||
profitFactor: performance.profitFactor,
|
||||
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
|
||||
avgWin: performance.avgWin || 0,
|
||||
avgLoss: performance.avgLoss || 0,
|
||||
expectancy: performance.expectancy || 0,
|
||||
calmarRatio: performance.calmarRatio,
|
||||
sortinoRatio: performance.sortinoRatio,
|
||||
annualizedReturn: performance.annualizedReturn,
|
||||
cagr: performance.cagr,
|
||||
},
|
||||
|
||||
// Chart data (frontend-ready format)
|
||||
equity: this.equityCurve.map(point => ({
|
||||
date: new Date(point.timestamp).toISOString(),
|
||||
value: point.value,
|
||||
})),
|
||||
|
||||
// OHLC data for charts
|
||||
ohlcData: this.getOHLCData(dataset),
|
||||
|
||||
// Trade history (frontend-ready)
|
||||
trades: closedTrades.map(trade => ({
|
||||
id: trade.id,
|
||||
symbol: trade.symbol,
|
||||
entryDate: trade.entry_time,
|
||||
exitDate: trade.exit_time,
|
||||
entryPrice: trade.entry_price,
|
||||
exitPrice: trade.exit_price,
|
||||
quantity: trade.quantity,
|
||||
side: trade.side === 'Buy' ? 'buy' : 'sell',
|
||||
pnl: trade.pnl,
|
||||
pnlPercent: trade.pnl_percent,
|
||||
commission: trade.commission,
|
||||
duration: trade.duration_ms,
|
||||
})),
|
||||
|
||||
// Final positions
|
||||
positions: finalPositions.map(pos => ({
|
||||
symbol: pos.symbol,
|
||||
quantity: pos.quantity,
|
||||
averagePrice: pos.averagePrice,
|
||||
currentPrice: pos.currentPrice || pos.averagePrice,
|
||||
unrealizedPnl: pos.unrealizedPnl || 0,
|
||||
realizedPnl: pos.realizedPnl || 0,
|
||||
})),
|
||||
|
||||
// Additional analytics
|
||||
analytics: {
|
||||
drawdownSeries: analysis.equity.underwater.map(point => ({
|
||||
...point,
|
||||
value: point.value * 100,
|
||||
})),
|
||||
dailyReturns: analysis.equity.dailyReturns.map(value => value * 100),
|
||||
monthlyReturns: Object.fromEntries(
|
||||
Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [
|
||||
month,
|
||||
value * 100,
|
||||
])
|
||||
),
|
||||
exposureTime: this.calculateExposureTime(closedTrades),
|
||||
riskMetrics: {
|
||||
volatility: analysis.risk.volatility,
|
||||
downsideDeviation: analysis.risk.downsideDeviation,
|
||||
var95: analysis.risk.var95,
|
||||
var99: analysis.risk.var99,
|
||||
cvar95: analysis.risk.cvar95,
|
||||
maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
this.snapshot = structuredClone({
|
||||
summary: performance,
|
||||
trades: closedTrades,
|
||||
equityCurve: this.equityCurve,
|
||||
drawdowns: result.analytics.drawdownSeries,
|
||||
dataQuality,
|
||||
performanceReport: defined(this.performanceAnalyzer).exportReport(performance),
|
||||
});
|
||||
// The completed snapshot is sufficient for export; do not retain the analysis input twice.
|
||||
this.equityCurve.length = 0;
|
||||
this.performanceAnalyzer = undefined;
|
||||
return structuredClone(result);
|
||||
}
|
||||
|
||||
export(format: 'json' | 'csv' | 'html' = 'json'): string {
|
||||
if (!this.snapshot) {
|
||||
throw new Error('No completed backtest report is available');
|
||||
}
|
||||
return formatReport(this.snapshot, format);
|
||||
}
|
||||
|
||||
private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics {
|
||||
const analyzer = defined(this.performanceAnalyzer);
|
||||
// Import each closed trade once, when the completed snapshot is built.
|
||||
closedTrades.forEach(trade => {
|
||||
analyzer.addTrade({
|
||||
entryTime: new Date(trade.entry_time),
|
||||
exitTime: new Date(trade.exit_time),
|
||||
symbol: trade.symbol,
|
||||
side: trade.side === 'Buy' ? 'long' : 'short',
|
||||
entryPrice: trade.entry_price,
|
||||
exitPrice: trade.exit_price,
|
||||
quantity: trade.quantity,
|
||||
commission: trade.commission || 0,
|
||||
pnl: trade.pnl || 0,
|
||||
returnPct: trade.pnl_percent || 0,
|
||||
holdingPeriod: trade.duration_ms / 60000, // Convert to minutes
|
||||
mae: 0, // Not tracked yet
|
||||
mfe: 0, // Not tracked yet
|
||||
});
|
||||
});
|
||||
|
||||
return analyzer.analyze();
|
||||
}
|
||||
|
||||
private calculateExposureTime(closedTrades: ClosedTrade[] = []): number {
|
||||
if (closedTrades.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let totalExposureTime = 0;
|
||||
for (const trade of closedTrades) {
|
||||
totalExposureTime += trade.duration_ms || 0;
|
||||
}
|
||||
|
||||
// Use equity curve to determine actual trading period
|
||||
const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0;
|
||||
const endTime =
|
||||
this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0;
|
||||
const totalTime = endTime - startTime;
|
||||
|
||||
return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0;
|
||||
}
|
||||
|
||||
private getOHLCData(dataset: HistoricalDataset): Record<string, OHLCBar[]> {
|
||||
const grouped: Record<string, OHLCBar[]> = Object.fromEntries(
|
||||
this.config.symbols.map(symbol => [symbol, []])
|
||||
);
|
||||
for (const bar of dataset.bars) {
|
||||
const { timestamp, open, high, low, close, volume } = bar;
|
||||
defined(grouped[bar.symbol]).push({ timestamp, open, high, low, close, volume });
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,423 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
type Bar,
|
||||
type MarketData,
|
||||
type OrderBookSnapshot,
|
||||
type PriceLevel,
|
||||
type Quote,
|
||||
type Trade,
|
||||
} from '../types';
|
||||
import { type MarketMicrostructure } from '../types/MarketMicrostructure';
|
||||
|
||||
const _logger = getLogger('MarketSimulator');
|
||||
|
||||
export interface SimulationConfig {
|
||||
useHistoricalSpreads: boolean;
|
||||
modelHiddenLiquidity: boolean;
|
||||
includeDarkPools: boolean;
|
||||
latencyMs: number;
|
||||
rebateRate: number;
|
||||
takeFeeRate: number;
|
||||
}
|
||||
|
||||
export interface LiquidityProfile {
|
||||
visibleLiquidity: number;
|
||||
hiddenLiquidity: number;
|
||||
darkPoolLiquidity: number;
|
||||
totalLiquidity: number;
|
||||
}
|
||||
|
||||
export class MarketSimulator {
|
||||
private orderBooks: Map<string, OrderBookSnapshot> = new Map();
|
||||
private microstructures: Map<string, MarketMicrostructure> = new Map();
|
||||
private liquidityProfiles: Map<string, LiquidityProfile> = new Map();
|
||||
private lastTrades: Map<string, Trade> = new Map();
|
||||
private config: SimulationConfig;
|
||||
private randomState = 1;
|
||||
|
||||
resetWithSeed(seed: number): void {
|
||||
this.randomState = seed >>> 0;
|
||||
this.orderBooks.clear();
|
||||
this.microstructures.clear();
|
||||
this.liquidityProfiles.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
|
||||
private random(): number {
|
||||
this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
|
||||
return this.randomState / 4294967296;
|
||||
}
|
||||
|
||||
constructor(config: Partial<SimulationConfig> = {}) {
|
||||
this.config = {
|
||||
useHistoricalSpreads: true,
|
||||
modelHiddenLiquidity: true,
|
||||
includeDarkPools: true,
|
||||
latencyMs: 1,
|
||||
rebateRate: -0.0002, // 2 bps rebate for providing liquidity
|
||||
takeFeeRate: 0.0003, // 3 bps fee for taking liquidity
|
||||
...config,
|
||||
};
|
||||
}
|
||||
|
||||
setMicrostructure(symbol: string, microstructure: MarketMicrostructure): void {
|
||||
this.microstructures.set(symbol, microstructure);
|
||||
this.updateLiquidityProfile(symbol);
|
||||
}
|
||||
|
||||
processMarketData(data: MarketData): OrderBookSnapshot | null {
|
||||
const { symbol } = this.getSymbolFromData(data);
|
||||
|
||||
switch (data.type) {
|
||||
case 'quote':
|
||||
return this.updateFromQuote(symbol, data.data);
|
||||
case 'trade':
|
||||
return this.updateFromTrade(symbol, data.data);
|
||||
case 'bar':
|
||||
return this.reconstructFromBar(symbol, data.data);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private updateFromQuote(symbol: string, quote: Quote): OrderBookSnapshot {
|
||||
let orderbook = this.orderBooks.get(symbol);
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
|
||||
if (!orderbook || !microstructure) {
|
||||
// Create new orderbook
|
||||
orderbook = this.createOrderBook(symbol, quote, microstructure);
|
||||
} else {
|
||||
// Update existing orderbook
|
||||
orderbook = this.updateOrderBook(orderbook, quote, microstructure);
|
||||
}
|
||||
|
||||
this.orderBooks.set(symbol, orderbook);
|
||||
return orderbook;
|
||||
}
|
||||
|
||||
private updateFromTrade(symbol: string, trade: Trade): OrderBookSnapshot | null {
|
||||
const orderbook = this.orderBooks.get(symbol);
|
||||
if (!orderbook) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Update last trade
|
||||
this.lastTrades.set(symbol, trade);
|
||||
|
||||
// Adjust orderbook based on trade
|
||||
// Large trades likely consumed liquidity
|
||||
const impactFactor = Math.min(trade.size / 1000, 0.1); // Max 10% impact
|
||||
|
||||
if (trade.side === 'buy') {
|
||||
// Buy trade consumed ask liquidity
|
||||
orderbook.asks = orderbook.asks.map((level, i) => ({
|
||||
...level,
|
||||
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
|
||||
}));
|
||||
} else {
|
||||
// Sell trade consumed bid liquidity
|
||||
orderbook.bids = orderbook.bids.map((level, i) => ({
|
||||
...level,
|
||||
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
|
||||
}));
|
||||
}
|
||||
|
||||
return orderbook;
|
||||
}
|
||||
|
||||
private reconstructFromBar(symbol: string, bar: Bar): OrderBookSnapshot {
|
||||
const microstructure =
|
||||
this.microstructures.get(symbol) || this.createDefaultMicrostructure(symbol);
|
||||
|
||||
// Estimate spread from high-low range
|
||||
const hlSpread = (bar.high - bar.low) / bar.close;
|
||||
const estimatedSpreadBps = Math.max(
|
||||
microstructure.avgSpreadBps,
|
||||
hlSpread * 10000 * 0.1 // 10% of HL range as spread estimate
|
||||
);
|
||||
|
||||
// Create synthetic quote
|
||||
const midPrice = bar.vwap || (bar.high + bar.low + bar.close) / 3;
|
||||
const halfSpread = (midPrice * estimatedSpreadBps) / 20000;
|
||||
|
||||
const quote: Quote = {
|
||||
symbol,
|
||||
timestamp: bar.timestamp,
|
||||
bid: midPrice - halfSpread,
|
||||
ask: midPrice + halfSpread,
|
||||
bidSize: bar.volume / 100, // Rough estimate
|
||||
askSize: bar.volume / 100,
|
||||
};
|
||||
|
||||
return this.createOrderBook(symbol, quote, microstructure);
|
||||
}
|
||||
|
||||
private createOrderBook(
|
||||
symbol: string,
|
||||
topQuote: Quote,
|
||||
microstructure?: MarketMicrostructure
|
||||
): OrderBookSnapshot {
|
||||
const micro = microstructure || this.createDefaultMicrostructure(symbol);
|
||||
const levels = 10;
|
||||
|
||||
const bids: PriceLevel[] = [];
|
||||
const asks: PriceLevel[] = [];
|
||||
|
||||
// Model order book depth
|
||||
for (let i = 0; i < levels; i++) {
|
||||
const depthFactor = Math.exp(-i * 0.3); // Exponential decay
|
||||
const _spreadMultiplier = 1 + i * 0.1; // Wider spread at deeper levels
|
||||
|
||||
// Hidden liquidity modeling
|
||||
const hiddenRatio = this.config.modelHiddenLiquidity
|
||||
? 1 + this.random() * 2 // 1-3x visible size hidden
|
||||
: 1;
|
||||
|
||||
// Bid levels
|
||||
const bidPrice = topQuote.bid - i * micro.tickSize;
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
bids.push({
|
||||
price: bidPrice,
|
||||
size: Math.round(bidSize / micro.lotSize) * micro.lotSize,
|
||||
orderCount: Math.max(1, Math.floor(bidSize / 100)),
|
||||
hiddenSize: this.config.modelHiddenLiquidity ? bidSize * (hiddenRatio - 1) : undefined,
|
||||
});
|
||||
|
||||
// Ask levels
|
||||
const askPrice = topQuote.ask + i * micro.tickSize;
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
asks.push({
|
||||
price: askPrice,
|
||||
size: Math.round(askSize / micro.lotSize) * micro.lotSize,
|
||||
orderCount: Math.max(1, Math.floor(askSize / 100)),
|
||||
hiddenSize: this.config.modelHiddenLiquidity ? askSize * (hiddenRatio - 1) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
symbol,
|
||||
timestamp: new Date(),
|
||||
bids,
|
||||
asks,
|
||||
lastTrade: this.lastTrades.get(symbol),
|
||||
};
|
||||
}
|
||||
|
||||
private updateOrderBook(
|
||||
current: OrderBookSnapshot,
|
||||
quote: Quote,
|
||||
microstructure?: MarketMicrostructure
|
||||
): OrderBookSnapshot {
|
||||
const _micro = microstructure || this.createDefaultMicrostructure(current.symbol);
|
||||
|
||||
// Update top of book
|
||||
if (current.bids.length > 0) {
|
||||
at(current.bids, 0).price = quote.bid;
|
||||
at(current.bids, 0).size = quote.bidSize;
|
||||
}
|
||||
|
||||
if (current.asks.length > 0) {
|
||||
at(current.asks, 0).price = quote.ask;
|
||||
at(current.asks, 0).size = quote.askSize;
|
||||
}
|
||||
|
||||
// Adjust deeper levels based on spread changes
|
||||
const oldSpread = at(current.asks, 0).price - at(current.bids, 0).price;
|
||||
const newSpread = quote.ask - quote.bid;
|
||||
const spreadRatio = newSpread / oldSpread;
|
||||
|
||||
// Update deeper levels
|
||||
for (let i = 1; i < current.bids.length; i++) {
|
||||
// Adjust sizes based on top of book changes
|
||||
const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
// Adjust prices to maintain relative spacing
|
||||
const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio;
|
||||
at(current.bids, i).price = at(current.bids, i - 1).price - spacing;
|
||||
}
|
||||
|
||||
for (let i = 1; i < current.asks.length; i++) {
|
||||
const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio;
|
||||
at(current.asks, i).price = at(current.asks, i - 1).price + spacing;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
simulateMarketImpact(
|
||||
symbol: string,
|
||||
side: 'buy' | 'sell',
|
||||
orderSize: number,
|
||||
orderType: 'market' | 'limit',
|
||||
limitPrice?: number
|
||||
): {
|
||||
fills: Array<{ price: number; size: number; venue: string }>;
|
||||
totalCost: number;
|
||||
avgPrice: number;
|
||||
marketImpact: number;
|
||||
fees: number;
|
||||
} {
|
||||
const orderbook = this.orderBooks.get(symbol);
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
const liquidityProfile = this.liquidityProfiles.get(symbol);
|
||||
|
||||
if (!orderbook) {
|
||||
throw new Error(`No orderbook available for ${symbol}`);
|
||||
}
|
||||
|
||||
const fills: Array<{ price: number; size: number; venue: string }> = [];
|
||||
let remainingSize = orderSize;
|
||||
let totalCost = 0;
|
||||
let fees = 0;
|
||||
|
||||
// Get relevant price levels
|
||||
const levels = side === 'buy' ? orderbook.asks : orderbook.bids;
|
||||
const multiplier = side === 'buy' ? 1 : -1;
|
||||
|
||||
// Simulate walking the book
|
||||
for (const level of levels) {
|
||||
if (remainingSize <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check limit price constraint
|
||||
if (limitPrice !== undefined) {
|
||||
if (side === 'buy' && level.price > limitPrice) {
|
||||
break;
|
||||
}
|
||||
if (side === 'sell' && level.price < limitPrice) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate available liquidity including hidden
|
||||
let availableSize = level.size;
|
||||
if (level.hiddenSize && this.config.modelHiddenLiquidity) {
|
||||
availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity
|
||||
}
|
||||
|
||||
const fillSize = Math.min(remainingSize, availableSize);
|
||||
|
||||
// Simulate latency - price might move
|
||||
if (this.config.latencyMs > 0 && orderType === 'market') {
|
||||
const priceMovement = microstructure
|
||||
? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
: 0;
|
||||
level.price += priceMovement * multiplier;
|
||||
}
|
||||
|
||||
fills.push({
|
||||
price: level.price,
|
||||
size: fillSize,
|
||||
venue: 'primary',
|
||||
});
|
||||
|
||||
totalCost += fillSize * level.price;
|
||||
remainingSize -= fillSize;
|
||||
|
||||
// Calculate fees
|
||||
if (orderType === 'market') {
|
||||
fees += fillSize * level.price * this.config.takeFeeRate;
|
||||
} else {
|
||||
// Limit orders that provide liquidity get rebate
|
||||
fees += fillSize * level.price * this.config.rebateRate;
|
||||
}
|
||||
}
|
||||
|
||||
// Dark pool execution for remaining size
|
||||
if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) {
|
||||
const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity;
|
||||
const darkPoolSize = remainingSize * darkPoolPct * this.random();
|
||||
|
||||
if (darkPoolSize > 0) {
|
||||
const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
fills.push({
|
||||
price: midPrice,
|
||||
size: darkPoolSize,
|
||||
venue: 'dark',
|
||||
});
|
||||
|
||||
totalCost += darkPoolSize * midPrice;
|
||||
remainingSize -= darkPoolSize;
|
||||
// Dark pools typically have lower fees
|
||||
fees += darkPoolSize * midPrice * 0.0001;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate results
|
||||
const filledSize = orderSize - remainingSize;
|
||||
const avgPrice = filledSize > 0 ? totalCost / filledSize : 0;
|
||||
|
||||
// Calculate market impact
|
||||
const initialMid = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
const marketImpact =
|
||||
filledSize > 0
|
||||
? (Math.abs(avgPrice - initialMid) / initialMid) * 10000 // in bps
|
||||
: 0;
|
||||
|
||||
return {
|
||||
fills,
|
||||
totalCost,
|
||||
avgPrice,
|
||||
marketImpact,
|
||||
fees,
|
||||
};
|
||||
}
|
||||
|
||||
private updateLiquidityProfile(symbol: string): void {
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
if (!microstructure) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Estimate liquidity distribution
|
||||
const visiblePct = 0.3; // 30% visible
|
||||
const hiddenPct = 0.5; // 50% hidden
|
||||
const darkPct = 0.2; // 20% dark
|
||||
|
||||
const totalDailyLiquidity = microstructure.dailyVolume;
|
||||
|
||||
this.liquidityProfiles.set(symbol, {
|
||||
visibleLiquidity: totalDailyLiquidity * visiblePct,
|
||||
hiddenLiquidity: totalDailyLiquidity * hiddenPct,
|
||||
darkPoolLiquidity: totalDailyLiquidity * darkPct,
|
||||
totalLiquidity: totalDailyLiquidity,
|
||||
});
|
||||
}
|
||||
|
||||
private createDefaultMicrostructure(symbol: string): MarketMicrostructure {
|
||||
return {
|
||||
symbol,
|
||||
avgSpreadBps: 5,
|
||||
dailyVolume: 1000000,
|
||||
avgTradeSize: 100,
|
||||
volatility: 0.02,
|
||||
tickSize: 0.01,
|
||||
lotSize: 1,
|
||||
intradayVolumeProfile: new Array(24).fill(1 / 24),
|
||||
};
|
||||
}
|
||||
|
||||
private getSymbolFromData(data: MarketData): { symbol: string } {
|
||||
return { symbol: data.data.symbol };
|
||||
}
|
||||
|
||||
getOrderBook(symbol: string): OrderBookSnapshot | undefined {
|
||||
return this.orderBooks.get(symbol);
|
||||
}
|
||||
|
||||
getLiquidityProfile(symbol: string): LiquidityProfile | undefined {
|
||||
return this.liquidityProfiles.get(symbol);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.orderBooks.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -9,13 +9,13 @@ import {
|
|||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
replayResultFormatSchema,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../contracts/strategy-replay';
|
||||
import { removeCandidateContainer } from './candidate-sandbox';
|
||||
import { canonicalWorkerUrl } from './canonical-build';
|
||||
import { canonicalWorkerUrl } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import {
|
||||
nativeWorkerMessageSchema,
|
||||
nativeWorkerRequestSchema,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
|
||||
import { sameIdentity } from '../contracts/native-replay';
|
||||
import { sameIdentity } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { importRetainedProgram } from '../strategies/retained-program';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
retainedProgramSelectionSchema,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
|
||||
import { replayIdentitySchema, stepSchema, submissionSchema } from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
const base = {
|
||||
version: z.literal(1),
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
verifyCandidateExecution,
|
||||
} from '@stock-bot/trading-runtime/candidate-environment';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
|
||||
import type { ReplaySubmissionOutcome } from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
candidateResponseSchema,
|
||||
readCandidateFrames,
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Shared read-only artifact inspection. */
|
||||
export * from '@stock-bot/trading-runtime/canonical-build';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint for the shared, purely statistical report builder. */
|
||||
export * from '@stock-bot/research/results';
|
||||
|
|
@ -4,10 +4,6 @@ import type {
|
|||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import type { DatasetResolver } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
/** Capabilities required by the canonical durable runner. No provider loading or playback. */
|
||||
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
|
||||
|
|
@ -26,18 +22,6 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
|
|||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Retained algorithm/playback examples only; cannot satisfy the durable runner contract. */
|
||||
export interface LegacyBacktestExecutionEngine
|
||||
extends Pick<BacktestExecutionEngine, 'on' | 'off' | 'stopBacktest' | 'getStatus' | 'shutdown'> {
|
||||
runBacktest(
|
||||
config: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<BacktestResult | NativeBacktestResult>;
|
||||
pauseBacktest(): Promise<void>;
|
||||
resumeBacktest(): Promise<void>;
|
||||
setSpeedMultiplier(speed: number | null): void;
|
||||
}
|
||||
|
||||
/** Cancellation has no result when a native worker is forcibly stopped. */
|
||||
export class BacktestCancelledError extends Error {
|
||||
constructor() {
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ import {
|
|||
type ReplayStep,
|
||||
type ReplaySubmissionOutcome,
|
||||
type ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { validateDatasetV2 } from '../data/historical-dataset-v2';
|
||||
|
||||
export type {
|
||||
|
|
@ -47,7 +47,7 @@ export type {
|
|||
DecisionContext,
|
||||
PublishedObservation,
|
||||
ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
/** Expand Number's exact shortest lexical representation, never round toFixed.
|
||||
* D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import type { BacktestConfig } from '../types';
|
||||
import { backtestStrategies } from './strategy-plan';
|
||||
|
||||
/** Resolve and validate before fetching data, and validate again in the isolated worker. */
|
||||
export function resolveNativeStrategies(config: BacktestConfig) {
|
||||
return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => {
|
||||
if (!kind) {
|
||||
throw new Error('Unknown native strategy: ' + name);
|
||||
}
|
||||
return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters };
|
||||
});
|
||||
}
|
||||
|
|
@ -12,10 +12,10 @@ import {
|
|||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { replayTraceSchema } from '../contracts/native-replay';
|
||||
import type { ReplayReportResult } from '../contracts/native-replay';
|
||||
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
|
||||
import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
|
||||
import { buildCanonicalBacktestReport } from './canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
|
||||
const finite = z.number().finite();
|
||||
export const retainedStrategyRequestSchema = z
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import {
|
|||
verifyRetainedProgramPackage,
|
||||
} from '../strategies/retained-program';
|
||||
import { IsolatedCandidateController } from './candidate-sandbox';
|
||||
import { verifyCanonicalWorkerBuild } from './canonical-build';
|
||||
import { buildCanonicalBacktestReport } from './canonical-result';
|
||||
import { verifyCanonicalWorkerBuild } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
NativeReplaySession,
|
||||
|
|
|
|||
|
|
@ -1,121 +0,0 @@
|
|||
import { formatStatistic } from '@stock-bot/calculations/analytics';
|
||||
import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import type { ClosedTrade } from './native-result';
|
||||
|
||||
export interface ReportExport {
|
||||
summary: PerformanceMetrics;
|
||||
trades: ClosedTrade[];
|
||||
equityCurve: { timestamp: number; value: number }[];
|
||||
drawdowns: { timestamp: number; value: number }[];
|
||||
dataQuality: unknown;
|
||||
performanceReport: string;
|
||||
}
|
||||
|
||||
export function formatReport(result: ReportExport, format: 'json' | 'csv' | 'html'): string {
|
||||
switch (format) {
|
||||
case 'json':
|
||||
return JSON.stringify(result, null, 2);
|
||||
case 'csv':
|
||||
return convertToCSV(result);
|
||||
case 'html':
|
||||
return generateHTMLReport(result);
|
||||
default:
|
||||
throw new Error(`Unsupported backtest export format: ${format}`);
|
||||
}
|
||||
}
|
||||
|
||||
function csvCell(value: string | number): string {
|
||||
let text = String(value);
|
||||
// Text is not a spreadsheet formula; numeric losses remain ordinary numbers.
|
||||
if (typeof value === 'string' && /^[=+\-@\t\r]/.test(text)) {
|
||||
text = "'" + text;
|
||||
}
|
||||
return /[",\r\n]/.test(text) ? '"' + text.replaceAll('"', '""') + '"' : text;
|
||||
}
|
||||
|
||||
function escapeHTML(value: string): string {
|
||||
return value.replace(
|
||||
/[&<>"']/g,
|
||||
char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char
|
||||
);
|
||||
}
|
||||
|
||||
export function convertToCSV(result: ReportExport): string {
|
||||
// Simple CSV conversion for trades
|
||||
const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%'];
|
||||
const rows = result.trades.map(t => [
|
||||
new Date(String(t.entry_time)).toISOString(),
|
||||
t.symbol,
|
||||
t.side === 'Buy' ? 'buy' : 'sell',
|
||||
t.entry_price,
|
||||
t.exit_price,
|
||||
t.quantity,
|
||||
t.pnl,
|
||||
t.pnl_percent,
|
||||
]);
|
||||
|
||||
return [headers, ...rows].map(row => row.map(csvCell).join(',')).join('\n');
|
||||
}
|
||||
|
||||
export function generateHTMLReport(result: ReportExport): string {
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Backtest Report</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; margin: 20px; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
||||
th { background-color: #f2f2f2; }
|
||||
.metric { margin: 10px 0; }
|
||||
.positive { color: green; }
|
||||
.negative { color: red; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Backtest Performance Report</h1>
|
||||
|
||||
<h2>Summary Statistics</h2>
|
||||
<div class="metric">Total Return: <span class="${result.summary.totalReturn >= 0 ? 'positive' : 'negative'}">${result.summary.totalReturn.toFixed(2)}%</span></div>
|
||||
<div class="metric">Sharpe Ratio: ${formatStatistic(result.summary.sharpeRatio)}</div>
|
||||
<div class="metric">Max Drawdown: <span class="negative">${(result.summary.maxDrawdown * 100).toFixed(2)}%</span></div>
|
||||
<div class="metric">Win Rate: ${result.summary.winRate.toFixed(1)}%</div>
|
||||
<div class="metric">Total Trades: ${result.summary.totalTrades}</div>
|
||||
|
||||
<h2>Detailed Performance Metrics</h2>
|
||||
<pre>${escapeHTML(result.performanceReport)}</pre>
|
||||
|
||||
<h2>Trade History</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>Symbol</th>
|
||||
<th>Side</th>
|
||||
<th>Entry Price</th>
|
||||
<th>Exit Price</th>
|
||||
<th>Quantity</th>
|
||||
<th>P&L</th>
|
||||
<th>Return %</th>
|
||||
</tr>
|
||||
${result.trades
|
||||
.map(
|
||||
t => `
|
||||
<tr>
|
||||
<td>${new Date(t.entry_time).toISOString().slice(0, 10)}</td>
|
||||
<td>${escapeHTML(t.symbol)}</td>
|
||||
<td>${t.side}</td>
|
||||
<td>$${t.entry_price.toFixed(2)}</td>
|
||||
<td>$${t.exit_price.toFixed(2)}</td>
|
||||
<td>${t.quantity}</td>
|
||||
<td class="${t.pnl >= 0 ? 'positive' : 'negative'}">$${t.pnl.toFixed(2)}</td>
|
||||
<td class="${t.pnl_percent >= 0 ? 'positive' : 'negative'}">${t.pnl_percent.toFixed(2)}%</td>
|
||||
</tr>
|
||||
`
|
||||
)
|
||||
.join('')}
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
|
@ -1,200 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { datasetManifestSchema } from '../contracts/historical';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { RunIdentity } from './run-repository';
|
||||
import type { BacktestResult as TypeScriptResult } from './typescript-result';
|
||||
|
||||
const finite = z.number().finite();
|
||||
const analyticsSchema = z.object({
|
||||
exposureTime: finite,
|
||||
drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(),
|
||||
dailyReturns: z.array(finite).optional(),
|
||||
monthlyReturns: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite.nullable()).optional(),
|
||||
});
|
||||
/** Validate once before persistence and before publishing a terminal result. */
|
||||
export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
||||
runId: z.string().uuid(),
|
||||
backtestId: z.string().uuid(),
|
||||
engine: z.enum(['native', 'typescript']),
|
||||
status: z.enum(['completed', 'cancelled']),
|
||||
completedAt: z.string().datetime(),
|
||||
config: z.object({
|
||||
name: z.string(),
|
||||
strategy: z.string(),
|
||||
symbols: z.array(z.string()),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
initialCapital: finite,
|
||||
commission: finite,
|
||||
slippage: finite,
|
||||
dataFrequency: z.string(),
|
||||
parameters: z.record(z.unknown()),
|
||||
dataset: datasetManifestSchema.optional(),
|
||||
riskLimits: z
|
||||
.object({
|
||||
maxPositionSize: finite,
|
||||
maxOrderSize: finite,
|
||||
maxDailyLoss: finite,
|
||||
maxGrossExposure: finite,
|
||||
maxSymbolExposure: finite,
|
||||
})
|
||||
.optional(),
|
||||
strategies: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
enabled: z.boolean(),
|
||||
config: z.record(z.unknown()).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
metrics: z
|
||||
.object({
|
||||
totalReturn: finite,
|
||||
sharpeRatio: finite.nullable(),
|
||||
maxDrawdown: finite,
|
||||
winRate: finite,
|
||||
totalTrades: finite,
|
||||
profitFactor: finite.nullable(),
|
||||
avgWin: finite,
|
||||
avgLoss: finite,
|
||||
})
|
||||
.catchall(finite.nullable()),
|
||||
equity: z.array(z.object({ date: z.string(), value: finite })),
|
||||
ohlcData: z.record(
|
||||
z.array(
|
||||
z.object({
|
||||
timestamp: finite,
|
||||
open: finite,
|
||||
high: finite,
|
||||
low: finite,
|
||||
close: finite,
|
||||
volume: finite.optional(),
|
||||
})
|
||||
)
|
||||
),
|
||||
trades: z.array(
|
||||
z.object({
|
||||
kind: z.enum(['fill', 'closed']),
|
||||
id: z.string(),
|
||||
symbol: z.string(),
|
||||
timestamp: z.string(),
|
||||
side: z.enum(['buy', 'sell']),
|
||||
price: finite,
|
||||
quantity: finite,
|
||||
commission: finite,
|
||||
pnl: finite.optional(),
|
||||
positionAfter: finite.optional(),
|
||||
entryDate: z.string().optional(),
|
||||
exitDate: z.string().nullable().optional(),
|
||||
entryPrice: finite.optional(),
|
||||
exitPrice: finite.optional(),
|
||||
pnlPercent: finite.optional(),
|
||||
duration: finite.optional(),
|
||||
})
|
||||
),
|
||||
positions: z.array(
|
||||
z.object({
|
||||
symbol: z.string(),
|
||||
quantity: finite,
|
||||
averagePrice: finite,
|
||||
currentPrice: finite,
|
||||
unrealizedPnl: finite,
|
||||
realizedPnl: finite,
|
||||
})
|
||||
),
|
||||
analytics: analyticsSchema,
|
||||
executionTime: finite.nonnegative(),
|
||||
});
|
||||
|
||||
export function normalizeBacktestResult(
|
||||
raw: NativeBacktestResult | TypeScriptResult,
|
||||
engine: Exclude<BacktestRunResult['engine'], 'legacy'>,
|
||||
config: BacktestConfig,
|
||||
identity: RunIdentity,
|
||||
executionTime: number,
|
||||
cancelled: boolean,
|
||||
dataset?: HistoricalDatasetManifest
|
||||
): BacktestRunResult {
|
||||
if (raw.status !== 'completed' && raw.status !== 'cancelled') {
|
||||
throw new Error(
|
||||
'error' in raw && typeof raw.error === 'string'
|
||||
? raw.error
|
||||
: `Backtest engine returned ${raw.status}`
|
||||
);
|
||||
}
|
||||
const trades = raw.trades.map(trade =>
|
||||
'entryDate' in trade
|
||||
? {
|
||||
...trade,
|
||||
kind: 'closed',
|
||||
timestamp: trade.entryDate,
|
||||
price: trade.entryPrice,
|
||||
}
|
||||
: { ...trade, kind: 'fill' }
|
||||
);
|
||||
// Native serialization uses null for undefined ratios; do the same for TS infinities.
|
||||
const metrics = Object.fromEntries(
|
||||
Object.entries(raw.metrics).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === 'number' && !Number.isFinite(value) ? null : value,
|
||||
])
|
||||
);
|
||||
// Public returns/win rates are fractions, not percentage points. Both backends
|
||||
// already report maxDrawdown as a fraction.
|
||||
metrics.totalReturn = raw.metrics.totalReturn / 100;
|
||||
metrics.winRate = raw.metrics.winRate / 100;
|
||||
if (engine === 'typescript') {
|
||||
metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills.
|
||||
metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
for (const key of ['annualReturn', 'annualizedReturn', 'cagr']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
const analytics = analyticsSchema.parse(raw.analytics);
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value =>
|
||||
engine === 'typescript' ? value / 100 : value
|
||||
);
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
return backtestRunResultSchema.parse({
|
||||
...raw,
|
||||
...identity,
|
||||
engine,
|
||||
completedAt: new Date(raw.completedAt).toISOString(),
|
||||
status: cancelled ? 'cancelled' : raw.status,
|
||||
executionTime,
|
||||
config: {
|
||||
name: config.name ?? 'Backtest',
|
||||
strategy: config.strategy,
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
commission: config.commission ?? 0.001,
|
||||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency,
|
||||
parameters: config.config ?? {},
|
||||
dataset,
|
||||
riskLimits: config.riskLimits,
|
||||
strategies: config.strategies,
|
||||
},
|
||||
metrics,
|
||||
trades,
|
||||
analytics,
|
||||
});
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
import { normalizeBacktestStrategyConfig } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
nativeParameters,
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../contracts/strategies';
|
||||
import { builtinStrategy } from '../contracts/strategy-names';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
/** One precedence rule for both backends: shared defaults, then per-strategy overrides. */
|
||||
export function backtestStrategies(config: BacktestConfig, backend: 'native' | 'typescript') {
|
||||
const entries = config.strategies ?? [{ name: config.strategy, enabled: true, config: {} }];
|
||||
if (!entries.some(entry => entry.enabled)) {
|
||||
throw new Error('No enabled backtest strategies');
|
||||
}
|
||||
return entries
|
||||
.filter(entry => entry.enabled)
|
||||
.map((entry, index) => {
|
||||
const kind = builtinStrategy(entry.name);
|
||||
const merged = { ...config.config, ...entry.config };
|
||||
// Built-ins cross the shared execution/parameter boundary once, after merging defaults.
|
||||
// Custom TypeScript factories retain their historical, factory-owned extension contract.
|
||||
const input = kind
|
||||
? normalizeBacktestStrategyConfig(merged)
|
||||
: { parameters: structuredClone(merged) };
|
||||
const { parameters } = input;
|
||||
if (backend === 'native') {
|
||||
if (!kind) {
|
||||
throw new Error(`Unknown native strategy: ${entry.name}`);
|
||||
}
|
||||
if (input.useTypeScriptImplementation) {
|
||||
throw new Error('The native engine does not execute TypeScript strategy callbacks');
|
||||
}
|
||||
const parsed = nativeParameters(kind, parameters);
|
||||
if (
|
||||
kind === 'pairs_trading' &&
|
||||
(typeof parsed.pairA !== 'string' ||
|
||||
typeof parsed.pairB !== 'string' ||
|
||||
!config.symbols.includes(parsed.pairA) ||
|
||||
!config.symbols.includes(parsed.pairB))
|
||||
) {
|
||||
throw new Error('Both pair instruments must be included in backtest symbols');
|
||||
}
|
||||
return { name: entry.name, kind, index, parameters: parsed };
|
||||
}
|
||||
const context = { ...parameters, initialCapital: config.initialCapital };
|
||||
const parsed =
|
||||
kind === 'sma_crossover'
|
||||
? typescriptSmaParameters.parse(context)
|
||||
: kind === 'mean_reversion'
|
||||
? typescriptMeanReversionParameters.parse(context)
|
||||
: context;
|
||||
return { name: entry.name, kind, index, parameters: parsed };
|
||||
});
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import type {
|
|||
DeepReadonly,
|
||||
StrategyDiagnosticSnapshot,
|
||||
StrategyProgram,
|
||||
} from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import {
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
|
|
@ -12,7 +12,7 @@ import {
|
|||
type ReplayProjectionResult,
|
||||
type ReplayReportResult,
|
||||
type ReplayResult,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
import {
|
||||
|
|
@ -23,7 +23,7 @@ import {
|
|||
type ReplayOptions,
|
||||
} from './native-replay';
|
||||
|
||||
export type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
export type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
export type StrategyReplayOptions = Omit<ReplayOptions, 'reverseCallbacks'>;
|
||||
type StrategyRun<Result extends ReplayOutput> = {
|
||||
result: Result;
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
/** Internal TypeScript backend output; normalized to BacktestRunResult by the runner. */
|
||||
export interface OHLCBar {
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
export interface BacktestResult {
|
||||
// Identification
|
||||
backtestId: string;
|
||||
status: 'completed' | 'failed' | 'cancelled';
|
||||
completedAt: string;
|
||||
|
||||
// Configuration
|
||||
config: {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
dataFrequency: string;
|
||||
};
|
||||
|
||||
// Performance metrics
|
||||
metrics: {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
totalTrades: number;
|
||||
profitFactor: number | null;
|
||||
profitableTrades: number;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
expectancy: number;
|
||||
calmarRatio: number | null;
|
||||
sortinoRatio: number | null;
|
||||
annualizedReturn: number | null;
|
||||
cagr: number | null;
|
||||
};
|
||||
|
||||
// Chart data
|
||||
equity: Array<{ date: string; value: number }>;
|
||||
ohlcData: Record<string, OHLCBar[]>;
|
||||
|
||||
// Trade history
|
||||
trades: Array<{
|
||||
id: string;
|
||||
symbol: string;
|
||||
entryDate: string;
|
||||
exitDate: string | null;
|
||||
entryPrice: number;
|
||||
exitPrice: number;
|
||||
quantity: number;
|
||||
side: string;
|
||||
pnl: number;
|
||||
pnlPercent: number;
|
||||
commission: number;
|
||||
duration: number;
|
||||
}>;
|
||||
|
||||
// Positions
|
||||
positions: Array<{
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
averagePrice: number;
|
||||
currentPrice: number;
|
||||
unrealizedPnl: number;
|
||||
realizedPnl: number;
|
||||
}>;
|
||||
|
||||
// Analytics
|
||||
analytics: {
|
||||
drawdownSeries: { timestamp: number; value: number }[];
|
||||
dailyReturns: number[];
|
||||
monthlyReturns: Record<string, number>;
|
||||
exposureTime: number;
|
||||
riskMetrics: Record<string, number | null>;
|
||||
};
|
||||
}
|
||||
|
|
@ -6,14 +6,13 @@ import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRep
|
|||
import { assertResearchConcurrency, ResearchBacktestPool } from './backtest/ResearchBacktestPool';
|
||||
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
||||
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
||||
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
|
||||
import type { PaperConfigurationInput, PaperRuntime } from '@stock-bot/stock-config/paper-runtime';
|
||||
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
|
||||
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
||||
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import { PaperDeploymentHost } from './paper/PaperDeploymentHost';
|
||||
import { AnalyticsService } from './services/AnalyticsService';
|
||||
import { StorageService } from './services/StorageService';
|
||||
import { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import { createBuiltinStrategy } from './strategies/canonical-builtins';
|
||||
import { stopOrchestratorWork } from './runtime';
|
||||
import type { OrchestratorServices as IServiceContainer } from './types';
|
||||
|
|
@ -163,12 +162,10 @@ export async function registerOrchestratorServices(
|
|||
),
|
||||
logger: services.logger,
|
||||
});
|
||||
const analytics = new AnalyticsService(services);
|
||||
// Both roles share canonical research. Only an explicitly configured paper
|
||||
// composition owns account custody; startup never activates it.
|
||||
Object.assign(custom, {
|
||||
StorageService: storageService,
|
||||
AnalyticsService: analytics,
|
||||
BacktestRunner: runner,
|
||||
...(paper ? { CanonicalPaperRuntime: paper } : {}),
|
||||
...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}),
|
||||
|
|
@ -176,7 +173,6 @@ export async function registerOrchestratorServices(
|
|||
const canonicalContainer = container as AwilixContainer<
|
||||
ServiceDefinitions & {
|
||||
StorageService: StorageService;
|
||||
AnalyticsService: AnalyticsService;
|
||||
CanonicalPaperRuntime: PaperRuntime;
|
||||
PaperDeploymentHost: PaperDeploymentHost;
|
||||
BacktestRunner: ResearchBacktestPool;
|
||||
|
|
@ -185,7 +181,6 @@ export async function registerOrchestratorServices(
|
|||
>;
|
||||
canonicalContainer.register({
|
||||
StorageService: asValue(storageService),
|
||||
AnalyticsService: asValue(analytics),
|
||||
BacktestRunner: asValue(runner),
|
||||
orchestratorServices: asValue(services),
|
||||
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
|
||||
|
|
|
|||
|
|
@ -1,149 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
const finite = z.number().finite();
|
||||
const optionalRatio = finite.nullable();
|
||||
const symbols = z
|
||||
.array(z.string().trim().min(1).max(128))
|
||||
.min(1)
|
||||
.max(128)
|
||||
.refine(values => new Set(values).size === values.length, 'Duplicate symbols');
|
||||
export const PerformanceMetricsSchema = z.object({
|
||||
totalReturn: finite,
|
||||
sharpeRatio: optionalRatio,
|
||||
sortinoRatio: optionalRatio,
|
||||
maxDrawdown: finite.nonnegative(),
|
||||
winRate: finite.min(0).max(1),
|
||||
profitFactor: finite.nonnegative().nullable(),
|
||||
avgWin: finite.nonnegative(),
|
||||
avgLoss: finite.nonnegative(),
|
||||
totalTrades: finite.int().nonnegative(),
|
||||
});
|
||||
export type PerformanceMetrics = z.infer<typeof PerformanceMetricsSchema>;
|
||||
export const RiskMetricsSchema = z.object({
|
||||
currentExposure: finite.nonnegative(),
|
||||
dailyPnl: finite,
|
||||
positionCount: finite.int().nonnegative(),
|
||||
grossExposure: finite.nonnegative(),
|
||||
var95: finite.nonnegative().nullable().optional(),
|
||||
cvar95: finite.nonnegative().nullable().optional(),
|
||||
});
|
||||
export type RiskMetrics = z.infer<typeof RiskMetricsSchema>;
|
||||
export const dateRangeSchema = z
|
||||
.object({ startDate: z.string().datetime(), endDate: z.string().datetime() })
|
||||
.refine(
|
||||
value => Date.parse(value.endDate) > Date.parse(value.startDate),
|
||||
'endDate must follow startDate'
|
||||
);
|
||||
export const optimizationRequestSchema = z
|
||||
.object({
|
||||
symbols,
|
||||
returns: z.array(z.array(finite).min(1).max(128)).min(2).max(100000),
|
||||
constraints: z
|
||||
.object({
|
||||
minWeight: finite.min(0).max(1).optional(),
|
||||
maxWeight: finite.min(0).max(1).optional(),
|
||||
targetReturn: finite.optional(),
|
||||
maxRisk: finite.nonnegative().optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
value => value.returns.every(row => row.length === value.symbols.length),
|
||||
'Returns must have one column per symbol'
|
||||
)
|
||||
.refine(
|
||||
value => (value.constraints?.minWeight ?? 0) <= (value.constraints?.maxWeight ?? 1),
|
||||
'Invalid weight bounds'
|
||||
)
|
||||
.refine(
|
||||
value =>
|
||||
(value.constraints?.minWeight ?? 0) * value.symbols.length <= 1 &&
|
||||
(value.constraints?.maxWeight ?? 1) * value.symbols.length >= 1,
|
||||
'Infeasible weight bounds'
|
||||
);
|
||||
export type OptimizationParams = z.infer<typeof optimizationRequestSchema>;
|
||||
export const portfolioWeightsSchema = z
|
||||
.object({
|
||||
symbols,
|
||||
weights: z.array(finite.min(0).max(1)).min(1).max(128),
|
||||
expected_return: finite,
|
||||
expected_risk: finite.nonnegative(),
|
||||
sharpe_ratio: optionalRatio,
|
||||
})
|
||||
.refine(
|
||||
value =>
|
||||
value.weights.length === value.symbols.length &&
|
||||
Math.abs(value.weights.reduce((sum, weight) => sum + weight, 0) - 1) <= 1e-6,
|
||||
'Invalid portfolio weights'
|
||||
);
|
||||
export const correlationRequestSchema = z.object({
|
||||
symbols: symbols.refine(values => values.length >= 2, 'At least two symbols are required'),
|
||||
});
|
||||
export const correlationResponseSchema = z
|
||||
.object({
|
||||
symbols,
|
||||
matrix: z.array(z.array(finite.min(-1).max(1)).max(128)).max(128),
|
||||
})
|
||||
.refine(value => {
|
||||
const size = value.symbols.length;
|
||||
if (value.matrix.length !== size || value.matrix.some(row => row.length !== size)) {
|
||||
return false;
|
||||
}
|
||||
const lower = Array.from({ length: size }, () => Array<number>(size).fill(0));
|
||||
for (let i = 0; i < size; i++) {
|
||||
if (Math.abs((value.matrix[i]?.[i] ?? 0) - 1) > 1e-8) {
|
||||
return false;
|
||||
}
|
||||
for (let j = 0; j <= i; j++) {
|
||||
const input = value.matrix[i]?.[j] ?? 0;
|
||||
if (Math.abs(input - (value.matrix[j]?.[i] ?? 0)) > 1e-8) {
|
||||
return false;
|
||||
}
|
||||
let residual = input;
|
||||
for (let k = 0; k < j; k++) {
|
||||
residual -= (lower[i]?.[k] ?? 0) * (lower[j]?.[k] ?? 0);
|
||||
}
|
||||
const row = lower[i];
|
||||
if (!row) {
|
||||
return false;
|
||||
}
|
||||
if (i === j) {
|
||||
if (residual < -1e-8) {
|
||||
return false;
|
||||
}
|
||||
row[j] = Math.sqrt(Math.max(0, residual));
|
||||
} else {
|
||||
const diagonal = lower[j]?.[j] ?? 0;
|
||||
if (diagonal > 1e-8) {
|
||||
row[j] = residual / diagonal;
|
||||
} else if (Math.abs(residual) > 1e-8) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}, 'Invalid correlation matrix');
|
||||
type Json = null | boolean | string | number | Json[] | { [key: string]: Json };
|
||||
const json: z.ZodType<Json> = z.lazy(() =>
|
||||
z.union([z.null(), z.boolean(), z.string(), finite, z.array(json), z.record(json)])
|
||||
);
|
||||
export const predictionRequestSchema = z
|
||||
.object({ modelId: z.string().min(1).max(128), features: z.record(finite) })
|
||||
.strict();
|
||||
export const predictionResponseSchema = z.object({
|
||||
model_id: z.string().min(1),
|
||||
prediction: finite,
|
||||
probability: z.record(finite.min(0).max(1)).nullable().optional(),
|
||||
metadata: z.record(json).nullable().optional(),
|
||||
});
|
||||
export const backtestAnalysisSchema = z.object({
|
||||
backtest_id: z.string().min(1),
|
||||
metrics: z.record(optionalRatio),
|
||||
statistics: z.record(optionalRatio),
|
||||
risk_analysis: z.record(optionalRatio),
|
||||
trade_analysis: z.record(optionalRatio),
|
||||
});
|
||||
export const regimeResponseSchema = z.object({ regime: z.string().trim().min(1).max(128) });
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
/** Compatibility export: canonical validation is shared with the research API. */
|
||||
export {
|
||||
smaStrategySelectionSchema,
|
||||
meanReversionStrategySelectionSchema,
|
||||
builtinStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
type MeanReversionStrategySelection,
|
||||
type MeanReversionSignalParameters,
|
||||
type BuiltinStrategySelection,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Shared financial wire contract. */
|
||||
export * from '@stock-bot/stock-config/canonical-execution';
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
/** Compatibility type export. Authors use @stock-bot/research/strategy-api. */
|
||||
export type {
|
||||
DeepReadonly,
|
||||
StrategyAdmissionFeedback,
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
StrategyDiagnostic,
|
||||
StrategyDiagnosticSnapshot,
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility export: pure financial replay contracts are shared with research APIs. */
|
||||
export * from '@stock-bot/stock-config/canonical-replay';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Shared financial wire contract. */
|
||||
export * from '@stock-bot/stock-config/paper-runtime';
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import { maxStrategyPeriod } from '@stock-bot/stock-config/strategy';
|
||||
import { instrumentIdSchema } from './historical';
|
||||
import type { BuiltinStrategy } from './strategy-names';
|
||||
|
||||
export { maxStrategyPeriod };
|
||||
const period = z.number().finite().int().min(1).max(maxStrategyPeriod);
|
||||
const positive = z.number().finite().positive();
|
||||
const quantity = positive.min(1e-8).max(1e9);
|
||||
const context = {
|
||||
initialCapital: positive.optional(),
|
||||
symbols: z.array(z.string()).optional(),
|
||||
};
|
||||
const smaPeriods = { fastPeriod: period.default(5), slowPeriod: period.min(2).default(15) };
|
||||
const validSma = (value: { fastPeriod: number; slowPeriod: number }) =>
|
||||
value.fastPeriod < value.slowPeriod;
|
||||
const smaMessage = 'SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000';
|
||||
|
||||
export const typescriptSmaParameters = z
|
||||
.object({
|
||||
...context,
|
||||
...smaPeriods,
|
||||
positionFraction: positive.max(1).default(0.1),
|
||||
minHoldingBars: z.number().int().min(0).max(maxStrategyPeriod).default(3),
|
||||
quantity: quantity.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(validSma, smaMessage);
|
||||
export const nativeSmaParameters = z
|
||||
.object({ ...smaPeriods, quantity: quantity.default(100) })
|
||||
.strict()
|
||||
.refine(validSma, smaMessage);
|
||||
export type SmaParameters = z.infer<typeof typescriptSmaParameters>;
|
||||
|
||||
export const typescriptMeanReversionParameters = z
|
||||
.object({
|
||||
...context,
|
||||
lookbackPeriod: period.min(2).default(20),
|
||||
trendPeriod: period.optional(),
|
||||
entryThreshold: positive.default(2),
|
||||
exitZScore: z.number().finite().min(0).default(0.5),
|
||||
rsiPeriod: period.default(14),
|
||||
rsiOversold: z.number().finite().min(0).max(100).default(30),
|
||||
rsiOverbought: z.number().finite().min(0).max(100).default(70),
|
||||
minNotionalVolume: z.number().finite().min(0).default(1000000),
|
||||
quantity: quantity.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
value => value.exitZScore < value.entryThreshold,
|
||||
'exitZScore must be below entryThreshold'
|
||||
)
|
||||
.refine(
|
||||
value => value.rsiOversold < value.rsiOverbought,
|
||||
'rsiOversold must be below rsiOverbought'
|
||||
)
|
||||
.refine(
|
||||
value => value.trendPeriod === undefined || value.trendPeriod >= value.lookbackPeriod,
|
||||
'trendPeriod must be at least lookbackPeriod'
|
||||
)
|
||||
.transform(value => ({
|
||||
...value,
|
||||
trendPeriod: value.trendPeriod ?? Math.max(50, value.lookbackPeriod),
|
||||
}));
|
||||
export type MeanReversionParameters = z.infer<typeof typescriptMeanReversionParameters>;
|
||||
|
||||
const nativeMean = {
|
||||
lookbackPeriod: period.min(2).default(20),
|
||||
entryThreshold: positive.default(2),
|
||||
// Native mean/momentum/pairs retain their existing absolute-share positionSize contract.
|
||||
positionSize: quantity.default(100),
|
||||
};
|
||||
export const nativeMeanReversionParameters = z.object(nativeMean).strict();
|
||||
export const nativeMomentumParameters = z
|
||||
.object({
|
||||
lookbackPeriod: period.default(14),
|
||||
momentumThreshold: positive.default(5),
|
||||
positionSize: quantity.default(100),
|
||||
})
|
||||
.strict();
|
||||
export const nativePairsParameters = z
|
||||
.object({
|
||||
...nativeMean,
|
||||
pairA: instrumentIdSchema,
|
||||
pairB: instrumentIdSchema,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.pairA !== value.pairB, 'Pairs must use distinct instruments');
|
||||
|
||||
export function nativeParameters(
|
||||
kind: BuiltinStrategy,
|
||||
input: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
switch (kind) {
|
||||
case 'sma_crossover':
|
||||
return nativeSmaParameters.parse(input);
|
||||
case 'mean_reversion':
|
||||
return nativeMeanReversionParameters.parse(input);
|
||||
case 'momentum':
|
||||
return nativeMomentumParameters.parse(input);
|
||||
case 'pairs_trading':
|
||||
return nativePairsParameters.parse(input);
|
||||
default:
|
||||
throw new Error(`Unsupported native strategy: ${kind}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
export {
|
||||
normalizeStrategyName,
|
||||
strategyAliases,
|
||||
builtinStrategy,
|
||||
type BuiltinStrategy,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
/** Data-only trusted built-in execution protocol; no strategy code or native imports. */
|
||||
import { z } from 'zod';
|
||||
import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from './builtin-strategy';
|
||||
import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
parseReplayProjectionValue,
|
||||
parseReplayReportValue,
|
||||
|
|
@ -11,7 +11,7 @@ import {
|
|||
type ReplayIdentity,
|
||||
type ReplayOutput,
|
||||
type ReplayResultFormat,
|
||||
} from './native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
export const strategyReplayRequestSchema = z
|
||||
.object({
|
||||
|
|
|
|||
|
|
@ -1,221 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { MarketDataService } from '../services/MarketDataService';
|
||||
import type { StrategyManager } from '../strategies/StrategyManager';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
PaperConfigSchema,
|
||||
type ModeConfig,
|
||||
type TradingMode,
|
||||
} from '../types';
|
||||
|
||||
const shutdownOrder = ['marketData', 'strategies', 'execution'] as const;
|
||||
type LifecycleService = (typeof shutdownOrder)[number];
|
||||
|
||||
export class ModeManager extends EventEmitter {
|
||||
private mode: TradingMode = 'paper';
|
||||
private config: ModeConfig | null = null;
|
||||
private tradingEngine: TradingEngine | null = null;
|
||||
private isInitialized = false;
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
allowedMode?: 'paper' | 'backtest';
|
||||
logger: Pick<Logger, 'info'>;
|
||||
marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
|
||||
execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
|
||||
strategies: Pick<StrategyManager, 'restoreStrategies' | 'shutdown'>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async initializeMode(config: ModeConfig): Promise<void> {
|
||||
if (config.mode === 'live') {
|
||||
throw new Error('Live trading is disabled: no real broker adapter exists');
|
||||
}
|
||||
if (this.dependencies.allowedMode && config.mode !== this.dependencies.allowedMode) {
|
||||
throw new Error(
|
||||
`Runtime composition only permits ${this.dependencies.allowedMode} mode; cannot initialize ${config.mode}`
|
||||
);
|
||||
}
|
||||
// Validate config based on mode
|
||||
switch (config.mode) {
|
||||
case 'backtest':
|
||||
BacktestConfigSchema.parse(config);
|
||||
break;
|
||||
case 'paper':
|
||||
PaperConfigSchema.parse(config);
|
||||
break;
|
||||
}
|
||||
|
||||
// Shutdown current mode if initialized
|
||||
if (this.isInitialized) {
|
||||
await this.shutdown();
|
||||
}
|
||||
|
||||
const attempted = new Set<LifecycleService>();
|
||||
try {
|
||||
this.mode = config.mode;
|
||||
this.config = config;
|
||||
|
||||
// Create Rust trading engine with appropriate config
|
||||
const engineConfig = this.createEngineConfig(config);
|
||||
this.tradingEngine = new TradingEngine(config.mode, engineConfig);
|
||||
|
||||
await this.initializeServices(config, attempted);
|
||||
} catch (error) {
|
||||
try {
|
||||
await this.shutdownServices(attempted);
|
||||
} catch {
|
||||
// Every cleanup was attempted; preserve the original initialization error.
|
||||
} finally {
|
||||
this.clearState();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.isInitialized = true;
|
||||
this.emit('modeChanged', config);
|
||||
|
||||
this.dependencies.logger.info(`Trading mode initialized: ${config.mode}`);
|
||||
}
|
||||
|
||||
private createEngineConfig(config: ModeConfig) {
|
||||
switch (config.mode) {
|
||||
case 'backtest':
|
||||
return {
|
||||
startTime: new Date(config.startDate).getTime(),
|
||||
endTime: new Date(config.endDate).getTime(),
|
||||
speedMultiplier: this.getSpeedMultiplier(config.speed),
|
||||
initialCapital: config.initialCapital,
|
||||
};
|
||||
case 'paper':
|
||||
return {
|
||||
startingCapital: config.startingCapital,
|
||||
};
|
||||
case 'live':
|
||||
return {
|
||||
broker: config.broker,
|
||||
accountId: config.accountId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private getSpeedMultiplier(speed: string): number {
|
||||
switch (speed) {
|
||||
case 'max':
|
||||
return 0;
|
||||
case 'realtime':
|
||||
return 1;
|
||||
case '2x':
|
||||
return 2;
|
||||
case '5x':
|
||||
return 5;
|
||||
case '10x':
|
||||
return 10;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeServices(
|
||||
config: ModeConfig,
|
||||
attempted: Set<LifecycleService>
|
||||
): Promise<void> {
|
||||
// Register before each await: an initializer may acquire resources then fail.
|
||||
// Configure execution service
|
||||
attempted.add('execution');
|
||||
await this.dependencies.execution.initialize(config, defined(this.tradingEngine));
|
||||
|
||||
if (config.mode === 'paper') {
|
||||
attempted.add('strategies');
|
||||
await this.dependencies.strategies.restoreStrategies();
|
||||
}
|
||||
// Admission is ready before a real-time feed can deliver events.
|
||||
attempted.add('marketData');
|
||||
await this.dependencies.marketData.initialize(config);
|
||||
}
|
||||
|
||||
private async shutdownServices(attempted: ReadonlySet<LifecycleService>): Promise<void> {
|
||||
let failed = false;
|
||||
let failure: unknown;
|
||||
for (const service of shutdownOrder) {
|
||||
if (!attempted.has(service)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await this.dependencies[service].shutdown();
|
||||
} catch (error) {
|
||||
if (!failed) {
|
||||
failure = error;
|
||||
}
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
if (failed) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private clearState(): void {
|
||||
this.tradingEngine = null;
|
||||
this.config = null;
|
||||
this.isInitialized = false;
|
||||
}
|
||||
|
||||
getCurrentMode(): TradingMode {
|
||||
return this.mode;
|
||||
}
|
||||
|
||||
getConfig(): ModeConfig | null {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
getTradingEngine(): TradingEngine {
|
||||
if (!this.tradingEngine) {
|
||||
throw new Error('Trading engine not initialized');
|
||||
}
|
||||
return this.tradingEngine;
|
||||
}
|
||||
|
||||
isBacktestMode(): boolean {
|
||||
return this.mode === 'backtest';
|
||||
}
|
||||
|
||||
isPaperMode(): boolean {
|
||||
return this.mode === 'paper';
|
||||
}
|
||||
|
||||
isLiveMode(): boolean {
|
||||
return this.mode === 'live';
|
||||
}
|
||||
|
||||
async transitionMode(
|
||||
fromMode: TradingMode,
|
||||
toMode: TradingMode,
|
||||
config: ModeConfig
|
||||
): Promise<void> {
|
||||
if (config.mode !== toMode || fromMode !== this.mode) {
|
||||
throw new Error('Mode transition does not match current mode or configuration');
|
||||
}
|
||||
await this.initializeMode(config);
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
if (!this.isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dependencies.logger.info(`Shutting down ${this.mode} mode...`);
|
||||
|
||||
try {
|
||||
await this.shutdownServices(new Set(shutdownOrder));
|
||||
} finally {
|
||||
this.clearState();
|
||||
this.emit('shutdown');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,307 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HistoricalDataset } from '@stock-bot/types';
|
||||
import type { HistoricalBar, StorageService } from '../services/StorageService';
|
||||
import { type Bar, type MarketData } from '../types';
|
||||
|
||||
const logger = getLogger('DataManager');
|
||||
|
||||
export interface DataResolution {
|
||||
interval: string;
|
||||
milliseconds: number;
|
||||
}
|
||||
|
||||
export interface DataQualityIssue {
|
||||
timestamp: Date;
|
||||
symbol: string;
|
||||
issue: string;
|
||||
severity: 'warning' | 'error';
|
||||
details?: unknown;
|
||||
}
|
||||
|
||||
export class DataManager extends EventEmitter {
|
||||
private static RESOLUTIONS: Record<string, DataResolution> = {
|
||||
tick: { interval: 'tick', milliseconds: 0 },
|
||||
'1s': { interval: '1s', milliseconds: 1000 },
|
||||
'5s': { interval: '5s', milliseconds: 5000 },
|
||||
'10s': { interval: '10s', milliseconds: 10000 },
|
||||
'30s': { interval: '30s', milliseconds: 30000 },
|
||||
'1m': { interval: '1m', milliseconds: 60000 },
|
||||
'5m': { interval: '5m', milliseconds: 300000 },
|
||||
'15m': { interval: '15m', milliseconds: 900000 },
|
||||
'30m': { interval: '30m', milliseconds: 1800000 },
|
||||
'1h': { interval: '1h', milliseconds: 3600000 },
|
||||
'4h': { interval: '4h', milliseconds: 14400000 },
|
||||
'1d': { interval: '1d', milliseconds: 86400000 },
|
||||
};
|
||||
|
||||
private dataCache: Map<string, MarketData[]> = new Map();
|
||||
private aggregatedCache: Map<string, Map<string, Bar[]>> = new Map();
|
||||
private dataQualityIssues: DataQualityIssue[] = [];
|
||||
|
||||
constructor(private storageService: Pick<StorageService, 'getHistoricalBars'>) {
|
||||
super();
|
||||
}
|
||||
|
||||
async loadHistoricalData(
|
||||
symbols: string[],
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
resolution: string = '1m',
|
||||
_includeExtendedHours: boolean = false
|
||||
): Promise<Map<string, MarketData[]>> {
|
||||
const result = new Map<string, MarketData[]>();
|
||||
|
||||
for (const symbol of symbols) {
|
||||
try {
|
||||
// Load raw data
|
||||
const data = await this.storageService.getHistoricalBars(
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
resolution
|
||||
);
|
||||
|
||||
if (!data.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
}
|
||||
this.recordQualityWarnings(symbol, data);
|
||||
|
||||
// Storage owns validation and adjustment. Never interpolate or adjust a second time.
|
||||
const marketData = this.convertToMarketData(symbol, data);
|
||||
|
||||
result.set(symbol, marketData);
|
||||
this.dataCache.set(`${symbol}:${resolution}`, marketData);
|
||||
|
||||
logger.info(`Loaded ${marketData.length} bars for ${symbol} at ${resolution} resolution`);
|
||||
} catch (error) {
|
||||
logger.error(`Failed to load data for ${symbol}:`, error);
|
||||
this.emit('dataError', { symbol, error });
|
||||
this.dataCache.clear();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */
|
||||
inspectDataset(dataset: HistoricalDataset): void {
|
||||
this.clearCache();
|
||||
const grouped = new Map<string, HistoricalDataset['bars']>();
|
||||
for (const bar of dataset.bars) {
|
||||
let bars = grouped.get(bar.symbol);
|
||||
if (!bars) {
|
||||
bars = [];
|
||||
grouped.set(bar.symbol, bars);
|
||||
}
|
||||
bars.push(bar);
|
||||
}
|
||||
for (const instrument of dataset.manifest.instruments) {
|
||||
this.recordQualityWarnings(instrument.id, grouped.get(instrument.id) ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
private recordQualityWarnings(
|
||||
symbol: string,
|
||||
bars: readonly { timestamp: Date | number; close: number }[]
|
||||
): void {
|
||||
bars.forEach((bar, index) => {
|
||||
const previous = bars[index - 1];
|
||||
if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) {
|
||||
this.dataQualityIssues.push({
|
||||
timestamp: new Date(bar.timestamp),
|
||||
symbol,
|
||||
issue: 'Price movement exceeds 20%; prices retained unchanged',
|
||||
severity: 'warning',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] {
|
||||
const fromMs = DataManager.RESOLUTIONS[fromResolution]?.milliseconds;
|
||||
const toMs = DataManager.RESOLUTIONS[toResolution]?.milliseconds;
|
||||
|
||||
if (!fromMs || !toMs || fromMs >= toMs) {
|
||||
throw new Error(`Cannot aggregate from ${fromResolution} to ${toResolution}`);
|
||||
}
|
||||
|
||||
const bars: Bar[] = [];
|
||||
let currentBar: Partial<Bar> | null = null;
|
||||
let barStartTime = 0;
|
||||
|
||||
for (const item of data) {
|
||||
if (item.type !== 'bar') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const bar = item.data;
|
||||
const timestamp = bar.timestamp;
|
||||
const alignedTime = Math.floor(timestamp / toMs) * toMs;
|
||||
|
||||
if (!currentBar || alignedTime > barStartTime) {
|
||||
// Finalize previous bar
|
||||
if (currentBar && currentBar.open !== undefined) {
|
||||
bars.push(currentBar as Bar);
|
||||
}
|
||||
|
||||
// Start new bar
|
||||
currentBar = {
|
||||
timestamp: alignedTime,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap,
|
||||
};
|
||||
barStartTime = alignedTime;
|
||||
} else {
|
||||
// Update current bar
|
||||
currentBar.high = Math.max(defined(currentBar.high), bar.high);
|
||||
currentBar.low = Math.min(defined(currentBar.low), bar.low);
|
||||
currentBar.close = bar.close;
|
||||
currentBar.volume = (currentBar.volume ?? 0) + bar.volume;
|
||||
|
||||
// Recalculate VWAP if available
|
||||
if (bar.vwap && currentBar.vwap) {
|
||||
const totalValue =
|
||||
currentBar.vwap * (defined(currentBar.volume) - bar.volume) + bar.vwap * bar.volume;
|
||||
currentBar.vwap = totalValue / defined(currentBar.volume);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add final bar
|
||||
if (currentBar && currentBar.open !== undefined) {
|
||||
bars.push(currentBar as Bar);
|
||||
}
|
||||
|
||||
return bars;
|
||||
}
|
||||
|
||||
downsampleData(data: MarketData[], targetPoints: number): MarketData[] {
|
||||
if (data.length <= targetPoints) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// Use LTTB (Largest Triangle Three Buckets) algorithm
|
||||
const downsampled: MarketData[] = [];
|
||||
const bucketSize = (data.length - 2) / (targetPoints - 2);
|
||||
|
||||
// Always include first point
|
||||
downsampled.push(at(data, 0));
|
||||
|
||||
for (let i = 0; i < targetPoints - 2; i++) {
|
||||
const bucketStart = Math.floor(i * bucketSize) + 1;
|
||||
const bucketEnd = Math.floor((i + 1) * bucketSize) + 1;
|
||||
|
||||
// Find point with maximum area in bucket
|
||||
let maxArea = -1;
|
||||
let maxAreaPoint = 0;
|
||||
|
||||
const prevPoint = at(downsampled, downsampled.length - 1);
|
||||
const prevTime = prevPoint.data.timestamp;
|
||||
const prevPrice = this.getPrice(prevPoint);
|
||||
|
||||
// Calculate average of next bucket for area calculation
|
||||
const nextBucketStart = Math.floor((i + 1) * bucketSize) + 1;
|
||||
let nextBucketEnd = Math.floor((i + 2) * bucketSize) + 1;
|
||||
if (nextBucketEnd >= data.length) {
|
||||
nextBucketEnd = data.length - 1;
|
||||
}
|
||||
|
||||
let avgTime = 0;
|
||||
let avgPrice = 0;
|
||||
for (let j = nextBucketStart; j < nextBucketEnd; j++) {
|
||||
avgTime += at(data, j).data.timestamp;
|
||||
avgPrice += this.getPrice(at(data, j));
|
||||
}
|
||||
avgTime /= nextBucketEnd - nextBucketStart;
|
||||
avgPrice /= nextBucketEnd - nextBucketStart;
|
||||
|
||||
// Find point with max area
|
||||
for (let j = bucketStart; j < bucketEnd && j < data.length; j++) {
|
||||
const time = at(data, j).data.timestamp;
|
||||
const price = this.getPrice(at(data, j));
|
||||
|
||||
// Calculate triangle area
|
||||
const area = Math.abs(
|
||||
(prevTime - avgTime) * (price - prevPrice) - (prevTime - time) * (avgPrice - prevPrice)
|
||||
);
|
||||
|
||||
if (area > maxArea) {
|
||||
maxArea = area;
|
||||
maxAreaPoint = j;
|
||||
}
|
||||
}
|
||||
|
||||
downsampled.push(at(data, maxAreaPoint));
|
||||
}
|
||||
|
||||
// Always include last point
|
||||
downsampled.push(at(data, data.length - 1));
|
||||
|
||||
return downsampled;
|
||||
}
|
||||
|
||||
private getPrice(data: MarketData): number {
|
||||
switch (data.type) {
|
||||
case 'bar':
|
||||
return data.data.close;
|
||||
case 'trade':
|
||||
return data.data.price;
|
||||
case 'quote':
|
||||
return (data.data.bid + data.data.ask) / 2;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private convertToMarketData(symbol: string, bars: HistoricalBar[]): MarketData[] {
|
||||
return bars.map(bar => ({
|
||||
type: 'bar' as const,
|
||||
data: {
|
||||
symbol,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap,
|
||||
timestamp: new Date(bar.timestamp).getTime(),
|
||||
interpolated: bar.interpolated,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
getDataQualityReport(): {
|
||||
totalIssues: number;
|
||||
bySymbol: Record<string, number>;
|
||||
bySeverity: Record<string, number>;
|
||||
issues: DataQualityIssue[];
|
||||
} {
|
||||
const bySymbol: Record<string, number> = {};
|
||||
const bySeverity: Record<string, number> = { warning: 0, error: 0 };
|
||||
|
||||
for (const issue of this.dataQualityIssues) {
|
||||
bySymbol[issue.symbol] = (bySymbol[issue.symbol] || 0) + 1;
|
||||
bySeverity[issue.severity] = (bySeverity[issue.severity] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
totalIssues: this.dataQualityIssues.length,
|
||||
bySymbol,
|
||||
bySeverity,
|
||||
issues: this.dataQualityIssues,
|
||||
};
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
this.dataCache.clear();
|
||||
this.aggregatedCache.clear();
|
||||
this.dataQualityIssues = [];
|
||||
}
|
||||
}
|
||||
|
|
@ -10,9 +10,9 @@ import {
|
|||
type HistoricalDataset,
|
||||
} from '@stock-bot/types';
|
||||
import { datasetBarSchema } from '../contracts/historical';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { StorageService } from '@stock-bot/trading-runtime/historical-storage';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '@stock-bot/trading-runtime/preparation';
|
||||
|
||||
export type DatasetResolver = (
|
||||
load: () => Promise<HistoricalDataset>,
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/preparation';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/retained-dataset';
|
||||
|
|
@ -1,294 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import type { Account, StoredOrder } from './model';
|
||||
import {
|
||||
ExecutionConflictError,
|
||||
type ExecutionRepository,
|
||||
type ExecutionTransaction,
|
||||
} from './repository';
|
||||
import {
|
||||
canonicalJson,
|
||||
type MarketInput,
|
||||
type StrategyCheckpoint,
|
||||
type StrategyJournalEvent,
|
||||
type StrategyOrderIntent,
|
||||
} from './strategy-recovery';
|
||||
|
||||
/** Only transaction writes are staged; committed history is never copied on entry. */
|
||||
class TransactionMap<T> {
|
||||
readonly writes = new Map<string, T>();
|
||||
constructor(private readonly base: Map<string, T>) {}
|
||||
get(key: string): T | undefined {
|
||||
return this.writes.get(key) ?? this.base.get(key);
|
||||
}
|
||||
put(key: string, value: T): void {
|
||||
this.writes.set(key, structuredClone(value));
|
||||
}
|
||||
*values(): Iterable<T> {
|
||||
for (const [key, value] of this.base) {
|
||||
yield this.writes.get(key) ?? value;
|
||||
}
|
||||
for (const [key, value] of this.writes) {
|
||||
if (!this.base.has(key)) {
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
}
|
||||
commit(): void {
|
||||
for (const [key, value] of this.writes) {
|
||||
this.base.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface RunState {
|
||||
account: Account;
|
||||
orders: Map<string, StoredOrder>;
|
||||
clients: Map<string, string>;
|
||||
openOrders: Set<string>;
|
||||
fills: Set<string>;
|
||||
events: Map<string, string>;
|
||||
journal: StrategyJournalEvent[];
|
||||
strategies: Map<string, StrategyCheckpoint>;
|
||||
intents: Map<string, StrategyOrderIntent>;
|
||||
pendingIntents: Set<string>;
|
||||
inputs: Map<string, MarketInput>;
|
||||
pendingInputs: Set<string>;
|
||||
}
|
||||
|
||||
const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
||||
const isOpen = (order: StoredOrder) =>
|
||||
order.report.status === 'accepted' || order.report.status === 'partiallyFilled';
|
||||
const compareIntents = (a: StrategyOrderIntent, b: StrategyOrderIntent) =>
|
||||
a.sequence - b.sequence ||
|
||||
compareText(a.strategyId, b.strategyId) ||
|
||||
compareText(a.clientOrderId, b.clientOrderId);
|
||||
|
||||
/** Binary search works with nonzero initial sequence numbers as well as empty journals. */
|
||||
function after(journal: StrategyJournalEvent[], cursor: number): StrategyJournalEvent | undefined {
|
||||
let low = 0,
|
||||
high = journal.length;
|
||||
while (low < high) {
|
||||
const mid = Math.floor((low + high) / 2);
|
||||
if (defined(journal[mid]).sequence <= cursor) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
return journal[low];
|
||||
}
|
||||
|
||||
/** Iterate only active IDs plus staged writes, never the retained applied/dispatched history. */
|
||||
function* candidates<T>(ids: Set<string>, table: TransactionMap<T>): Iterable<T> {
|
||||
for (const id of ids) {
|
||||
const value = table.get(id);
|
||||
if (value !== undefined) {
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
for (const [id, value] of table.writes) {
|
||||
if (!ids.has(id)) {
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Explicit run-local backtest store, never a fallback for paper or live execution. */
|
||||
export class BacktestExecutionRepository implements ExecutionRepository {
|
||||
private state?: RunState;
|
||||
private tail: Promise<unknown> = Promise.resolve();
|
||||
|
||||
async initialize(_id: string, account: Account): Promise<void> {
|
||||
await this.tail;
|
||||
this.state = {
|
||||
account: structuredClone(account),
|
||||
orders: new Map(),
|
||||
clients: new Map(),
|
||||
openOrders: new Set(),
|
||||
fills: new Set(),
|
||||
events: new Map(),
|
||||
journal: [],
|
||||
strategies: new Map(),
|
||||
intents: new Map(),
|
||||
pendingIntents: new Set(),
|
||||
inputs: new Map(),
|
||||
pendingInputs: new Set(),
|
||||
};
|
||||
}
|
||||
|
||||
transact<T>(_id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
|
||||
const task = this.tail.then(async () => {
|
||||
const state = this.state;
|
||||
if (!state) {
|
||||
throw new Error('Execution account is not initialized');
|
||||
}
|
||||
const account = structuredClone(state.account);
|
||||
const orders = new TransactionMap(state.orders);
|
||||
const clients = new TransactionMap(state.clients);
|
||||
const events = new TransactionMap(state.events);
|
||||
const strategies = new TransactionMap(state.strategies);
|
||||
const intents = new TransactionMap(state.intents);
|
||||
const inputs = new TransactionMap(state.inputs);
|
||||
const fills = new Set<string>();
|
||||
const journal: StrategyJournalEvent[] = [];
|
||||
let open = true;
|
||||
const assertOpen = () => {
|
||||
if (!open) {
|
||||
throw new Error('Execution transaction has finished');
|
||||
}
|
||||
};
|
||||
try {
|
||||
const result = await work({
|
||||
account,
|
||||
async findOrder(id) {
|
||||
assertOpen();
|
||||
const orderId = clients.get(id);
|
||||
return structuredClone(orderId === undefined ? undefined : orders.get(orderId));
|
||||
},
|
||||
async getOrder(id) {
|
||||
assertOpen();
|
||||
return structuredClone(orders.get(id));
|
||||
},
|
||||
async openOrders() {
|
||||
assertOpen();
|
||||
return structuredClone([...candidates(state.openOrders, orders)].filter(isOpen));
|
||||
},
|
||||
async putOrder(order) {
|
||||
assertOpen();
|
||||
const id = order.report.orderId;
|
||||
const clientId = order.report.clientOrderId;
|
||||
const existingId = clients.get(clientId);
|
||||
if (existingId !== undefined && existingId !== id) {
|
||||
throw new ExecutionConflictError('Client order ID already exists');
|
||||
}
|
||||
const old = orders.get(id);
|
||||
if (old && old.report.clientOrderId !== clientId) {
|
||||
throw new ExecutionConflictError('Order client ID cannot change');
|
||||
}
|
||||
orders.put(id, order);
|
||||
clients.put(clientId, id);
|
||||
},
|
||||
async insertFill(_orderId, fill) {
|
||||
assertOpen();
|
||||
if (state.fills.has(fill.id) || fills.has(fill.id)) {
|
||||
return false;
|
||||
}
|
||||
fills.add(fill.id);
|
||||
return true;
|
||||
},
|
||||
async recordEvent(id, hash) {
|
||||
assertOpen();
|
||||
const previous = events.get(id);
|
||||
if (previous !== undefined && previous !== hash) {
|
||||
throw new ExecutionConflictError('Conflicting market event identity');
|
||||
}
|
||||
if (previous !== undefined) {
|
||||
return false;
|
||||
}
|
||||
events.put(id, hash);
|
||||
return true;
|
||||
},
|
||||
async appendJournal(payload) {
|
||||
assertOpen();
|
||||
const sequence = (account.strategySequence ?? 0) + 1;
|
||||
if (!Number.isSafeInteger(sequence)) {
|
||||
throw new Error('Strategy journal sequence exhausted');
|
||||
}
|
||||
account.strategySequence = sequence;
|
||||
journal.push({ sequence, payload: structuredClone(payload) });
|
||||
},
|
||||
async nextJournal(cursor) {
|
||||
assertOpen();
|
||||
return structuredClone(after(state.journal, cursor) ?? after(journal, cursor));
|
||||
},
|
||||
async strategies() {
|
||||
assertOpen();
|
||||
return structuredClone(
|
||||
[...strategies.values()].sort((a, b) => compareText(a.strategyId, b.strategyId))
|
||||
);
|
||||
},
|
||||
async putStrategy(checkpoint) {
|
||||
assertOpen();
|
||||
strategies.put(checkpoint.strategyId, checkpoint);
|
||||
},
|
||||
async nextIntent() {
|
||||
assertOpen();
|
||||
let next: StrategyOrderIntent | undefined;
|
||||
for (const intent of candidates(state.pendingIntents, intents)) {
|
||||
if (intent.status === 'pending' && (!next || compareIntents(intent, next) < 0)) {
|
||||
next = intent;
|
||||
}
|
||||
}
|
||||
return structuredClone(next);
|
||||
},
|
||||
async putIntent(intent) {
|
||||
assertOpen();
|
||||
const old = intents.get(intent.clientOrderId);
|
||||
if (
|
||||
old &&
|
||||
(old.strategyId !== intent.strategyId ||
|
||||
old.sequence !== intent.sequence ||
|
||||
canonicalJson(old.request) !== canonicalJson(intent.request) ||
|
||||
(old.status === 'dispatched' && intent.status !== 'dispatched'))
|
||||
) {
|
||||
throw new ExecutionConflictError('Conflicting strategy order intent');
|
||||
}
|
||||
intents.put(intent.clientOrderId, intent);
|
||||
},
|
||||
async nextInput() {
|
||||
assertOpen();
|
||||
let next: MarketInput | undefined;
|
||||
for (const input of candidates(state.pendingInputs, inputs)) {
|
||||
if (input.status === 'pending' && (!next || input.sequence < next.sequence)) {
|
||||
next = input;
|
||||
}
|
||||
}
|
||||
return structuredClone(next);
|
||||
},
|
||||
async putInput(input) {
|
||||
assertOpen();
|
||||
inputs.put(input.id, input);
|
||||
},
|
||||
});
|
||||
// Clone anything the callback can retain before publishing any staged writes.
|
||||
const detachedResult = structuredClone(result);
|
||||
state.account = structuredClone(account);
|
||||
for (const table of [orders, clients, events, strategies, intents, inputs]) {
|
||||
table.commit();
|
||||
}
|
||||
for (const [id, order] of orders.writes) {
|
||||
if (isOpen(order)) {
|
||||
state.openOrders.add(id);
|
||||
} else {
|
||||
state.openOrders.delete(id);
|
||||
}
|
||||
}
|
||||
for (const [id, intent] of intents.writes) {
|
||||
if (intent.status === 'pending') {
|
||||
state.pendingIntents.add(id);
|
||||
} else {
|
||||
state.pendingIntents.delete(id);
|
||||
}
|
||||
}
|
||||
for (const [id, input] of inputs.writes) {
|
||||
if (input.status === 'pending') {
|
||||
state.pendingInputs.add(id);
|
||||
} else {
|
||||
state.pendingInputs.delete(id);
|
||||
}
|
||||
}
|
||||
for (const id of fills) {
|
||||
state.fills.add(id);
|
||||
}
|
||||
for (const event of journal) {
|
||||
state.journal.push(event);
|
||||
}
|
||||
return detachedResult;
|
||||
} finally {
|
||||
open = false;
|
||||
}
|
||||
});
|
||||
this.tail = task.catch(() => {});
|
||||
return task;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,9 +10,9 @@ import {
|
|||
type CanonicalExecutionIdentity,
|
||||
type CanonicalMatchingConfig,
|
||||
type FinancialTransactionRequest,
|
||||
} from '../contracts/canonical-execution';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-execution';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import { nativeAdmissionOrders, type DecisionContext } from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
freeze,
|
||||
increment,
|
||||
|
|
@ -34,7 +34,7 @@ import {
|
|||
type CanonicalPaperInput,
|
||||
type CanonicalTransaction,
|
||||
} from './canonical-paper';
|
||||
import { ExecutionConflictError } from './repository';
|
||||
import { ExecutionConflictError } from './canonical-paper';
|
||||
|
||||
const callback = new AsyncLocalStorage<boolean>();
|
||||
function outsideCallback() {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import {
|
|||
type CanonicalPostgres,
|
||||
type CanonicalTransaction,
|
||||
} from './canonical-paper';
|
||||
import { ExecutionConflictError } from './repository';
|
||||
import { ExecutionConflictError } from './canonical-paper';
|
||||
|
||||
function accountState(raw: unknown): CanonicalAccount {
|
||||
const result = canonicalAccountSchema.safeParse(raw);
|
||||
|
|
|
|||
|
|
@ -1,213 +0,0 @@
|
|||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { refuseCanonicalAccount } from './canonical-paper';
|
||||
import type { Account, Fill, StoredOrder } from './model';
|
||||
import {
|
||||
ExecutionConflictError,
|
||||
type ExecutionRepository,
|
||||
type ExecutionTransaction,
|
||||
} from './repository';
|
||||
import {
|
||||
canonicalJson,
|
||||
type MarketInput,
|
||||
type StrategyCheckpoint,
|
||||
type StrategyJournalPayload,
|
||||
type StrategyOrderIntent,
|
||||
} from './strategy-recovery';
|
||||
|
||||
export class PostgresExecutionRepository implements ExecutionRepository {
|
||||
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
|
||||
async initialize(id: string, initial: Account) {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`INSERT INTO simulation_accounts (id, state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING`,
|
||||
[id, JSON.stringify(initial)]
|
||||
);
|
||||
const result = await client.query(
|
||||
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
|
||||
[id]
|
||||
);
|
||||
refuseCanonicalAccount(result.rows[0].state);
|
||||
const account: Account = result.rows[0].state;
|
||||
if (account.initialCapital !== initial.initialCapital) {
|
||||
throw new ExecutionConflictError(
|
||||
'Existing account capital differs; use a new account ID, not an implicit reset'
|
||||
);
|
||||
}
|
||||
Object.assign(account, {
|
||||
limits: initial.limits,
|
||||
commission: initial.commission,
|
||||
slippage: initial.slippage,
|
||||
maxQuoteAgeMs: initial.maxQuoteAgeMs,
|
||||
});
|
||||
await client.query('UPDATE simulation_accounts SET state = $2::jsonb WHERE id = $1', [
|
||||
id,
|
||||
JSON.stringify(account),
|
||||
]);
|
||||
});
|
||||
}
|
||||
transact<T>(id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
|
||||
return this.postgres.transaction(async client => {
|
||||
const state = await client.query(
|
||||
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
|
||||
[id]
|
||||
);
|
||||
if (!state.rows[0]) {
|
||||
throw new Error('Execution account is not initialized');
|
||||
}
|
||||
refuseCanonicalAccount(state.rows[0].state);
|
||||
const readOrder = async (column: 'id' | 'client_order_id', key: string) => {
|
||||
const result = await client.query(
|
||||
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`,
|
||||
[id, key]
|
||||
);
|
||||
return result.rows[0]?.payload as StoredOrder | undefined;
|
||||
};
|
||||
const result = await work({
|
||||
account: state.rows[0].state as Account,
|
||||
findOrder: key => readOrder('client_order_id', key),
|
||||
getOrder: key => readOrder('id', key),
|
||||
async openOrders() {
|
||||
const result = await client.query(
|
||||
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND status IN ('accepted','partiallyFilled') ORDER BY created_at,id`,
|
||||
[id]
|
||||
);
|
||||
return result.rows.map(r => r.payload as StoredOrder);
|
||||
},
|
||||
async putOrder(order) {
|
||||
await client.query(
|
||||
`INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
|
||||
[
|
||||
order.report.orderId,
|
||||
id,
|
||||
order.report.clientOrderId,
|
||||
order.report.status,
|
||||
JSON.stringify(order),
|
||||
]
|
||||
);
|
||||
},
|
||||
async insertFill(orderId: string, fill: Fill) {
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO simulation_fills (account_id,id,order_id,payload)
|
||||
VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
|
||||
[id, fill.id, orderId, JSON.stringify(fill)]
|
||||
);
|
||||
return inserted.rows.length > 0;
|
||||
},
|
||||
async recordEvent(eventId, hash) {
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO simulation_events (account_id,id,fingerprint)
|
||||
VALUES ($1,$2,$3) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
|
||||
[id, eventId, hash]
|
||||
);
|
||||
if (inserted.rows.length) {
|
||||
return true;
|
||||
}
|
||||
const previous = await client.query(
|
||||
'SELECT fingerprint FROM simulation_events WHERE account_id = $1 AND id = $2',
|
||||
[id, eventId]
|
||||
);
|
||||
if (previous.rows[0]?.fingerprint !== hash) {
|
||||
throw new ExecutionConflictError('Conflicting market event identity');
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async appendJournal(payload: StrategyJournalPayload) {
|
||||
const account = state.rows[0].state as Account;
|
||||
const sequence = (account.strategySequence ?? 0) + 1;
|
||||
if (!Number.isSafeInteger(sequence)) {
|
||||
throw new Error('Strategy journal sequence exhausted');
|
||||
}
|
||||
account.strategySequence = sequence;
|
||||
await client.query(
|
||||
'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)',
|
||||
[id, sequence, JSON.stringify(payload)]
|
||||
);
|
||||
},
|
||||
async nextJournal(cursor) {
|
||||
const result = await client.query(
|
||||
'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence LIMIT 1',
|
||||
[id, cursor]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) {
|
||||
return undefined;
|
||||
}
|
||||
const sequence = Number(row.sequence);
|
||||
if (!Number.isSafeInteger(sequence)) {
|
||||
throw new Error('Invalid strategy journal sequence');
|
||||
}
|
||||
return { sequence, payload: row.payload as StrategyJournalPayload };
|
||||
},
|
||||
async strategies() {
|
||||
const result = await client.query(
|
||||
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"',
|
||||
[id]
|
||||
);
|
||||
return result.rows.map(row => row.payload as StrategyCheckpoint);
|
||||
},
|
||||
async putStrategy(checkpoint) {
|
||||
await client.query(
|
||||
`INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)
|
||||
ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`,
|
||||
[id, checkpoint.strategyId, JSON.stringify(checkpoint)]
|
||||
);
|
||||
},
|
||||
async nextIntent() {
|
||||
const result = await client.query(
|
||||
`SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence,strategy_id COLLATE "C",client_order_id COLLATE "C" LIMIT 1`,
|
||||
[id]
|
||||
);
|
||||
return result.rows[0]?.payload as StrategyOrderIntent | undefined;
|
||||
},
|
||||
async putIntent(intent) {
|
||||
const previous = await client.query(
|
||||
'SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND client_order_id = $2',
|
||||
[id, intent.clientOrderId]
|
||||
);
|
||||
const old = previous.rows[0]?.payload as StrategyOrderIntent | undefined;
|
||||
if (
|
||||
old &&
|
||||
(old.strategyId !== intent.strategyId ||
|
||||
old.sequence !== intent.sequence ||
|
||||
canonicalJson(old.request) !== canonicalJson(intent.request) ||
|
||||
(old.status === 'dispatched' && intent.status !== 'dispatched'))
|
||||
) {
|
||||
throw new ExecutionConflictError('Conflicting strategy order intent');
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO simulation_strategy_intents (account_id,client_order_id,strategy_id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5,$6::jsonb)
|
||||
ON CONFLICT (account_id,client_order_id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
|
||||
[
|
||||
id,
|
||||
intent.clientOrderId,
|
||||
intent.strategyId,
|
||||
intent.sequence,
|
||||
intent.status,
|
||||
JSON.stringify(intent),
|
||||
]
|
||||
);
|
||||
},
|
||||
async nextInput() {
|
||||
const result = await client.query(
|
||||
`SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1`,
|
||||
[id]
|
||||
);
|
||||
return result.rows[0]?.payload as MarketInput | undefined;
|
||||
},
|
||||
async putInput(input) {
|
||||
await client.query(
|
||||
`INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
|
||||
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
|
||||
[id, input.id, input.sequence, input.status, JSON.stringify(input)]
|
||||
);
|
||||
},
|
||||
});
|
||||
await client.query(
|
||||
'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1',
|
||||
[id, JSON.stringify(state.rows[0].state)]
|
||||
);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { OrderRequest } from '../types';
|
||||
import {
|
||||
amount,
|
||||
applyFill,
|
||||
decimal,
|
||||
fillPrice,
|
||||
fingerprint,
|
||||
riskViolations,
|
||||
terminal,
|
||||
type Account,
|
||||
type ExecutionChange,
|
||||
type Fill,
|
||||
type Quote,
|
||||
type StoredOrder,
|
||||
} from './model';
|
||||
import { ExecutionConflictError, type ExecutionTransaction } from './repository';
|
||||
|
||||
export interface ExecutionClock {
|
||||
now(quote?: Quote): number;
|
||||
isBacktest(): boolean;
|
||||
}
|
||||
|
||||
/** Transaction-scoped simulation rules; the caller owns commit, serialization and publication. */
|
||||
export class SimulationExecution {
|
||||
constructor(private readonly clock: ExecutionClock) {}
|
||||
|
||||
rollDay(account: Account, time: number) {
|
||||
const day = new Date(time).toISOString().slice(0, 10);
|
||||
if (day > account.day || (this.clock.isBacktest() && !Object.keys(account.quotes).length)) {
|
||||
account.day = day;
|
||||
account.dailyPnl = 0;
|
||||
}
|
||||
}
|
||||
private async assertRecovered(tx: ExecutionTransaction) {
|
||||
if (
|
||||
(await tx.nextInput()) ||
|
||||
(await tx.nextIntent()) ||
|
||||
(await tx.strategies()).some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0))
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
'Strategy recovery backlog must drain before new order admission'
|
||||
);
|
||||
}
|
||||
}
|
||||
async journalChange(tx: ExecutionTransaction, change: ExecutionChange) {
|
||||
if (change.report.strategyId) {
|
||||
await tx.appendJournal({
|
||||
kind: 'execution',
|
||||
report: change.report,
|
||||
fills: change.fills,
|
||||
account: structuredClone(tx.account),
|
||||
});
|
||||
}
|
||||
}
|
||||
async acceptOrder(
|
||||
tx: ExecutionTransaction,
|
||||
request: OrderRequest,
|
||||
strategyId?: string,
|
||||
internal = false
|
||||
): Promise<ExecutionChange> {
|
||||
const hash = fingerprint(request, strategyId);
|
||||
const existing = await tx.findOrder(defined(request.clientOrderId));
|
||||
if (existing) {
|
||||
if (existing.fingerprint !== hash) {
|
||||
throw new ExecutionConflictError('Client order ID reused with a different request');
|
||||
}
|
||||
return { report: existing.report, fills: [] };
|
||||
}
|
||||
if (!internal) {
|
||||
await this.assertRecovered(tx);
|
||||
}
|
||||
const quote = tx.account.quotes[request.symbol];
|
||||
const timestamp = this.clock.now(quote);
|
||||
this.rollDay(tx.account, timestamp);
|
||||
const order: StoredOrder = {
|
||||
request,
|
||||
fingerprint: hash,
|
||||
policy: { commission: tx.account.commission, slippage: tx.account.slippage },
|
||||
report: {
|
||||
orderId: randomUUID(),
|
||||
clientOrderId: defined(request.clientOrderId),
|
||||
strategyId: strategyId,
|
||||
symbol: request.symbol,
|
||||
side: request.side,
|
||||
quantity: request.quantity,
|
||||
status: 'accepted',
|
||||
fills: [],
|
||||
timestamp,
|
||||
},
|
||||
};
|
||||
const invalid = !['market', 'limit'].includes(request.orderType)
|
||||
? 'Unsupported order type'
|
||||
: !['DAY', 'GTC', 'IOC', 'FOK'].includes(request.timeInForce)
|
||||
? 'Unsupported time in force'
|
||||
: request.orderType === 'limit' &&
|
||||
(!request.limitPrice || !Number.isFinite(request.limitPrice) || request.limitPrice <= 0)
|
||||
? 'Valid limit price required'
|
||||
: !quote ||
|
||||
timestamp - quote.timestamp > tx.account.maxQuoteAgeMs ||
|
||||
quote.timestamp > timestamp
|
||||
? 'Missing, stale, or future market quote'
|
||||
: undefined;
|
||||
const price = quote && !invalid ? fillPrice(order, quote) : 0;
|
||||
const violations = invalid
|
||||
? [invalid]
|
||||
: riskViolations(
|
||||
tx.account,
|
||||
request,
|
||||
await tx.openOrders(),
|
||||
price,
|
||||
timestamp,
|
||||
order.policy.commission
|
||||
);
|
||||
if (violations.length) {
|
||||
order.report.status = 'rejected';
|
||||
order.report.rejectionReason = violations.join('; ');
|
||||
}
|
||||
await tx.putOrder(order); // Fill FK and acknowledgement are in the same transaction.
|
||||
const fills =
|
||||
order.report.status === 'rejected' || !quote
|
||||
? []
|
||||
: await this.fill(tx, order, quote, await tx.openOrders());
|
||||
await tx.putOrder(order);
|
||||
const change = { report: order.report, fills };
|
||||
await this.journalChange(tx, change);
|
||||
return change;
|
||||
}
|
||||
async fill(
|
||||
tx: ExecutionTransaction,
|
||||
order: StoredOrder,
|
||||
quote: Quote,
|
||||
reservations: StoredOrder[]
|
||||
): Promise<Fill[]> {
|
||||
if (terminal(order.report.status)) {
|
||||
return [];
|
||||
}
|
||||
const request = order.request;
|
||||
if (
|
||||
request.timeInForce === 'DAY' &&
|
||||
new Date(order.report.timestamp).toISOString().slice(0, 10) !==
|
||||
new Date(quote.timestamp).toISOString().slice(0, 10)
|
||||
) {
|
||||
order.report.status = 'cancelled';
|
||||
return [];
|
||||
}
|
||||
const crosses =
|
||||
request.orderType === 'market' ||
|
||||
(request.side === 'buy'
|
||||
? quote.ask <= defined(request.limitPrice)
|
||||
: quote.bid >= defined(request.limitPrice));
|
||||
const remaining = amount(
|
||||
decimal(request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0))
|
||||
);
|
||||
const available = request.side === 'buy' ? quote.askSize : quote.bidSize;
|
||||
const quantity = crosses ? Math.min(remaining, available) : 0;
|
||||
if (!quantity || (request.timeInForce === 'FOK' && quantity < remaining)) {
|
||||
if (request.timeInForce === 'IOC' || request.timeInForce === 'FOK') {
|
||||
order.report.status = 'cancelled';
|
||||
}
|
||||
return [];
|
||||
}
|
||||
const price = fillPrice(order, quote);
|
||||
const violations = riskViolations(
|
||||
tx.account,
|
||||
{ ...request, quantity: remaining },
|
||||
reservations.filter(o => o.report.orderId !== order.report.orderId),
|
||||
price,
|
||||
this.clock.now(quote),
|
||||
order.policy.commission
|
||||
);
|
||||
if (violations.length) {
|
||||
order.report.status = 'cancelled';
|
||||
order.report.rejectionReason = violations.join('; ');
|
||||
return [];
|
||||
}
|
||||
const fill = {
|
||||
id: order.report.orderId + ':' + quote.eventId,
|
||||
price,
|
||||
quantity,
|
||||
commission: amount(decimal(quantity).times(price).times(order.policy.commission)),
|
||||
timestamp: quote.timestamp,
|
||||
pnl: 0,
|
||||
};
|
||||
const projected = structuredClone(tx.account);
|
||||
const applied = applyFill(projected, request.symbol, request.side, fill);
|
||||
if (!(await tx.insertFill(order.report.orderId, applied))) {
|
||||
return [];
|
||||
}
|
||||
// Keep the same quote object so consumed liquidity is persisted with the accounting change.
|
||||
Object.assign(tx.account, { ...projected, quotes: tx.account.quotes });
|
||||
if (order.report.strategyId) {
|
||||
const book = (tx.account.strategyPositions[order.report.strategyId] ??= {});
|
||||
book[request.symbol] = amount(
|
||||
decimal(book[request.symbol] ?? 0).plus(request.side === 'buy' ? quantity : -quantity)
|
||||
);
|
||||
}
|
||||
// Store the actual delta, not cumulative realized P&L.
|
||||
// The returned fill is also appended to the durable report in this transaction.
|
||||
order.report.fills.push(applied);
|
||||
if (request.side === 'buy') {
|
||||
quote.askSize = amount(decimal(quote.askSize).minus(quantity));
|
||||
} else {
|
||||
quote.bidSize = amount(decimal(quote.bidSize).minus(quantity));
|
||||
}
|
||||
order.report.status =
|
||||
quantity >= remaining
|
||||
? 'filled'
|
||||
: request.timeInForce === 'IOC'
|
||||
? 'cancelled'
|
||||
: 'partiallyFilled';
|
||||
return [applied];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,288 +0,0 @@
|
|||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { OrderRequestSchema, type OrderRequest } from '../types';
|
||||
import { accountMetrics, identity, type Account, type ExecutionChange } from './model';
|
||||
import { ExecutionConflictError, type ExecutionTransaction } from './repository';
|
||||
import {
|
||||
canonicalJson,
|
||||
strategyConfigHash,
|
||||
type RecoverableStrategy,
|
||||
type StrategyCheckpoint,
|
||||
type StrategyOrderIntent,
|
||||
} from './strategy-recovery';
|
||||
|
||||
/** Explicit ports keep recovery independent of the service container and storage adapters. */
|
||||
export interface StrategyRecoveryRuntime {
|
||||
accountId(): string;
|
||||
isBacktest(): boolean;
|
||||
serialized<T>(work: () => Promise<T>): Promise<T>;
|
||||
transact<T>(work: (tx: ExecutionTransaction) => Promise<T>): Promise<T>;
|
||||
dispatch(tx: ExecutionTransaction, intent: StrategyOrderIntent): Promise<ExecutionChange>;
|
||||
publish(change: ExecutionChange): Promise<void>;
|
||||
consumeMarketInput(): Promise<boolean>;
|
||||
observationFailed(error: unknown): void;
|
||||
}
|
||||
|
||||
/** Owns checkpoints, decision scopes and outbox replay; never opens a nested transaction. */
|
||||
export class StrategyRecovery {
|
||||
private readonly decision = new AsyncLocalStorage<{
|
||||
account: Account;
|
||||
strategyId: string;
|
||||
intents: StrategyOrderIntent[];
|
||||
sequence: number;
|
||||
open: boolean;
|
||||
observations: (() => void)[];
|
||||
}>();
|
||||
constructor(private readonly runtime: StrategyRecoveryRuntime) {}
|
||||
|
||||
assertExternalIO(): void {
|
||||
if (this.decision.getStore()) {
|
||||
throw new Error(
|
||||
'Strategy callbacks cannot perform repository I/O; use the decision account view and order intents'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
decisionAccount() {
|
||||
const context = this.decision.getStore();
|
||||
if (!context) {
|
||||
return undefined;
|
||||
}
|
||||
if (!context.open) {
|
||||
throw new Error('Strategy evaluation has finished');
|
||||
}
|
||||
return { ...structuredClone(context.account), ...accountMetrics(context.account) };
|
||||
}
|
||||
|
||||
captureStrategyOrder(request: OrderRequest, strategyId: string): void {
|
||||
const context = this.decision.getStore();
|
||||
if (!context?.open || context.strategyId !== strategyId) {
|
||||
throw new Error('Strategy orders require an active checkpoint transaction');
|
||||
}
|
||||
const order = OrderRequestSchema.parse(request);
|
||||
if (!order.clientOrderId) {
|
||||
throw new Error('Strategy intent requires a stable client order ID');
|
||||
}
|
||||
if (context.intents.some(intent => intent.clientOrderId === order.clientOrderId)) {
|
||||
throw new ExecutionConflictError('Duplicate intent in one decision');
|
||||
}
|
||||
context.intents.push({
|
||||
strategyId,
|
||||
clientOrderId: order.clientOrderId,
|
||||
sequence: context.sequence,
|
||||
request: order,
|
||||
status: 'pending',
|
||||
});
|
||||
}
|
||||
afterStrategyCommit(observation: () => void): void {
|
||||
const context = this.decision.getStore();
|
||||
if (!context?.open) {
|
||||
throw new Error('No active strategy decision');
|
||||
}
|
||||
context.observations.push(observation);
|
||||
}
|
||||
async getRecoveryStatus() {
|
||||
return this.runtime.transact(async tx => ({
|
||||
accountId: this.runtime.accountId(),
|
||||
pendingInputs: !!(await tx.nextInput()),
|
||||
pendingIntents: !!(await tx.nextIntent()),
|
||||
strategies: (await tx.strategies()).map(s => ({
|
||||
strategyId: s.strategyId,
|
||||
enabled: s.enabled,
|
||||
version: s.version,
|
||||
cursor: s.cursor,
|
||||
journalTail: tx.account.strategySequence ?? 0,
|
||||
lag: (tx.account.strategySequence ?? 0) - s.cursor,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
async registerStrategy(strategy: RecoverableStrategy): Promise<void> {
|
||||
const config = structuredClone(strategy.getConfig());
|
||||
const version =
|
||||
strategy.getCheckpointVersion() ??
|
||||
(this.runtime.isBacktest() ? 'run-local-unversioned' : undefined);
|
||||
if (!version) {
|
||||
throw new Error('Paper strategies require a versioned checkpoint contract');
|
||||
}
|
||||
const hash = strategyConfigHash(config, version);
|
||||
const initialState = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
|
||||
strategy.restoreCheckpoint(initialState);
|
||||
const saved = await this.runtime.serialized(() =>
|
||||
this.runtime.transact(async tx => {
|
||||
const existing = (await tx.strategies()).find(s => s.strategyId === config.id);
|
||||
if (existing && (existing.version !== version || existing.configHash !== hash)) {
|
||||
throw new ExecutionConflictError(
|
||||
'Strategy configuration/checkpoint version changed; use an explicit new strategy ID'
|
||||
);
|
||||
}
|
||||
const checkpoint: StrategyCheckpoint = existing ?? {
|
||||
strategyId: config.id,
|
||||
config,
|
||||
configHash: hash,
|
||||
version,
|
||||
enabled: true,
|
||||
cursor: tx.account.strategySequence ?? 0,
|
||||
state: initialState,
|
||||
};
|
||||
strategy.restoreCheckpoint(checkpoint.state);
|
||||
await tx.putStrategy({ ...checkpoint, enabled: true });
|
||||
return checkpoint;
|
||||
})
|
||||
);
|
||||
strategy.restoreCheckpoint(saved.state);
|
||||
}
|
||||
|
||||
async registeredStrategies() {
|
||||
return this.runtime.transact(async tx =>
|
||||
(await tx.strategies()).map(s => ({ ...s.config, enabled: s.enabled }))
|
||||
);
|
||||
}
|
||||
async pauseStrategy(strategyId: string) {
|
||||
await this.runtime.serialized(() =>
|
||||
this.runtime.transact(async tx => {
|
||||
const checkpoint = (await tx.strategies()).find(s => s.strategyId === strategyId);
|
||||
if (checkpoint) {
|
||||
await tx.putStrategy({ ...checkpoint, enabled: false });
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Account row locks serialize owners. Restore before EVERY step, not just startup. */
|
||||
async recoverStrategies(strategies: RecoverableStrategy[]): Promise<void> {
|
||||
await this.runtime.serialized(async () => {
|
||||
const byId = new Map(strategies.map(strategy => [strategy.getConfig().id, strategy]));
|
||||
const enabled = await this.runtime.transact(async tx =>
|
||||
(await tx.strategies()).filter(s => s.enabled)
|
||||
);
|
||||
for (const checkpoint of enabled) {
|
||||
const strategy = byId.get(checkpoint.strategyId);
|
||||
if (!strategy) {
|
||||
throw new ExecutionConflictError(
|
||||
'An enabled strategy must be restored before processing its account'
|
||||
);
|
||||
}
|
||||
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
|
||||
if (
|
||||
checkpoint.version !== version ||
|
||||
checkpoint.configHash !== strategyConfigHash(strategy.getConfig(), version)
|
||||
) {
|
||||
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
|
||||
}
|
||||
}
|
||||
while (true) {
|
||||
const dispatched = await this.runtime.transact(async tx => {
|
||||
const intent = await tx.nextIntent();
|
||||
if (!intent) {
|
||||
return undefined;
|
||||
}
|
||||
const change = await this.runtime.dispatch(tx, intent);
|
||||
await tx.putIntent({ ...intent, status: 'dispatched', orderId: change.report.orderId });
|
||||
return change;
|
||||
});
|
||||
if (dispatched) {
|
||||
await this.runtime.publish(dispatched);
|
||||
continue;
|
||||
}
|
||||
let progressed = false;
|
||||
const registrations = await this.runtime.transact(tx => tx.strategies());
|
||||
for (const registration of registrations.filter(s => s.enabled)) {
|
||||
const strategy = byId.get(registration.strategyId);
|
||||
if (!strategy) {
|
||||
throw new ExecutionConflictError(
|
||||
'An enabled strategy must be restored before processing its account'
|
||||
);
|
||||
}
|
||||
let before = strategy.captureCheckpoint();
|
||||
let observations: (() => void)[] = [];
|
||||
try {
|
||||
const advanced = await this.runtime.transact(async tx => {
|
||||
const checkpoint = (await tx.strategies()).find(
|
||||
s => s.strategyId === registration.strategyId
|
||||
);
|
||||
if (!checkpoint?.enabled) {
|
||||
return false;
|
||||
}
|
||||
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
|
||||
if (
|
||||
strategyConfigHash(strategy.getConfig(), version) !== checkpoint.configHash ||
|
||||
checkpoint.version !== version
|
||||
) {
|
||||
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
|
||||
}
|
||||
strategy.restoreCheckpoint(checkpoint.state);
|
||||
before = checkpoint.state;
|
||||
const event = await tx.nextJournal(checkpoint.cursor);
|
||||
if (!event) {
|
||||
return false;
|
||||
}
|
||||
const context = {
|
||||
account: event.payload.account,
|
||||
strategyId: checkpoint.strategyId,
|
||||
intents: [] as StrategyOrderIntent[],
|
||||
sequence: event.sequence,
|
||||
open: true,
|
||||
observations: [] as (() => void)[],
|
||||
};
|
||||
try {
|
||||
await this.decision.run(context, async () => {
|
||||
const payload = event.payload;
|
||||
if (
|
||||
payload.kind === 'market' &&
|
||||
payload.recipients.includes(checkpoint.strategyId) &&
|
||||
strategy.getConfig().symbols.includes(payload.market.data.symbol)
|
||||
) {
|
||||
await strategy.onMarketData({
|
||||
...payload.market,
|
||||
eventId: identity(payload.market),
|
||||
});
|
||||
} else if (
|
||||
payload.kind === 'execution' &&
|
||||
payload.report.strategyId === checkpoint.strategyId
|
||||
) {
|
||||
for (const fill of payload.fills) {
|
||||
await strategy.onFill({
|
||||
...fill,
|
||||
orderId: payload.report.orderId,
|
||||
symbol: payload.report.symbol,
|
||||
side: payload.report.side,
|
||||
strategyId: checkpoint.strategyId,
|
||||
});
|
||||
}
|
||||
await strategy.onOrderUpdate(payload.report);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
context.open = false;
|
||||
}
|
||||
const state = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
|
||||
await tx.putStrategy({ ...checkpoint, cursor: event.sequence, state });
|
||||
for (const intent of context.intents) {
|
||||
await tx.putIntent(intent);
|
||||
}
|
||||
observations = context.observations;
|
||||
return true;
|
||||
});
|
||||
progressed ||= advanced;
|
||||
for (const observe of observations) {
|
||||
try {
|
||||
observe();
|
||||
} catch (error) {
|
||||
this.runtime.observationFailed(error);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
strategy.restoreCheckpoint(before);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (progressed) {
|
||||
continue;
|
||||
}
|
||||
if (!(await this.runtime.consumeMarketInput())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -6,13 +6,13 @@ import {
|
|||
canonicalExecutionCheckpointSchema,
|
||||
financialTransactionResultSchema,
|
||||
matchingCommandSchema,
|
||||
} from '../contracts/canonical-execution';
|
||||
} from '@stock-bot/stock-config/canonical-execution';
|
||||
import {
|
||||
nativeFinancialViewSchema,
|
||||
nativeManagedOrderSchema,
|
||||
stepSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { paperConfigurationSchema, paperConnectionSchema } from '@stock-bot/stock-config/paper-runtime';
|
||||
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
|
||||
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
|
|
@ -195,7 +195,8 @@ export interface CanonicalExecutionRepository {
|
|||
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
|
||||
export { compareEventKeys } from '../contracts/canonical-execution';
|
||||
export class ExecutionConflictError extends Error {}
|
||||
export { compareEventKeys } from '@stock-bot/stock-config/canonical-execution';
|
||||
/** Legacy callers must never reinterpret any version of a canonical envelope. */
|
||||
export function refuseCanonicalAccount(state: unknown): void {
|
||||
if (state && typeof state === 'object' && 'kind' in state) {
|
||||
|
|
|
|||
|
|
@ -1,268 +0,0 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import Decimal from 'decimal.js-light';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { MarketData, OrderRequest } from '../types';
|
||||
|
||||
export interface RiskLimits {
|
||||
maxPositionSize: number;
|
||||
maxOrderSize: number;
|
||||
maxDailyLoss: number;
|
||||
maxGrossExposure: number;
|
||||
maxSymbolExposure: number;
|
||||
}
|
||||
export const defaultRiskLimits: RiskLimits = {
|
||||
maxPositionSize: 10000,
|
||||
maxOrderSize: 1000,
|
||||
maxDailyLoss: 5000,
|
||||
maxGrossExposure: 200000,
|
||||
maxSymbolExposure: 50000,
|
||||
};
|
||||
export interface Fill {
|
||||
id: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
commission: number;
|
||||
timestamp: number;
|
||||
pnl: number;
|
||||
}
|
||||
export interface ExecutionReport {
|
||||
orderId: string;
|
||||
clientOrderId: string;
|
||||
symbol: string;
|
||||
side: 'buy' | 'sell';
|
||||
quantity: number;
|
||||
status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected';
|
||||
fills: Fill[];
|
||||
rejectionReason?: string;
|
||||
timestamp: number;
|
||||
strategyId?: string;
|
||||
}
|
||||
/** A committed order report and only the new fills from that transaction. */
|
||||
export interface ExecutionChange {
|
||||
report: ExecutionReport;
|
||||
fills: Fill[];
|
||||
}
|
||||
export interface Position {
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
averagePrice: number;
|
||||
realizedPnl: number;
|
||||
}
|
||||
export interface Quote {
|
||||
bid: number;
|
||||
ask: number;
|
||||
bidSize: number;
|
||||
askSize: number;
|
||||
timestamp: number;
|
||||
eventId: string;
|
||||
}
|
||||
export interface Account {
|
||||
/** Account-row-locked journal sequence, safe integer checked before increment. */
|
||||
strategySequence?: number;
|
||||
inputSequence?: number;
|
||||
admittedTimes?: Record<string, number>;
|
||||
initialCapital: number;
|
||||
cash: number;
|
||||
realizedPnl: number;
|
||||
dailyPnl: number;
|
||||
day: string;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
limits: RiskLimits;
|
||||
maxQuoteAgeMs: number;
|
||||
positions: Record<string, Position>;
|
||||
quotes: Record<string, Quote>;
|
||||
strategyPositions: Record<string, Record<string, number>>;
|
||||
}
|
||||
export interface StoredOrder {
|
||||
request: OrderRequest;
|
||||
report: ExecutionReport;
|
||||
fingerprint: string;
|
||||
policy: { commission: number; slippage: number };
|
||||
}
|
||||
export const terminal = (status: ExecutionReport['status']) =>
|
||||
['filled', 'cancelled', 'rejected'].includes(status);
|
||||
type DecimalValue = ConstructorParameters<typeof Decimal>[0];
|
||||
export const decimal = (value: DecimalValue) => new Decimal(value);
|
||||
export function amount(value: DecimalValue) {
|
||||
const result = decimal(value).toDecimalPlaces(8).toNumber();
|
||||
if (!Number.isFinite(result)) {
|
||||
throw new Error('Non-finite accounting value');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function identity(data: MarketData): string {
|
||||
return data.eventId ?? createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
||||
}
|
||||
export function fingerprint(order: OrderRequest, strategyId?: string) {
|
||||
return JSON.stringify([
|
||||
order.symbol,
|
||||
order.side,
|
||||
order.quantity,
|
||||
order.orderType,
|
||||
order.limitPrice ?? null,
|
||||
order.stopPrice ?? null,
|
||||
order.timeInForce,
|
||||
strategyId ?? null,
|
||||
]);
|
||||
}
|
||||
export function applyFill(
|
||||
account: Account,
|
||||
symbol: string,
|
||||
side: 'buy' | 'sell',
|
||||
fill: Omit<Fill, 'pnl'>
|
||||
): Fill {
|
||||
const old = account.positions[symbol] ?? { symbol, quantity: 0, averagePrice: 0, realizedPnl: 0 };
|
||||
const signed = decimal(fill.quantity).times(side === 'buy' ? 1 : -1);
|
||||
const next = decimal(old.quantity).plus(signed);
|
||||
const closes = old.quantity !== 0 && Math.sign(old.quantity) !== Math.sign(signed.toNumber());
|
||||
const closed = closes ? Math.min(Math.abs(old.quantity), fill.quantity) : 0;
|
||||
const pnl = amount(
|
||||
decimal(fill.price)
|
||||
.minus(old.averagePrice)
|
||||
.times(closed)
|
||||
.times(Math.sign(old.quantity))
|
||||
.minus(fill.commission)
|
||||
);
|
||||
let averagePrice = old.averagePrice;
|
||||
if (next.isZero()) {
|
||||
averagePrice = 0;
|
||||
} else if (!closes) {
|
||||
averagePrice = amount(
|
||||
decimal(old.averagePrice)
|
||||
.times(Math.abs(old.quantity))
|
||||
.plus(decimal(fill.price).times(fill.quantity))
|
||||
.div(next.abs())
|
||||
);
|
||||
} else if (Math.sign(next.toNumber()) !== Math.sign(old.quantity)) {
|
||||
averagePrice = fill.price;
|
||||
}
|
||||
account.positions[symbol] = {
|
||||
symbol,
|
||||
quantity: amount(next),
|
||||
averagePrice,
|
||||
realizedPnl: amount(decimal(old.realizedPnl).plus(pnl)),
|
||||
};
|
||||
account.cash = amount(
|
||||
decimal(account.cash).minus(signed.times(fill.price)).minus(fill.commission)
|
||||
);
|
||||
account.realizedPnl = amount(decimal(account.realizedPnl).plus(pnl));
|
||||
account.dailyPnl = amount(decimal(account.dailyPnl).plus(pnl));
|
||||
return { ...fill, pnl };
|
||||
}
|
||||
export function accountMetrics(account: Account) {
|
||||
let marketValue = decimal(0),
|
||||
grossExposure = decimal(0),
|
||||
unrealized = decimal(0);
|
||||
for (const position of Object.values(account.positions)) {
|
||||
const quote = account.quotes[position.symbol];
|
||||
const mark = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice;
|
||||
marketValue = marketValue.plus(decimal(position.quantity).times(mark));
|
||||
grossExposure = grossExposure.plus(decimal(position.quantity).abs().times(mark));
|
||||
unrealized = unrealized.plus(
|
||||
decimal(mark).minus(position.averagePrice).times(position.quantity)
|
||||
);
|
||||
}
|
||||
return {
|
||||
cash: account.cash,
|
||||
realizedPnl: account.realizedPnl,
|
||||
unrealizedPnl: amount(unrealized),
|
||||
equity: amount(decimal(account.cash).plus(marketValue)),
|
||||
grossExposure: amount(grossExposure),
|
||||
dailyPnl: account.dailyPnl,
|
||||
};
|
||||
}
|
||||
/** The same stored pricing policy values both fills and their unpaid commissions. */
|
||||
export function fillPrice(order: StoredOrder, quote: Quote) {
|
||||
const raw =
|
||||
order.request.side === 'buy'
|
||||
? quote.ask * (1 + order.policy.slippage)
|
||||
: quote.bid * (1 - order.policy.slippage);
|
||||
return amount(
|
||||
order.request.orderType === 'limit'
|
||||
? order.request.side === 'buy'
|
||||
? Math.min(raw, defined(order.request.limitPrice))
|
||||
: Math.max(raw, defined(order.request.limitPrice))
|
||||
: raw
|
||||
);
|
||||
}
|
||||
/** Quantities are shares; exposure/loss limits are account-currency notional amounts. */
|
||||
export function riskViolations(
|
||||
account: Account,
|
||||
request: OrderRequest,
|
||||
reservations: StoredOrder[],
|
||||
price: number,
|
||||
timestamp: number,
|
||||
commission: number
|
||||
): string[] {
|
||||
const violations: string[] = [];
|
||||
if (request.quantity > account.limits.maxOrderSize) {
|
||||
violations.push('Order quantity limit');
|
||||
}
|
||||
const current = account.positions[request.symbol]?.quantity ?? 0;
|
||||
const signed = request.side === 'buy' ? request.quantity : -request.quantity;
|
||||
const reducing = current * signed < 0 && Math.abs(signed) <= Math.abs(current);
|
||||
if (account.dailyPnl <= -account.limits.maxDailyLoss && !reducing) {
|
||||
violations.push('Daily loss limit');
|
||||
}
|
||||
const quantities = new Map<string, { long: number; short: number }>();
|
||||
for (const p of Object.values(account.positions)) {
|
||||
quantities.set(p.symbol, { long: p.quantity, short: p.quantity });
|
||||
}
|
||||
const proposed = current + signed;
|
||||
quantities.set(request.symbol, { long: proposed, short: proposed });
|
||||
// Paid fees already reduce equity. Reserve only the remaining, unpaid liability.
|
||||
let unpaidFees = decimal(amount(decimal(request.quantity).times(price).times(commission)));
|
||||
for (const order of reservations) {
|
||||
if (terminal(order.report.status)) {
|
||||
continue;
|
||||
}
|
||||
const qty = amount(
|
||||
decimal(order.request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0))
|
||||
);
|
||||
const quote = account.quotes[order.request.symbol];
|
||||
if (quote) {
|
||||
unpaidFees = unpaidFees.plus(
|
||||
amount(decimal(qty).times(fillPrice(order, quote)).times(order.policy.commission))
|
||||
);
|
||||
}
|
||||
const q = quantities.get(order.request.symbol) ?? { long: 0, short: 0 };
|
||||
if (order.request.side === 'buy') {
|
||||
q.long = amount(decimal(q.long).plus(qty));
|
||||
} else {
|
||||
q.short = amount(decimal(q.short).minus(qty));
|
||||
}
|
||||
quantities.set(order.request.symbol, q);
|
||||
}
|
||||
let gross = decimal(0);
|
||||
for (const [symbol, q] of quantities) {
|
||||
const quantity = Math.max(Math.abs(q.long), Math.abs(q.short));
|
||||
if (!quantity) {
|
||||
continue;
|
||||
}
|
||||
const quote = account.quotes[symbol];
|
||||
if (quote && timestamp - quote.timestamp > account.maxQuoteAgeMs && !reducing) {
|
||||
violations.push(`Stale valuation for ${symbol}`);
|
||||
}
|
||||
const mark = symbol === request.symbol ? Math.max(price, quote?.ask ?? price) : quote?.ask;
|
||||
if (!mark || !Number.isFinite(mark)) {
|
||||
violations.push(`Missing valuation for ${symbol}`);
|
||||
continue;
|
||||
}
|
||||
const exposure = decimal(quantity).times(mark);
|
||||
if (quantity > account.limits.maxPositionSize && !(reducing && symbol === request.symbol)) {
|
||||
violations.push(`Position quantity limit: ${symbol}`);
|
||||
}
|
||||
if (exposure.gt(account.limits.maxSymbolExposure) && !(reducing && symbol === request.symbol)) {
|
||||
violations.push(`Symbol notional limit: ${symbol}`);
|
||||
}
|
||||
gross = gross.plus(exposure);
|
||||
}
|
||||
if (gross.gt(account.limits.maxGrossExposure) && !reducing) {
|
||||
violations.push('Gross notional limit');
|
||||
}
|
||||
if (gross.plus(unpaidFees).gt(Math.max(0, accountMetrics(account).equity)) && !reducing) {
|
||||
violations.push('Unlevered capital exposure limit');
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
import type { Account, Fill, StoredOrder } from './model';
|
||||
import type {
|
||||
MarketInput,
|
||||
StrategyCheckpoint,
|
||||
StrategyJournalEvent,
|
||||
StrategyJournalPayload,
|
||||
StrategyOrderIntent,
|
||||
} from './strategy-recovery';
|
||||
|
||||
export interface ExecutionTransaction {
|
||||
account: Account;
|
||||
findOrder(clientOrderId: string): Promise<StoredOrder | undefined>;
|
||||
getOrder(orderId: string): Promise<StoredOrder | undefined>;
|
||||
openOrders(): Promise<StoredOrder[]>;
|
||||
putOrder(order: StoredOrder): Promise<void>;
|
||||
insertFill(orderId: string, fill: Fill): Promise<boolean>;
|
||||
recordEvent(eventId: string, fingerprint: string): Promise<boolean>;
|
||||
appendJournal(payload: StrategyJournalPayload): Promise<void>;
|
||||
nextJournal(cursor: number): Promise<StrategyJournalEvent | undefined>;
|
||||
strategies(): Promise<StrategyCheckpoint[]>;
|
||||
putStrategy(checkpoint: StrategyCheckpoint): Promise<void>;
|
||||
putIntent(intent: StrategyOrderIntent): Promise<void>;
|
||||
nextIntent(): Promise<StrategyOrderIntent | undefined>;
|
||||
nextInput(): Promise<MarketInput | undefined>;
|
||||
putInput(input: MarketInput): Promise<void>;
|
||||
}
|
||||
export interface ExecutionRepository {
|
||||
initialize(accountId: string, initial: Account): Promise<void>;
|
||||
transact<T>(accountId: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export class ExecutionConflictError extends Error {}
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { canonicalJson } from '../canonical-json';
|
||||
import type { MarketData, OrderRequest, StrategyConfig } from '../types';
|
||||
import type { Account, ExecutionReport, Fill } from './model';
|
||||
|
||||
export { canonicalJson } from '../canonical-json';
|
||||
export function strategyConfigHash(config: StrategyConfig, version: string): string {
|
||||
const { enabled: _enabled, ...definition } = config;
|
||||
return createHash('sha256').update(canonicalJson({ definition, version })).digest('hex');
|
||||
}
|
||||
export type StrategyJournalPayload = { account: Account } & (
|
||||
| { kind: 'market'; market: MarketData; recipients: string[] }
|
||||
| { kind: 'execution'; report: ExecutionReport; fills: Fill[] }
|
||||
);
|
||||
export type StrategyJournalEvent = { sequence: number; payload: StrategyJournalPayload };
|
||||
export interface MarketInput {
|
||||
id: string;
|
||||
sequence: number;
|
||||
market: MarketData;
|
||||
status: 'pending' | 'applied';
|
||||
}
|
||||
export interface StrategyCheckpoint {
|
||||
strategyId: string;
|
||||
config: StrategyConfig;
|
||||
configHash: string;
|
||||
version: string;
|
||||
enabled: boolean;
|
||||
cursor: number;
|
||||
state: unknown;
|
||||
}
|
||||
export interface StrategyOrderIntent {
|
||||
clientOrderId: string;
|
||||
strategyId: string;
|
||||
sequence: number;
|
||||
request: OrderRequest;
|
||||
status: 'pending' | 'dispatched';
|
||||
orderId?: string;
|
||||
}
|
||||
export interface RecoverableStrategy {
|
||||
getConfig(): Readonly<StrategyConfig>;
|
||||
getCheckpointVersion(): string | undefined;
|
||||
captureCheckpoint(): unknown;
|
||||
restoreCheckpoint(state: unknown): void;
|
||||
onMarketData(data: MarketData): Promise<void>;
|
||||
onFill(
|
||||
fill: Fill & { orderId: string; symbol: string; side: 'buy' | 'sell'; strategyId?: string }
|
||||
): Promise<void>;
|
||||
onOrderUpdate(report: ExecutionReport): Promise<void>;
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
import { Hono } from 'hono';
|
||||
import { cors } from 'hono/cors';
|
||||
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
|
||||
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di/http-security';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { createRoutes } from './routes/create-routes';
|
||||
|
|
|
|||
|
|
@ -1,342 +0,0 @@
|
|||
import {
|
||||
IncrementalEMA,
|
||||
IncrementalRSI,
|
||||
IncrementalSMA,
|
||||
TechnicalIndicators,
|
||||
} from '@stock-bot/engine';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
|
||||
export interface MacdResult {
|
||||
macd: number[];
|
||||
signal: number[];
|
||||
histogram: number[];
|
||||
}
|
||||
export interface BollingerBandsResult {
|
||||
middle: number[];
|
||||
upper: number[];
|
||||
lower: number[];
|
||||
}
|
||||
export interface StochasticResult {
|
||||
k: number[];
|
||||
d: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper class for the Rust TA library with TypeScript-friendly interfaces
|
||||
*/
|
||||
export class TechnicalAnalysis {
|
||||
private indicators: TechnicalIndicators;
|
||||
|
||||
constructor() {
|
||||
this.indicators = new TechnicalIndicators();
|
||||
}
|
||||
|
||||
// Simple indicators
|
||||
sma(values: number[], period: number): number[] {
|
||||
return this.indicators.calculateSma(values, period);
|
||||
}
|
||||
|
||||
ema(values: number[], period: number): number[] {
|
||||
return this.indicators.calculateEma(values, period);
|
||||
}
|
||||
|
||||
rsi(values: number[], period: number): number[] {
|
||||
return this.indicators.calculateRsi(values, period);
|
||||
}
|
||||
|
||||
atr(high: number[], low: number[], close: number[], period: number): number[] {
|
||||
return this.indicators.calculateAtr(high, low, close, period);
|
||||
}
|
||||
|
||||
// Complex indicators with parsed results
|
||||
macd(values: number[], fastPeriod = 12, slowPeriod = 26, signalPeriod = 9): MacdResult {
|
||||
const result = this.indicators.calculateMacd(values, fastPeriod, slowPeriod, signalPeriod);
|
||||
return JSON.parse(result);
|
||||
}
|
||||
|
||||
bollingerBands(values: number[], period = 20, stdDev = 2): BollingerBandsResult {
|
||||
const result = this.indicators.calculateBollingerBands(values, period, stdDev);
|
||||
return JSON.parse(result);
|
||||
}
|
||||
|
||||
stochastic(
|
||||
high: number[],
|
||||
low: number[],
|
||||
close: number[],
|
||||
kPeriod = 14,
|
||||
dPeriod = 3,
|
||||
smoothK = 1
|
||||
): StochasticResult {
|
||||
const result = this.indicators.calculateStochastic(high, low, close, kPeriod, dPeriod, smoothK);
|
||||
return JSON.parse(result);
|
||||
}
|
||||
|
||||
// Helper to get the latest value from an indicator array
|
||||
static latest(values: number[]): number | undefined {
|
||||
return values[values.length - 1];
|
||||
}
|
||||
|
||||
// Helper to check for crossovers
|
||||
static crossover(series1: number[], series2: number[]): boolean {
|
||||
if (series1.length < 2 || series2.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const prev1 = at(series1, series1.length - 2);
|
||||
const curr1 = at(series1, series1.length - 1);
|
||||
const prev2 = at(series2, series2.length - 2);
|
||||
const curr2 = at(series2, series2.length - 1);
|
||||
return prev1 <= prev2 && curr1 > curr2;
|
||||
}
|
||||
|
||||
static crossunder(series1: number[], series2: number[]): boolean {
|
||||
if (series1.length < 2 || series2.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const prev1 = at(series1, series1.length - 2);
|
||||
const curr1 = at(series1, series1.length - 1);
|
||||
const prev2 = at(series2, series2.length - 2);
|
||||
const curr2 = at(series2, series2.length - 1);
|
||||
return prev1 >= prev2 && curr1 < curr2;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental indicator manager for streaming data
|
||||
*/
|
||||
export class IncrementalIndicators {
|
||||
private indicators: Map<string, IncrementalSMA | IncrementalEMA | IncrementalRSI> = new Map();
|
||||
|
||||
createSMA(key: string, period: number): IncrementalSMA {
|
||||
const indicator = new IncrementalSMA(period);
|
||||
this.indicators.set(key, indicator);
|
||||
return indicator;
|
||||
}
|
||||
|
||||
createEMA(key: string, period: number): IncrementalEMA {
|
||||
const indicator = new IncrementalEMA(period);
|
||||
this.indicators.set(key, indicator);
|
||||
return indicator;
|
||||
}
|
||||
|
||||
createRSI(key: string, period: number): IncrementalRSI {
|
||||
const indicator = new IncrementalRSI(period);
|
||||
this.indicators.set(key, indicator);
|
||||
return indicator;
|
||||
}
|
||||
|
||||
get(key: string): IncrementalSMA | IncrementalEMA | IncrementalRSI | undefined {
|
||||
return this.indicators.get(key);
|
||||
}
|
||||
|
||||
update(key: string, value: number): number | null {
|
||||
const indicator = this.indicators.get(key);
|
||||
if (!indicator) {
|
||||
throw new Error(`Indicator ${key} not found`);
|
||||
}
|
||||
return indicator.update(value);
|
||||
}
|
||||
|
||||
current(key: string): number | null {
|
||||
const indicator = this.indicators.get(key);
|
||||
if (!indicator) {
|
||||
throw new Error(`Indicator ${key} not found`);
|
||||
}
|
||||
return indicator.current();
|
||||
}
|
||||
|
||||
reset(key: string): void {
|
||||
const indicator = this.indicators.get(key);
|
||||
if (indicator && 'reset' in indicator) {
|
||||
indicator.reset();
|
||||
}
|
||||
}
|
||||
|
||||
entries() {
|
||||
return this.indicators.entries();
|
||||
}
|
||||
|
||||
deletePrefix(prefix: string): void {
|
||||
for (const key of this.indicators.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
this.indicators.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resetAll(): void {
|
||||
this.indicators.forEach(indicator => {
|
||||
if ('reset' in indicator) {
|
||||
indicator.reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signal generator using technical indicators
|
||||
*/
|
||||
export interface TradingSignal {
|
||||
symbol: string;
|
||||
timestamp: number;
|
||||
action: 'BUY' | 'SELL' | 'HOLD';
|
||||
strength: number; // 0-1
|
||||
indicators: Record<string, number>;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export class SignalGenerator {
|
||||
private ta: TechnicalAnalysis;
|
||||
|
||||
constructor() {
|
||||
this.ta = new TechnicalAnalysis();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate signals based on multiple indicators
|
||||
*/
|
||||
generateSignals(
|
||||
symbol: string,
|
||||
prices: {
|
||||
close: number[];
|
||||
high: number[];
|
||||
low: number[];
|
||||
volume: number[];
|
||||
},
|
||||
timestamp: number
|
||||
): TradingSignal {
|
||||
const indicators: Record<string, number> = {};
|
||||
let buySignals = 0;
|
||||
let sellSignals = 0;
|
||||
let totalWeight = 0;
|
||||
const reasons: string[] = [];
|
||||
|
||||
// RSI signals
|
||||
if (prices.close.length >= 14) {
|
||||
const rsi = this.ta.rsi(prices.close, 14);
|
||||
const currentRsi = TechnicalAnalysis.latest(rsi);
|
||||
if (currentRsi !== undefined) {
|
||||
indicators.rsi = currentRsi;
|
||||
if (currentRsi < 30) {
|
||||
buySignals += 2;
|
||||
totalWeight += 2;
|
||||
reasons.push('RSI oversold');
|
||||
} else if (currentRsi > 70) {
|
||||
sellSignals += 2;
|
||||
totalWeight += 2;
|
||||
reasons.push('RSI overbought');
|
||||
} else {
|
||||
totalWeight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MACD signals
|
||||
if (prices.close.length >= 26) {
|
||||
const macd = this.ta.macd(prices.close);
|
||||
const currentMacd = TechnicalAnalysis.latest(macd.macd);
|
||||
const currentSignal = TechnicalAnalysis.latest(macd.signal);
|
||||
const currentHistogram = TechnicalAnalysis.latest(macd.histogram);
|
||||
|
||||
if (currentMacd !== undefined && currentSignal !== undefined) {
|
||||
indicators.macd = currentMacd;
|
||||
indicators.macdSignal = currentSignal;
|
||||
indicators.macdHistogram = currentHistogram || 0;
|
||||
|
||||
if (TechnicalAnalysis.crossover(macd.macd, macd.signal)) {
|
||||
buySignals += 3;
|
||||
totalWeight += 3;
|
||||
reasons.push('MACD bullish crossover');
|
||||
} else if (TechnicalAnalysis.crossunder(macd.macd, macd.signal)) {
|
||||
sellSignals += 3;
|
||||
totalWeight += 3;
|
||||
reasons.push('MACD bearish crossover');
|
||||
} else {
|
||||
totalWeight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bollinger Bands signals
|
||||
if (prices.close.length >= 20) {
|
||||
const bb = this.ta.bollingerBands(prices.close, 20, 2);
|
||||
const currentPrice = at(prices.close, prices.close.length - 1);
|
||||
const currentUpper = TechnicalAnalysis.latest(bb.upper);
|
||||
const currentLower = TechnicalAnalysis.latest(bb.lower);
|
||||
const currentMiddle = TechnicalAnalysis.latest(bb.middle);
|
||||
|
||||
if (currentUpper && currentLower && currentMiddle) {
|
||||
indicators.bbUpper = currentUpper;
|
||||
indicators.bbLower = currentLower;
|
||||
indicators.bbMiddle = currentMiddle;
|
||||
|
||||
const bbPercent = (currentPrice - currentLower) / (currentUpper - currentLower);
|
||||
indicators.bbPercent = bbPercent;
|
||||
|
||||
if (bbPercent < 0.2) {
|
||||
buySignals += 2;
|
||||
totalWeight += 2;
|
||||
reasons.push('Near lower Bollinger Band');
|
||||
} else if (bbPercent > 0.8) {
|
||||
sellSignals += 2;
|
||||
totalWeight += 2;
|
||||
reasons.push('Near upper Bollinger Band');
|
||||
} else {
|
||||
totalWeight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stochastic signals
|
||||
if (prices.high.length >= 14 && prices.low.length >= 14 && prices.close.length >= 14) {
|
||||
const stoch = this.ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3);
|
||||
const currentK = TechnicalAnalysis.latest(stoch.k);
|
||||
const currentD = TechnicalAnalysis.latest(stoch.d);
|
||||
|
||||
if (currentK !== undefined && currentD !== undefined) {
|
||||
indicators.stochK = currentK;
|
||||
indicators.stochD = currentD;
|
||||
|
||||
if (currentK < 20 && currentD < 20) {
|
||||
buySignals += 1;
|
||||
totalWeight += 1;
|
||||
reasons.push('Stochastic oversold');
|
||||
} else if (currentK > 80 && currentD > 80) {
|
||||
sellSignals += 1;
|
||||
totalWeight += 1;
|
||||
reasons.push('Stochastic overbought');
|
||||
} else {
|
||||
totalWeight += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine overall signal
|
||||
let action: 'BUY' | 'SELL' | 'HOLD' = 'HOLD';
|
||||
let strength = 0;
|
||||
|
||||
if (totalWeight > 0) {
|
||||
const buyStrength = buySignals / totalWeight;
|
||||
const sellStrength = sellSignals / totalWeight;
|
||||
|
||||
if (buyStrength > 0.5) {
|
||||
action = 'BUY';
|
||||
strength = buyStrength;
|
||||
} else if (sellStrength > 0.5) {
|
||||
action = 'SELL';
|
||||
strength = sellStrength;
|
||||
} else {
|
||||
action = 'HOLD';
|
||||
strength = Math.max(buyStrength, sellStrength);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
symbol,
|
||||
timestamp,
|
||||
action,
|
||||
strength,
|
||||
indicators,
|
||||
reason: reasons.join('; ') || 'No clear signal',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalJson } from '../canonical-json';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperConnectionSchema,
|
||||
|
|
@ -13,7 +13,7 @@ import {
|
|||
type PaperFrameInput,
|
||||
type PaperReadiness,
|
||||
type PaperRuntime,
|
||||
} from '../contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import type {
|
||||
CanonicalAccount,
|
||||
CanonicalExecutionRepository,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import type { PaperDeploymentStatus } from '@stock-bot/stock-config/paper-deployments';
|
||||
import type { PaperReadiness, PaperRuntime } from '../contracts/paper-runtime';
|
||||
import type { PaperReadiness, PaperRuntime } from '@stock-bot/stock-config/paper-runtime';
|
||||
import type { CanonicalExecutionRepository, CanonicalPostgres } from '../execution/canonical-paper';
|
||||
import {
|
||||
authorizedPaperPackage,
|
||||
|
|
@ -8,9 +8,9 @@ import {
|
|||
paperHash,
|
||||
readPaperDeployment,
|
||||
verifyPaperEvidenceCustody,
|
||||
} from './paper-deployment-custody';
|
||||
} from '@stock-bot/trading-runtime/paper-deployment-custody';
|
||||
import type { createPromotedPaperRuntime } from './paper-host';
|
||||
import { paperHostUrl, readPaperHostIdentity } from './paper-host-identity';
|
||||
import { paperHostUrl, readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
|
||||
export const unboundPaperReadiness = (reason = 'deployment-not-bound'): PaperReadiness => ({
|
||||
configured: false,
|
||||
|
|
|
|||
|
|
@ -1,60 +0,0 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { MarketDataService } from '../services/MarketDataService';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { OrchestratorServices, OrderRequest } from '../types';
|
||||
|
||||
/** Compatibility facade: no independent simulator, balance, or position book. */
|
||||
export class PaperTradingManager extends EventEmitter {
|
||||
constructor(
|
||||
_container: OrchestratorServices,
|
||||
_storage: StorageService,
|
||||
_market: MarketDataService,
|
||||
private readonly execution: ExecutionService,
|
||||
_initialBalance = 100000
|
||||
) {
|
||||
super();
|
||||
}
|
||||
executeOrder(order: OrderRequest) {
|
||||
return this.execution.submitOrder(order);
|
||||
}
|
||||
updateMarketPrice(
|
||||
symbol: string,
|
||||
bid: number,
|
||||
ask: number,
|
||||
eventId: string,
|
||||
timestamp: number,
|
||||
size: number
|
||||
) {
|
||||
return this.execution.onMarketData({
|
||||
type: 'quote',
|
||||
eventId,
|
||||
data: { symbol, bid, ask, bidSize: size, askSize: size, timestamp },
|
||||
});
|
||||
}
|
||||
getAccount() {
|
||||
return this.execution.getAccount();
|
||||
}
|
||||
getAllPositions() {
|
||||
return this.execution.getPositions();
|
||||
}
|
||||
async getPosition(symbol: string) {
|
||||
return (await this.getAllPositions()).find(p => p.symbol === symbol);
|
||||
}
|
||||
async getPerformanceMetrics() {
|
||||
const account = await this.getAccount();
|
||||
return {
|
||||
cash: account.cash,
|
||||
currentEquity: account.equity,
|
||||
netPnl: account.realizedPnl + account.unrealizedPnl,
|
||||
realizedPnl: account.realizedPnl,
|
||||
unrealizedPnl: account.unrealizedPnl,
|
||||
};
|
||||
}
|
||||
checkPendingOrders() {
|
||||
throw new Error('Pending orders are processed only by ordered market events');
|
||||
}
|
||||
reset() {
|
||||
throw new Error('Implicit paper account reset is disabled; use a new account ID');
|
||||
}
|
||||
}
|
||||
|
|
@ -6,14 +6,14 @@ import {
|
|||
compareEventKeys,
|
||||
matchingCommandSchema,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../contracts/canonical-execution';
|
||||
} from '@stock-bot/stock-config/canonical-execution';
|
||||
import {
|
||||
paperFrameSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperFrame,
|
||||
type PaperFrameInput,
|
||||
} from '../contracts/paper-runtime';
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
import type { CanonicalAccount, CanonicalPaperInput } from '../execution/canonical-paper';
|
||||
|
||||
type Observation = PaperFrame['observations'][number];
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/paper-deployment-custody';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Shared read-only artifact inspection. */
|
||||
export * from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
|
|
@ -5,8 +5,8 @@ import type { StrategyVersionPackage } from '@stock-bot/types';
|
|||
import type { CanonicalExecutionRepository } from '../execution/canonical-paper';
|
||||
import { importRetainedProgram } from '../strategies/retained-program';
|
||||
import { CanonicalPaperRuntime } from './CanonicalPaperRuntime';
|
||||
import { retainedPaperDeployment } from './paper-deployment-custody';
|
||||
import { verifyPaperHostBuild } from './paper-host-identity';
|
||||
import { retainedPaperDeployment } from '@stock-bot/trading-runtime/paper-deployment-custody';
|
||||
import { verifyPaperHostBuild } from '@stock-bot/trading-runtime/paper-host-identity';
|
||||
|
||||
/** Caller must have verified the immutable operator promotion and current permission before calling. */
|
||||
export async function createPromotedPaperRuntime(options: {
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/paper-operator';
|
||||
|
|
@ -1,14 +1,12 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
import {
|
||||
orchestratorDiagnosticSchema,
|
||||
paperDiagnosticSchema,
|
||||
} from '@stock-bot/stock-config/diagnostics';
|
||||
import { createAnalyticsRoutes } from '../api/rest/analytics';
|
||||
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import { createBacktestRoutes } from '../api/rest/backtest';
|
||||
import { createPaperRoutes } from '../api/rest/paper';
|
||||
import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments';
|
||||
import { readCanonicalBuildIdentity } from '../backtest/canonical-build';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
|
||||
/**
|
||||
|
|
@ -16,7 +14,7 @@ import type { OrchestratorServices as IServiceContainer } from '../types';
|
|||
*/
|
||||
export function createRoutes(
|
||||
services: IServiceContainer,
|
||||
_io?: SocketIOServer,
|
||||
_io?: unknown,
|
||||
origins?: readonly string[]
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
|
|
@ -106,7 +104,6 @@ export function createRoutes(
|
|||
);
|
||||
app.route('/api/orders', unavailable);
|
||||
app.route('/api/positions', unavailable);
|
||||
app.route('/api/analytics', createAnalyticsRoutes(services));
|
||||
app.route('/api/backtest', createBacktestRoutes(services));
|
||||
|
||||
// Add request logging middleware
|
||||
|
|
|
|||
|
|
@ -1,197 +0,0 @@
|
|||
import axios, { type AxiosRequestConfig } from 'axios';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
backtestAnalysisSchema,
|
||||
correlationRequestSchema,
|
||||
correlationResponseSchema,
|
||||
dateRangeSchema,
|
||||
optimizationRequestSchema,
|
||||
PerformanceMetricsSchema,
|
||||
portfolioWeightsSchema,
|
||||
predictionRequestSchema,
|
||||
predictionResponseSchema,
|
||||
regimeResponseSchema,
|
||||
RiskMetricsSchema,
|
||||
type OptimizationParams,
|
||||
} from '../contracts/analytics';
|
||||
import type { OrchestratorServices } from '../types';
|
||||
import { AnalyticsServiceError } from './analytics-error';
|
||||
|
||||
export interface AnalyticsTransport {
|
||||
request(config: AxiosRequestConfig): Promise<{ data: unknown }>;
|
||||
}
|
||||
|
||||
/** Validated, bounded upstream access. Failure is never a fabricated financial observation. */
|
||||
export class AnalyticsService {
|
||||
private readonly client: AnalyticsTransport;
|
||||
private readonly now: () => number;
|
||||
private readonly analyticsUrl: string;
|
||||
private readonly timeoutMs: number;
|
||||
private readonly cache = new Map<string, { data: unknown; expiresAt: number }>();
|
||||
constructor(
|
||||
private readonly container: Pick<OrchestratorServices, 'logger'>,
|
||||
options: {
|
||||
client?: AnalyticsTransport;
|
||||
now?: () => number;
|
||||
baseUrl?: string;
|
||||
timeoutMs?: number;
|
||||
} = {}
|
||||
) {
|
||||
this.client = options.client ?? axios;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.analyticsUrl =
|
||||
options.baseUrl ?? process.env.ANALYTICS_SERVICE_URL ?? 'http://localhost:3003';
|
||||
this.timeoutMs = options.timeoutMs ?? 5000;
|
||||
if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 60000) {
|
||||
throw new Error('Analytics timeout must be an integer between 1 and 60000 ms');
|
||||
}
|
||||
}
|
||||
async getPerformanceMetrics(portfolioId: string, startDate: Date, endDate: Date) {
|
||||
const range = dateRangeSchema.parse({
|
||||
startDate: startDate.toISOString(),
|
||||
endDate: endDate.toISOString(),
|
||||
});
|
||||
return this.fetch(
|
||||
'/analytics/performance/' + encodeURIComponent(portfolioId),
|
||||
PerformanceMetricsSchema,
|
||||
{
|
||||
params: { start_date: range.startDate, end_date: range.endDate },
|
||||
cacheKey: JSON.stringify(['performance', portfolioId, range]),
|
||||
ttl: 60000,
|
||||
}
|
||||
);
|
||||
}
|
||||
async getRiskMetrics(portfolioId: string) {
|
||||
return this.fetch('/analytics/risk/' + encodeURIComponent(portfolioId), RiskMetricsSchema, {
|
||||
cacheKey: JSON.stringify(['risk', portfolioId]),
|
||||
ttl: 60000,
|
||||
});
|
||||
}
|
||||
async optimizePortfolio(input: OptimizationParams) {
|
||||
const request = optimizationRequestSchema.parse(input);
|
||||
const constraints = request.constraints;
|
||||
const raw = await this.fetch(
|
||||
'/optimize/portfolio',
|
||||
portfolioWeightsSchema.refine(
|
||||
value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols),
|
||||
'Portfolio symbol identity mismatch'
|
||||
),
|
||||
{
|
||||
data: {
|
||||
symbols: request.symbols,
|
||||
returns: request.returns,
|
||||
constraints: constraints
|
||||
? {
|
||||
min_weight: constraints.minWeight ?? 0,
|
||||
max_weight: constraints.maxWeight ?? 1,
|
||||
target_return: constraints.targetReturn,
|
||||
max_risk: constraints.maxRisk,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
symbols: raw.symbols,
|
||||
weights: raw.weights,
|
||||
expectedReturn: raw.expected_return,
|
||||
expectedRisk: raw.expected_risk,
|
||||
sharpeRatio: raw.sharpe_ratio,
|
||||
};
|
||||
}
|
||||
async detectMarketRegime(): Promise<string> {
|
||||
const result = await this.fetch('/analytics/regime', regimeResponseSchema, {
|
||||
cacheKey: 'regime',
|
||||
ttl: 300000,
|
||||
});
|
||||
return result.regime;
|
||||
}
|
||||
async calculateCorrelationMatrix(symbols: string[]): Promise<number[][]> {
|
||||
const request = correlationRequestSchema.parse({ symbols });
|
||||
const response = await this.fetch(
|
||||
'/analytics/correlation',
|
||||
correlationResponseSchema.refine(
|
||||
value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols),
|
||||
'Correlation symbol identity mismatch'
|
||||
),
|
||||
{ data: request.symbols }
|
||||
);
|
||||
return response.matrix;
|
||||
}
|
||||
async runBacktestAnalysis(backtestId: string) {
|
||||
return this.fetch(
|
||||
'/analytics/backtest/' + encodeURIComponent(backtestId),
|
||||
backtestAnalysisSchema.refine(
|
||||
value => value.backtest_id === backtestId,
|
||||
'Backtest identity mismatch'
|
||||
)
|
||||
);
|
||||
}
|
||||
async predictWithModel(modelId: string, features: Record<string, number>) {
|
||||
const request = predictionRequestSchema.parse({ modelId, features });
|
||||
return this.fetch(
|
||||
'/models/predict',
|
||||
predictionResponseSchema.refine(
|
||||
value => value.model_id === request.modelId,
|
||||
'Model identity mismatch'
|
||||
),
|
||||
{ data: { model_id: request.modelId, features: request.features } }
|
||||
);
|
||||
}
|
||||
private async fetch<T>(
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
options: {
|
||||
data?: unknown;
|
||||
params?: Record<string, string>;
|
||||
cacheKey?: string;
|
||||
ttl?: number;
|
||||
} = {}
|
||||
): Promise<T> {
|
||||
const key = options.cacheKey;
|
||||
const cached = key ? this.cache.get(key) : undefined;
|
||||
if (cached && this.now() < cached.expiresAt) {
|
||||
return schema.parse(structuredClone(cached.data));
|
||||
}
|
||||
if (key) {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
let response: { data: unknown };
|
||||
try {
|
||||
response = await this.client.request({
|
||||
url: this.analyticsUrl + path,
|
||||
method: options.data === undefined ? 'GET' : 'POST',
|
||||
params: options.params,
|
||||
data: options.data,
|
||||
timeout: this.timeoutMs,
|
||||
maxContentLength: 1048576,
|
||||
});
|
||||
} catch {
|
||||
this.container.logger.error('Analytics upstream unavailable', { path });
|
||||
throw new AnalyticsServiceError('unavailable');
|
||||
}
|
||||
const parsed = schema.safeParse(response.data);
|
||||
if (!parsed.success) {
|
||||
this.container.logger.error('Invalid analytics upstream response', { path });
|
||||
throw new AnalyticsServiceError('invalid-response');
|
||||
}
|
||||
if (key) {
|
||||
for (const [entry, value] of this.cache) {
|
||||
if (this.now() >= value.expiresAt) {
|
||||
this.cache.delete(entry);
|
||||
}
|
||||
}
|
||||
if (this.cache.size >= 128) {
|
||||
const oldest = this.cache.keys().next().value;
|
||||
if (oldest !== undefined) {
|
||||
this.cache.delete(oldest);
|
||||
}
|
||||
}
|
||||
this.cache.set(key, {
|
||||
data: structuredClone(parsed.data),
|
||||
expiresAt: this.now() + (options.ttl ?? 60000),
|
||||
});
|
||||
}
|
||||
return structuredClone(parsed.data);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,436 +0,0 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { BacktestExecutionRepository } from '../execution/BacktestExecutionRepository';
|
||||
import {
|
||||
accountMetrics,
|
||||
amount,
|
||||
decimal,
|
||||
defaultRiskLimits,
|
||||
identity,
|
||||
terminal,
|
||||
type Account,
|
||||
type ExecutionChange,
|
||||
type ExecutionReport,
|
||||
type Fill,
|
||||
type Quote,
|
||||
} from '../execution/model';
|
||||
import { PostgresExecutionRepository } from '../execution/PostgresExecutionRepository';
|
||||
import { ExecutionConflictError, type ExecutionRepository } from '../execution/repository';
|
||||
import { SimulationExecution } from '../execution/SimulationExecution';
|
||||
import type { RecoverableStrategy } from '../execution/strategy-recovery';
|
||||
import { StrategyRecovery } from '../execution/StrategyRecovery';
|
||||
import {
|
||||
MarketDataSchema,
|
||||
ModeConfigSchema,
|
||||
OrderRequestSchema,
|
||||
type MarketData,
|
||||
type ModeConfig,
|
||||
type OrchestratorServices,
|
||||
type OrderRequest,
|
||||
} from '../types';
|
||||
import type { StorageService } from './StorageService';
|
||||
|
||||
export type { ExecutionReport, Fill } from '../execution/model';
|
||||
export type StrategyOrderUpdate = ExecutionReport;
|
||||
export interface StrategyFill extends Fill {
|
||||
orderId: string;
|
||||
symbol: string;
|
||||
side: 'buy' | 'sell';
|
||||
strategyId?: string;
|
||||
positionUpdate?: unknown;
|
||||
}
|
||||
export class UnsupportedExecutionError extends Error {}
|
||||
|
||||
/** Sole runtime order gateway. Paper state commits atomically; backtests opt into a run-local ledger. */
|
||||
export class ExecutionService extends EventEmitter {
|
||||
private repository?: ExecutionRepository;
|
||||
private accountId = '';
|
||||
private mode: 'paper' | 'backtest' | undefined;
|
||||
private engine?: TradingEngine;
|
||||
private observer?: (report: ExecutionReport, fills: StrategyFill[]) => Promise<void>;
|
||||
private tail: Promise<unknown> = Promise.resolve();
|
||||
private closing = false;
|
||||
private readonly simulation: SimulationExecution;
|
||||
private readonly recovery: StrategyRecovery;
|
||||
requiresDurableCheckpoint(): boolean {
|
||||
return this.mode === 'paper';
|
||||
}
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
_storage: StorageService,
|
||||
private readonly options: {
|
||||
repository?: ExecutionRepository;
|
||||
clock?: () => number;
|
||||
allowedMode?: 'paper' | 'backtest';
|
||||
} = {}
|
||||
) {
|
||||
super();
|
||||
this.simulation = new SimulationExecution({
|
||||
now: quote => this.now(quote),
|
||||
isBacktest: () => this.mode === 'backtest',
|
||||
});
|
||||
this.recovery = new StrategyRecovery({
|
||||
accountId: () => this.accountId,
|
||||
isBacktest: () => this.mode === 'backtest',
|
||||
serialized: work => this.serialized(work),
|
||||
transact: work => this.store().transact(this.accountId, work),
|
||||
dispatch: (tx, intent) =>
|
||||
this.simulation.acceptOrder(tx, intent.request, intent.strategyId, true),
|
||||
publish: change => this.publish(change),
|
||||
consumeMarketInput: () => this.consumeMarketInput(),
|
||||
observationFailed: error =>
|
||||
this.container.logger.error('Strategy observation failed after checkpoint commit', {
|
||||
error,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
setObserver(observer: (report: ExecutionReport, fills: StrategyFill[]) => Promise<void>) {
|
||||
this.observer = observer;
|
||||
}
|
||||
async initialize(input: ModeConfig, engine: TradingEngine): Promise<void> {
|
||||
const config = ModeConfigSchema.parse(input);
|
||||
if (config.mode === 'live') {
|
||||
throw new UnsupportedExecutionError(
|
||||
'Live trading is disabled: no real broker adapter exists'
|
||||
);
|
||||
}
|
||||
if (this.options.allowedMode && config.mode !== this.options.allowedMode) {
|
||||
throw new UnsupportedExecutionError(
|
||||
`Runtime composition only permits ${this.options.allowedMode} mode; cannot initialize ${config.mode}`
|
||||
);
|
||||
}
|
||||
await this.tail;
|
||||
this.closing = false;
|
||||
this.mode = undefined;
|
||||
const repository =
|
||||
this.options.repository ??
|
||||
(config.mode === 'backtest'
|
||||
? new BacktestExecutionRepository()
|
||||
: this.container.postgres
|
||||
? new PostgresExecutionRepository(this.container.postgres)
|
||||
: undefined);
|
||||
if (!repository) {
|
||||
throw new UnsupportedExecutionError(
|
||||
'Paper execution requires the PostgreSQL simulation ledger'
|
||||
);
|
||||
}
|
||||
if (config.mode === 'paper' && repository instanceof BacktestExecutionRepository) {
|
||||
throw new UnsupportedExecutionError('Run-local storage cannot back a paper account');
|
||||
}
|
||||
const now = this.options.clock?.() ?? Date.now();
|
||||
const initialCapital = config.mode === 'paper' ? config.startingCapital : config.initialCapital;
|
||||
const account: Account = {
|
||||
initialCapital,
|
||||
cash: initialCapital,
|
||||
realizedPnl: 0,
|
||||
dailyPnl: 0,
|
||||
day: new Date(now).toISOString().slice(0, 10),
|
||||
commission: config.commission ?? 0.001,
|
||||
slippage: config.slippage ?? 0.0001,
|
||||
limits: config.riskLimits ?? { ...defaultRiskLimits },
|
||||
maxQuoteAgeMs:
|
||||
config.mode === 'paper' ? (config.maxQuoteAgeMs ?? 60000) : Number.MAX_SAFE_INTEGER,
|
||||
positions: {},
|
||||
quotes: {},
|
||||
strategyPositions: {},
|
||||
};
|
||||
const id =
|
||||
config.mode === 'paper'
|
||||
? (config.accountId ?? 'paper-default')
|
||||
: (config.runId ?? randomUUID());
|
||||
await repository.initialize(id, account);
|
||||
this.repository = repository;
|
||||
this.accountId = id;
|
||||
this.mode = config.mode;
|
||||
this.engine = engine;
|
||||
engine.updateRiskLimits(account.limits);
|
||||
}
|
||||
private serialized<T>(work: () => Promise<T>): Promise<T> {
|
||||
const result = this.tail.then(work);
|
||||
this.tail = result.catch(() => {});
|
||||
return result;
|
||||
}
|
||||
private store() {
|
||||
this.recovery.assertExternalIO();
|
||||
if (!this.repository || !this.mode || this.closing) {
|
||||
throw new UnsupportedExecutionError(
|
||||
'Execution gateway is not initialized or is shutting down'
|
||||
);
|
||||
}
|
||||
return this.repository;
|
||||
}
|
||||
private now(quote?: Quote) {
|
||||
return this.mode === 'backtest'
|
||||
? (quote?.timestamp ?? 0)
|
||||
: (this.options.clock?.() ?? Date.now());
|
||||
}
|
||||
async submitOrder(
|
||||
input: OrderRequest,
|
||||
context: { strategyId?: string } = {}
|
||||
): Promise<ExecutionReport> {
|
||||
this.recovery.assertExternalIO();
|
||||
const request = OrderRequestSchema.parse(input);
|
||||
// The API must supply stable IDs for retried requests; strategy IDs are derived from source events.
|
||||
request.clientOrderId ??= randomUUID();
|
||||
return this.serialized(async () => {
|
||||
const change = await this.store().transact(this.accountId, async tx => {
|
||||
return this.simulation.acceptOrder(tx, request, context.strategyId);
|
||||
});
|
||||
await this.publish(change);
|
||||
return change.report;
|
||||
});
|
||||
}
|
||||
/** Durable admission precedes processing; a strategy failure cannot discard later inputs. */
|
||||
async enqueueMarketData(input: MarketData): Promise<boolean> {
|
||||
const data = MarketDataSchema.parse(input);
|
||||
return this.serialized(() =>
|
||||
this.store().transact(this.accountId, async tx => {
|
||||
const key = identity(data);
|
||||
const hash = createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
||||
if (!(await tx.recordEvent(key, hash))) {
|
||||
return false;
|
||||
}
|
||||
const quote = this.quoteFor(data);
|
||||
const previous =
|
||||
tx.account.admittedTimes?.[data.data.symbol] ??
|
||||
tx.account.quotes[data.data.symbol]?.timestamp;
|
||||
if (previous !== undefined && quote.timestamp < previous) {
|
||||
throw new ExecutionConflictError('Out-of-order market data');
|
||||
}
|
||||
if (this.mode === 'paper' && !this.freshQuote(tx.account, quote)) {
|
||||
throw new Error('Stale or future market data');
|
||||
}
|
||||
const sequence = (tx.account.inputSequence ?? 0) + 1;
|
||||
if (!Number.isSafeInteger(sequence)) {
|
||||
throw new Error('Market input sequence exhausted');
|
||||
}
|
||||
tx.account.inputSequence = sequence;
|
||||
(tx.account.admittedTimes ??= {})[data.data.symbol] = quote.timestamp;
|
||||
await tx.putInput({ id: key, sequence, market: data, status: 'pending' });
|
||||
return true;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async onMarketData(input: MarketData): Promise<boolean> {
|
||||
const admitted = await this.enqueueMarketData(input);
|
||||
await this.serialized(async () => {
|
||||
while (await this.consumeMarketInput()) {
|
||||
/* drain unblocked inputs */
|
||||
}
|
||||
});
|
||||
return admitted;
|
||||
}
|
||||
|
||||
private quoteFor(data: MarketData): Quote {
|
||||
const quote: Quote =
|
||||
data.type === 'quote'
|
||||
? { ...data.data, eventId: identity(data) }
|
||||
: {
|
||||
bid: data.type === 'bar' ? data.data.close : data.data.price,
|
||||
ask: data.type === 'bar' ? data.data.close : data.data.price,
|
||||
bidSize: data.type === 'bar' ? data.data.volume : data.data.size,
|
||||
askSize: data.type === 'bar' ? data.data.volume : data.data.size,
|
||||
timestamp: data.data.timestamp,
|
||||
eventId: identity(data),
|
||||
};
|
||||
if (
|
||||
![quote.bid, quote.ask, quote.bidSize, quote.askSize, quote.timestamp].every(
|
||||
Number.isFinite
|
||||
) ||
|
||||
quote.bid <= 0 ||
|
||||
quote.ask < quote.bid ||
|
||||
quote.bidSize < 0 ||
|
||||
quote.askSize < 0
|
||||
) {
|
||||
throw new Error('Invalid market quote/liquidity');
|
||||
}
|
||||
return quote;
|
||||
}
|
||||
private freshQuote(account: Account, quote: Quote) {
|
||||
const now = this.now(quote);
|
||||
return quote.timestamp <= now && now - quote.timestamp <= account.maxQuoteAgeMs;
|
||||
}
|
||||
|
||||
private async consumeMarketInput(): Promise<boolean> {
|
||||
const outcome = await this.store().transact(this.accountId, async tx => {
|
||||
const registrations = await tx.strategies();
|
||||
if (
|
||||
(await tx.nextIntent()) ||
|
||||
registrations.some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const input = await tx.nextInput();
|
||||
if (!input) {
|
||||
return undefined;
|
||||
}
|
||||
const data = input.market,
|
||||
quote = this.quoteFor(data);
|
||||
this.simulation.rollDay(tx.account, quote.timestamp);
|
||||
tx.account.quotes[data.data.symbol] = quote;
|
||||
const orders = await tx.openOrders(),
|
||||
changes: ExecutionChange[] = [];
|
||||
for (const order of orders) {
|
||||
const before = order.report.status;
|
||||
const expired =
|
||||
order.request.timeInForce === 'DAY' &&
|
||||
new Date(order.report.timestamp).toISOString().slice(0, 10) <
|
||||
new Date(quote.timestamp).toISOString().slice(0, 10);
|
||||
if (expired) {
|
||||
order.report.status = 'cancelled';
|
||||
}
|
||||
// Recovery must not fill paper orders on quotes that have become stale.
|
||||
const fills =
|
||||
!expired &&
|
||||
order.request.symbol === data.data.symbol &&
|
||||
this.freshQuote(tx.account, quote)
|
||||
? await this.simulation.fill(tx, order, quote, orders)
|
||||
: [];
|
||||
await tx.putOrder(order);
|
||||
if (fills.length || before !== order.report.status) {
|
||||
const change = { report: order.report, fills };
|
||||
changes.push(change);
|
||||
await this.simulation.journalChange(tx, change);
|
||||
}
|
||||
}
|
||||
await tx.appendJournal({
|
||||
kind: 'market',
|
||||
market: data,
|
||||
recipients: registrations.filter(s => s.enabled).map(s => s.strategyId),
|
||||
account: structuredClone(tx.account),
|
||||
});
|
||||
await tx.putInput({ ...input, status: 'applied' });
|
||||
return changes;
|
||||
});
|
||||
if (!outcome) {
|
||||
return false;
|
||||
}
|
||||
for (const change of outcome) {
|
||||
await this.publish(change);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
async cancelOrder(id: string): Promise<boolean> {
|
||||
return this.serialized(async () => {
|
||||
const change = await this.store().transact(this.accountId, async tx => {
|
||||
const order = await tx.getOrder(id);
|
||||
if (!order || terminal(order.report.status)) {
|
||||
return undefined;
|
||||
}
|
||||
order.report.status = 'cancelled';
|
||||
await tx.putOrder(order);
|
||||
const change = { report: order.report, fills: [] };
|
||||
await this.simulation.journalChange(tx, change);
|
||||
return change;
|
||||
});
|
||||
if (change) {
|
||||
await this.publish(change);
|
||||
}
|
||||
return !!change;
|
||||
});
|
||||
}
|
||||
async getOrderStatus(id: string) {
|
||||
return this.store().transact(
|
||||
this.accountId,
|
||||
async tx => (await tx.getOrder(id))?.report ?? null
|
||||
);
|
||||
}
|
||||
async getAccount() {
|
||||
const decisionAccount = this.recovery.decisionAccount();
|
||||
if (decisionAccount) {
|
||||
return decisionAccount;
|
||||
}
|
||||
return this.store().transact(this.accountId, async tx => ({
|
||||
...tx.account,
|
||||
...accountMetrics(tx.account),
|
||||
}));
|
||||
}
|
||||
async getStrategySnapshot(id: string) {
|
||||
return this.store().transact(this.accountId, async tx => ({
|
||||
positions: tx.account.strategyPositions[id] ?? {},
|
||||
orders: (await tx.openOrders()).filter(o => o.report.strategyId === id),
|
||||
}));
|
||||
}
|
||||
async getPositions() {
|
||||
const account = await this.getAccount();
|
||||
return Object.values(account.positions).map(p => ({
|
||||
...p,
|
||||
unrealizedPnl: amount(
|
||||
decimal(
|
||||
account.quotes[p.symbol]
|
||||
? (defined(account.quotes[p.symbol]).bid + defined(account.quotes[p.symbol]).ask) / 2
|
||||
: p.averagePrice
|
||||
)
|
||||
.minus(p.averagePrice)
|
||||
.times(p.quantity)
|
||||
),
|
||||
}));
|
||||
}
|
||||
captureStrategyOrder(request: OrderRequest, strategyId: string): void {
|
||||
this.recovery.captureStrategyOrder(request, strategyId);
|
||||
}
|
||||
afterStrategyCommit(observation: () => void): void {
|
||||
this.recovery.afterStrategyCommit(observation);
|
||||
}
|
||||
getRecoveryStatus() {
|
||||
return this.recovery.getRecoveryStatus();
|
||||
}
|
||||
registerStrategy(strategy: RecoverableStrategy): Promise<void> {
|
||||
return this.recovery.registerStrategy(strategy);
|
||||
}
|
||||
registeredStrategies() {
|
||||
return this.recovery.registeredStrategies();
|
||||
}
|
||||
pauseStrategy(strategyId: string): Promise<void> {
|
||||
return this.recovery.pauseStrategy(strategyId);
|
||||
}
|
||||
recoverStrategies(strategies: RecoverableStrategy[]): Promise<void> {
|
||||
return this.recovery.recoverStrategies(strategies);
|
||||
}
|
||||
private async publish(change: ExecutionChange) {
|
||||
const fills = change.fills.map(fill => ({
|
||||
...fill,
|
||||
orderId: change.report.orderId,
|
||||
symbol: change.report.symbol,
|
||||
side: change.report.side,
|
||||
strategyId: change.report.strategyId,
|
||||
}));
|
||||
// Native analytics is a run-local projection only. Paper positions always read the SQL ledger.
|
||||
if (this.mode === 'backtest') {
|
||||
for (const fill of fills) {
|
||||
defined(this.engine).advanceTime(fill.timestamp);
|
||||
defined(this.engine).processFillWithMetadata(
|
||||
fill.symbol,
|
||||
fill.price,
|
||||
fill.quantity,
|
||||
fill.side,
|
||||
fill.commission,
|
||||
fill.orderId,
|
||||
fill.strategyId ?? null
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await this.observer?.(change.report, fills);
|
||||
this.emit('orderUpdate', change.report);
|
||||
for (const fill of fills) {
|
||||
this.emit('fill', fill);
|
||||
}
|
||||
} catch (error) {
|
||||
this.container.logger.error('Execution observer failed after commit', { error });
|
||||
}
|
||||
}
|
||||
async routeOrderToExchange(_order: OrderRequest, _exchange: string): Promise<void> {
|
||||
throw new UnsupportedExecutionError('Exchange/broker routing is disabled');
|
||||
}
|
||||
async shutdown() {
|
||||
this.closing = true;
|
||||
await this.tail;
|
||||
this.mode = undefined;
|
||||
this.engine = undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,229 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import {
|
||||
BarSchema,
|
||||
MarketDataSchema,
|
||||
QuoteSchema,
|
||||
TradeSchema,
|
||||
type MarketData,
|
||||
type ModeConfig,
|
||||
} from '../types';
|
||||
import type { StorageService } from './StorageService';
|
||||
|
||||
export class MarketDataService extends EventEmitter {
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
private dataIngestionSocket: Socket | null = null;
|
||||
private subscriptions = new Set<string>();
|
||||
private batchBuffer: MarketData[] = [];
|
||||
private batchTimer: NodeJS.Timeout | null = null;
|
||||
private readonly BATCH_SIZE = 100;
|
||||
private readonly BATCH_INTERVAL_MS = 50;
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'warn' | 'error' | 'debug'>;
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>;
|
||||
drainStrategies: () => Promise<void>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
|
||||
if (config.mode !== 'backtest') {
|
||||
// Connect to data-ingestion service for real-time data
|
||||
await this.connectToDataIngestion();
|
||||
}
|
||||
}
|
||||
|
||||
private async connectToDataIngestion(): Promise<void> {
|
||||
const dataIngestionUrl = process.env.DATA_INGESTION_URL || 'http://localhost:3001';
|
||||
|
||||
this.dataIngestionSocket = io(dataIngestionUrl, {
|
||||
transports: ['websocket'],
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('connect', () => {
|
||||
this.dependencies.logger.info('Connected to data-ingestion service');
|
||||
// Re-subscribe to symbols
|
||||
this.subscriptions.forEach(symbol => {
|
||||
defined(this.dataIngestionSocket).emit('subscribe', { symbol });
|
||||
});
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('disconnect', () => {
|
||||
this.dependencies.logger.warn('Disconnected from data-ingestion service');
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('marketData', data => {
|
||||
this.handleMarketData(data);
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('error', error => {
|
||||
this.dependencies.logger.error('Data ingestion socket error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
async subscribeToSymbol(symbol: string): Promise<void> {
|
||||
this.subscriptions.add(symbol);
|
||||
|
||||
if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) {
|
||||
this.dataIngestionSocket.emit('subscribe', { symbol });
|
||||
}
|
||||
|
||||
this.dependencies.logger.debug(`Subscribed to ${symbol}`);
|
||||
}
|
||||
|
||||
async unsubscribeFromSymbol(symbol: string): Promise<void> {
|
||||
this.subscriptions.delete(symbol);
|
||||
|
||||
if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) {
|
||||
this.dataIngestionSocket.emit('unsubscribe', { symbol });
|
||||
}
|
||||
|
||||
this.dependencies.logger.debug(`Unsubscribed from ${symbol}`);
|
||||
}
|
||||
|
||||
ingest(input: unknown): void {
|
||||
this.handleMarketData(input);
|
||||
}
|
||||
async flush(): Promise<void> {
|
||||
this.processBatch();
|
||||
await this.dependencies.drainStrategies();
|
||||
}
|
||||
private handleMarketData(input: unknown): void {
|
||||
try {
|
||||
if (!input || typeof input !== 'object') {
|
||||
throw new Error('Invalid market data');
|
||||
}
|
||||
const data = input as Record<string, unknown>;
|
||||
// Validate and transform data
|
||||
let marketData: MarketData;
|
||||
|
||||
if ('type' in data && 'data' in data) {
|
||||
marketData = MarketDataSchema.parse(data);
|
||||
} else if (data.bid !== undefined && data.ask !== undefined) {
|
||||
const quote = QuoteSchema.parse({
|
||||
symbol: data.symbol,
|
||||
bid: data.bid,
|
||||
ask: data.ask,
|
||||
bidSize: data.bidSize || data.bid_size || 0,
|
||||
askSize: data.askSize || data.ask_size || 0,
|
||||
timestamp: data.timestamp || Date.now(),
|
||||
});
|
||||
marketData = { type: 'quote', data: quote };
|
||||
} else if (data.price !== undefined && data.size !== undefined) {
|
||||
const trade = TradeSchema.parse({
|
||||
symbol: data.symbol,
|
||||
price: data.price,
|
||||
size: data.size,
|
||||
side: data.side || 'buy',
|
||||
timestamp: data.timestamp || Date.now(),
|
||||
});
|
||||
marketData = { type: 'trade', data: trade };
|
||||
} else if (data.open !== undefined && data.close !== undefined) {
|
||||
const bar = BarSchema.parse({
|
||||
symbol: data.symbol,
|
||||
open: data.open,
|
||||
high: data.high,
|
||||
low: data.low,
|
||||
close: data.close,
|
||||
volume: data.volume,
|
||||
vwap: data.vwap,
|
||||
timestamp: data.timestamp || Date.now(),
|
||||
});
|
||||
marketData = { type: 'bar', data: bar };
|
||||
} else {
|
||||
this.dependencies.logger.warn('Unknown market data format:', data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add to batch buffer
|
||||
if (typeof data.eventId === 'string') {
|
||||
marketData.eventId = data.eventId;
|
||||
}
|
||||
this.batchBuffer.push(marketData);
|
||||
|
||||
// Process batch if size threshold reached
|
||||
if (this.batchBuffer.length >= this.BATCH_SIZE) {
|
||||
this.processBatch();
|
||||
} else if (!this.batchTimer) {
|
||||
// Set timer for time-based batching
|
||||
this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS);
|
||||
}
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error('Error handling market data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private processBatch(): void {
|
||||
if (this.batchBuffer.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear timer
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer);
|
||||
this.batchTimer = null;
|
||||
}
|
||||
|
||||
// Emit batch
|
||||
const batch = [...this.batchBuffer];
|
||||
this.batchBuffer = [];
|
||||
|
||||
this.emit('marketDataBatch', batch);
|
||||
}
|
||||
|
||||
async loadHistoricalData(
|
||||
symbols: string[],
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
interval = '1m'
|
||||
): Promise<MarketData[]> {
|
||||
const { storage } = this.dependencies;
|
||||
const groups = await Promise.all(
|
||||
symbols.map(async symbol => {
|
||||
const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval);
|
||||
return bars.map(
|
||||
(bar): MarketData => ({
|
||||
type: 'bar',
|
||||
data: {
|
||||
symbol,
|
||||
timestamp: bar.timestamp.getTime(),
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
vwap: bar.vwap,
|
||||
},
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
return groups.flat().sort((a, b) => a.data.timestamp - b.data.timestamp);
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
// Clear batch timer
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer);
|
||||
this.batchTimer = null;
|
||||
}
|
||||
|
||||
// Disconnect from data ingestion
|
||||
if (this.dataIngestionSocket) {
|
||||
this.dataIngestionSocket.disconnect();
|
||||
this.dataIngestionSocket = null;
|
||||
}
|
||||
|
||||
await this.flush();
|
||||
this.subscriptions.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
|
||||
export * from '@stock-bot/trading-runtime/historical-storage';
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
export class AnalyticsServiceError extends Error {
|
||||
readonly status: 502 | 503;
|
||||
readonly code: 'analytics_unavailable' | 'analytics_invalid_response';
|
||||
constructor(reason: 'unavailable' | 'invalid-response') {
|
||||
super(
|
||||
reason === 'unavailable'
|
||||
? 'Analytics service is unavailable'
|
||||
: 'Analytics service returned an invalid response'
|
||||
);
|
||||
this.name = 'AnalyticsServiceError';
|
||||
this.status = reason === 'unavailable' ? 503 : 502;
|
||||
this.code = reason === 'unavailable' ? 'analytics_unavailable' : 'analytics_invalid_response';
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { assertResearchConcurrency } from './backtest/ResearchBacktestPool';
|
||||
import { paperConfigurationSchema } from './contracts/paper-runtime';
|
||||
import { paperConfigurationSchema } from '@stock-bot/stock-config/paper-runtime';
|
||||
import {
|
||||
assertSupportedComposition,
|
||||
registerOrchestratorServices,
|
||||
|
|
|
|||
|
|
@ -1,384 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { ModeManager } from '../core/ModeManager';
|
||||
import { identity } from '../execution/model';
|
||||
import type {
|
||||
ExecutionService,
|
||||
StrategyFill,
|
||||
StrategyOrderUpdate,
|
||||
} from '../services/ExecutionService';
|
||||
import {
|
||||
OrderRequestSchema,
|
||||
type MarketData,
|
||||
type OrderRequest,
|
||||
type StrategyConfig,
|
||||
} from '../types';
|
||||
|
||||
const logger = getLogger('BaseStrategy');
|
||||
const finite = z.number().finite();
|
||||
const checkpointSchema = z.object({
|
||||
version: z.literal(1),
|
||||
positions: z.array(z.tuple([z.string(), finite])),
|
||||
pendingOrders: z.array(z.tuple([z.string(), OrderRequestSchema])),
|
||||
seenFills: z.array(z.string()).max(2048),
|
||||
performance: z.object({
|
||||
trades: finite.nonnegative(),
|
||||
wins: finite.nonnegative(),
|
||||
losses: finite.nonnegative(),
|
||||
totalPnl: finite,
|
||||
maxDrawdown: finite,
|
||||
currentDrawdown: finite,
|
||||
peakEquity: finite,
|
||||
}),
|
||||
indicators: z.unknown(),
|
||||
});
|
||||
|
||||
export interface Signal {
|
||||
type: 'buy' | 'sell' | 'close';
|
||||
symbol: string;
|
||||
strength: number; // -1 to 1
|
||||
reason?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export abstract class BaseStrategy extends EventEmitter {
|
||||
protected config: StrategyConfig;
|
||||
protected isActive = false;
|
||||
private eventIdentity?: string;
|
||||
private readonly seenFills = new Set<string>();
|
||||
setMarketEvent(eventId: string) {
|
||||
this.eventIdentity = eventId;
|
||||
}
|
||||
protected positions = new Map<string, number>();
|
||||
protected pendingOrders = new Map<string, OrderRequest>();
|
||||
protected performance = {
|
||||
trades: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
totalPnl: 0,
|
||||
maxDrawdown: 0,
|
||||
currentDrawdown: 0,
|
||||
peakEquity: 0,
|
||||
};
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
protected modeManager: ModeManager,
|
||||
protected executionService: ExecutionService
|
||||
) {
|
||||
super();
|
||||
this.config = structuredClone(config);
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
logger.info(`Initializing strategy: ${this.config.name}`);
|
||||
const snapshot = await this.executionService.getStrategySnapshot(this.config.id);
|
||||
this.positions = new Map(
|
||||
Object.entries(snapshot.positions).filter(([, quantity]) => quantity !== 0)
|
||||
);
|
||||
this.pendingOrders = new Map(
|
||||
snapshot.orders.map(order => [order.report.orderId, order.request])
|
||||
);
|
||||
// Subscribe to symbols
|
||||
for (const symbol of this.config.symbols) {
|
||||
// Note: In real implementation, would subscribe through market data service
|
||||
logger.debug(`Strategy ${this.config.id} subscribed to ${symbol}`);
|
||||
}
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.isActive = true;
|
||||
logger.info(`Started strategy: ${this.config.name}`);
|
||||
await this.onStart();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.isActive = false;
|
||||
await this.executionService.pauseStrategy(this.config.id);
|
||||
|
||||
// Cancel pending orders
|
||||
for (const [orderId, _order] of this.pendingOrders) {
|
||||
await this.executionService.cancelOrder(orderId);
|
||||
}
|
||||
this.pendingOrders.clear();
|
||||
|
||||
logger.info(`Stopped strategy: ${this.config.name}`);
|
||||
await this.onStop();
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
await this.suspend();
|
||||
this.removeAllListeners();
|
||||
logger.info(`Shutdown strategy: ${this.config.name}`);
|
||||
}
|
||||
/** Process shutdown is not an instruction to cancel durable orders or erase indicators. */
|
||||
async suspend(): Promise<void> {
|
||||
this.isActive = false;
|
||||
}
|
||||
getCheckpointVersion(): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
protected captureIndicators(): unknown {
|
||||
return null;
|
||||
}
|
||||
protected restoreIndicators(state: unknown): void {
|
||||
if (state !== null) {
|
||||
throw new Error('Unexpected checkpoint state for a stateless strategy');
|
||||
}
|
||||
}
|
||||
captureCheckpoint(): unknown {
|
||||
return {
|
||||
version: 1,
|
||||
positions: [...this.positions],
|
||||
pendingOrders: [...this.pendingOrders],
|
||||
seenFills: [...this.seenFills].slice(-2048),
|
||||
performance: { ...this.performance },
|
||||
indicators: this.captureIndicators(),
|
||||
};
|
||||
}
|
||||
restoreCheckpoint(input: unknown): void {
|
||||
const state = checkpointSchema.parse(input);
|
||||
this.restoreIndicators(state.indicators);
|
||||
this.positions = new Map(state.positions);
|
||||
this.pendingOrders = new Map(state.pendingOrders);
|
||||
this.seenFills.clear();
|
||||
for (const id of state.seenFills) {
|
||||
this.seenFills.add(id);
|
||||
}
|
||||
this.performance = state.performance;
|
||||
}
|
||||
|
||||
// Market data handling
|
||||
async onMarketData(data: MarketData): Promise<void> {
|
||||
if (!this.isActive) {
|
||||
logger.info(
|
||||
`[BaseStrategy] Strategy ${this.config.id} received market data but is not active`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.eventIdentity = identity(data);
|
||||
// Update any indicators or state
|
||||
this.updateIndicators(data);
|
||||
|
||||
// Generate signals
|
||||
const signal = await this.generateSignal(data);
|
||||
|
||||
if (signal) {
|
||||
this.executionService.afterStrategyCommit(() => {
|
||||
this.emit('signal', signal);
|
||||
});
|
||||
|
||||
// Convert signal to order if strong enough
|
||||
const order = await this.signalToOrder(signal);
|
||||
if (order) {
|
||||
const clientOrderId = createHash('sha256')
|
||||
.update(JSON.stringify([this.config.id, this.eventIdentity, order]))
|
||||
.digest('hex');
|
||||
this.executionService.captureStrategyOrder({ ...order, clientOrderId }, this.config.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onMarketDataBatch(batch: MarketData[]): Promise<void> {
|
||||
// Default implementation processes individually
|
||||
// Strategies can override for more efficient batch processing
|
||||
for (const data of batch) {
|
||||
await this.onMarketData(data);
|
||||
}
|
||||
}
|
||||
|
||||
getConfig(): Readonly<StrategyConfig> {
|
||||
return structuredClone(this.config);
|
||||
}
|
||||
|
||||
hasOrder(orderId: string): boolean {
|
||||
return this.pendingOrders.has(orderId);
|
||||
}
|
||||
|
||||
// Order and fill handling
|
||||
async onOrderUpdate(update: StrategyOrderUpdate): Promise<void> {
|
||||
logger.debug(`Strategy ${this.config.id} order update:`, update);
|
||||
|
||||
if (['filled', 'rejected', 'cancelled'].includes(update.status)) {
|
||||
this.pendingOrders.delete(update.orderId);
|
||||
} else {
|
||||
this.pendingOrders.set(update.orderId, {
|
||||
symbol: update.symbol,
|
||||
side: update.side,
|
||||
quantity: update.quantity,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async onOrderError(order: OrderRequest, error: unknown): Promise<void> {
|
||||
logger.error(`Strategy ${this.config.id} order error:`, error);
|
||||
// Strategies can override to handle errors
|
||||
}
|
||||
|
||||
async onFill(fill: StrategyFill): Promise<void> {
|
||||
if (this.seenFills.has(fill.id)) {
|
||||
return;
|
||||
}
|
||||
this.seenFills.add(fill.id);
|
||||
if (this.seenFills.size > 2048) {
|
||||
this.seenFills.delete(defined(this.seenFills.values().next().value));
|
||||
}
|
||||
const quantity =
|
||||
(this.positions.get(fill.symbol) ?? 0) +
|
||||
(fill.side === 'buy' ? fill.quantity : -fill.quantity);
|
||||
if (Math.abs(quantity) < 1e-8) {
|
||||
this.positions.delete(fill.symbol);
|
||||
} else {
|
||||
this.positions.set(fill.symbol, quantity);
|
||||
}
|
||||
// Update performance metrics
|
||||
this.performance.trades++;
|
||||
|
||||
if ((fill.pnl ?? 0) > 0) {
|
||||
this.performance.wins++;
|
||||
} else if ((fill.pnl ?? 0) < 0) {
|
||||
this.performance.losses++;
|
||||
}
|
||||
|
||||
this.performance.totalPnl += fill.pnl ?? 0;
|
||||
|
||||
// Update drawdown
|
||||
const currentEquity = this.getEquity();
|
||||
if (currentEquity > this.performance.peakEquity) {
|
||||
this.performance.peakEquity = currentEquity;
|
||||
this.performance.currentDrawdown = 0;
|
||||
} else {
|
||||
this.performance.currentDrawdown =
|
||||
this.performance.peakEquity > 0
|
||||
? (this.performance.peakEquity - currentEquity) / this.performance.peakEquity
|
||||
: 0;
|
||||
this.performance.maxDrawdown = Math.max(
|
||||
this.performance.maxDrawdown,
|
||||
this.performance.currentDrawdown
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Configuration
|
||||
async updateConfig(updates: Partial<StrategyConfig>): Promise<void> {
|
||||
if (this.isActive) {
|
||||
throw new Error(
|
||||
'Active strategy configuration is immutable; use an explicit new strategy ID'
|
||||
);
|
||||
}
|
||||
this.config = this.validateConfig(structuredClone({ ...this.config, ...updates }));
|
||||
logger.info(`Updated config for strategy ${this.config.id}`);
|
||||
|
||||
// Strategies can override to handle specific config changes
|
||||
this.onConfigUpdate(updates);
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
isInterestedInSymbol(symbol: string): boolean {
|
||||
return this.config.symbols.includes(symbol);
|
||||
}
|
||||
|
||||
hasPosition(symbol: string): boolean {
|
||||
return this.positions.has(symbol) && Math.abs(defined(this.positions.get(symbol))) > 0.0001;
|
||||
}
|
||||
|
||||
getPosition(symbol: string): number {
|
||||
return this.positions.get(symbol) || 0;
|
||||
}
|
||||
|
||||
getPerformance() {
|
||||
const winRate =
|
||||
this.performance.trades > 0 ? (this.performance.wins / this.performance.trades) * 100 : 0;
|
||||
|
||||
return {
|
||||
...this.performance,
|
||||
winRate,
|
||||
averagePnl:
|
||||
this.performance.trades > 0 ? this.performance.totalPnl / this.performance.trades : 0,
|
||||
};
|
||||
}
|
||||
|
||||
protected getEquity(): number {
|
||||
// Get initial capital from config parameters or default
|
||||
const initialCapital = Number(this.config.parameters?.initialCapital ?? 100000);
|
||||
return initialCapital + this.performance.totalPnl;
|
||||
}
|
||||
|
||||
protected async signalToOrder(signal: Signal): Promise<OrderRequest | null> {
|
||||
// Only act on strong signals
|
||||
if (Math.abs(signal.strength) < 0.7) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if we already have a position
|
||||
const currentPosition = this.getPosition(signal.symbol);
|
||||
|
||||
// Use quantity from signal metadata if provided
|
||||
const quantity =
|
||||
typeof signal.metadata?.quantity === 'number'
|
||||
? signal.metadata.quantity
|
||||
: this.calculatePositionSize(signal);
|
||||
|
||||
logger.info(
|
||||
`[BaseStrategy] Converting signal to order: ${signal.type} ${quantity} ${signal.symbol}, current position: ${currentPosition}`
|
||||
);
|
||||
|
||||
// Simple logic - can be overridden by specific strategies
|
||||
if (signal.type === 'buy') {
|
||||
// Allow buying to open long or close short
|
||||
return {
|
||||
symbol: signal.symbol,
|
||||
side: 'buy',
|
||||
quantity: quantity,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
} else if (signal.type === 'sell') {
|
||||
// Allow selling to close long or open short
|
||||
return {
|
||||
symbol: signal.symbol,
|
||||
side: 'sell',
|
||||
quantity: quantity,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
} else if (signal.type === 'close' && currentPosition !== 0) {
|
||||
return {
|
||||
symbol: signal.symbol,
|
||||
side: currentPosition > 0 ? 'sell' : 'buy',
|
||||
quantity: Math.abs(currentPosition),
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected calculatePositionSize(signal: Signal): number {
|
||||
// Simple fixed size - strategies should override with proper position sizing
|
||||
const baseSize = 100; // 100 shares
|
||||
const allocation = this.config.allocation || 1.0;
|
||||
|
||||
return Math.floor(baseSize * allocation * Math.abs(signal.strength));
|
||||
}
|
||||
|
||||
// Abstract methods that strategies must implement
|
||||
protected abstract updateIndicators(data: MarketData): void;
|
||||
protected abstract generateSignal(data: MarketData): Promise<Signal | null>;
|
||||
|
||||
// Optional hooks for strategies to override
|
||||
protected onStart(): void | Promise<void> {}
|
||||
protected onStop(): void | Promise<void> {}
|
||||
protected onConfigUpdate(_updates: Partial<StrategyConfig>): void {}
|
||||
/** Validate before assignment, so a rejected inactive edit cannot poison the current definition. */
|
||||
protected validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,238 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import { type MarketData, type StrategyConfig } from '../types';
|
||||
import type { BaseStrategy, Signal } from './BaseStrategy';
|
||||
|
||||
export class StrategyManager extends EventEmitter {
|
||||
private strategies = new Map<string, BaseStrategy>();
|
||||
private activeStrategies = new Set<string>();
|
||||
private delivery: Promise<unknown> = Promise.resolve();
|
||||
private listening = false;
|
||||
private recoveryTimer?: ReturnType<typeof setInterval>;
|
||||
private readonly onBatch = (batch: MarketData[]) => {
|
||||
void this.deliverBatch(batch).catch(error =>
|
||||
this.dependencies.logger.error('Market delivery failed', { error })
|
||||
);
|
||||
};
|
||||
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'error'>;
|
||||
marketData: Pick<EventEmitter, 'on' | 'off'>;
|
||||
execution: Pick<
|
||||
ExecutionService,
|
||||
| 'requiresDurableCheckpoint'
|
||||
| 'enqueueMarketData'
|
||||
| 'recoverStrategies'
|
||||
| 'registeredStrategies'
|
||||
| 'registerStrategy'
|
||||
| 'pauseStrategy'
|
||||
>;
|
||||
createStrategy: (config: StrategyConfig) => BaseStrategy | Promise<BaseStrategy>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
setupEventListeners(): void {
|
||||
if (this.listening) {
|
||||
return;
|
||||
}
|
||||
this.listening = true;
|
||||
const { marketData: marketDataService, execution: executionService } = this.dependencies;
|
||||
marketDataService.on('marketDataBatch', this.onBatch);
|
||||
// Financial notifications are journal inputs, not volatile observer callbacks.
|
||||
this.recoveryTimer = setInterval(() => {
|
||||
if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) {
|
||||
void this.recover().catch(error =>
|
||||
this.dependencies.logger.error('Strategy recovery remains pending', { error })
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
this.recoveryTimer.unref();
|
||||
}
|
||||
|
||||
private deliverBatch(batch: MarketData[]): Promise<void> {
|
||||
const work = this.delivery
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
const { execution } = this.dependencies;
|
||||
const failures: unknown[] = [];
|
||||
for (const data of batch) {
|
||||
try {
|
||||
await execution.enqueueMarketData(data);
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
await execution.recoverStrategies(
|
||||
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
|
||||
);
|
||||
if (failures.length) {
|
||||
throw new AggregateError(failures, 'Some market inputs were rejected');
|
||||
}
|
||||
});
|
||||
this.delivery = work;
|
||||
return work;
|
||||
}
|
||||
|
||||
recover(): Promise<void> {
|
||||
const work = this.delivery
|
||||
.catch(() => {})
|
||||
.then(() =>
|
||||
this.dependencies.execution.recoverStrategies(
|
||||
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
|
||||
)
|
||||
);
|
||||
this.delivery = work;
|
||||
return work;
|
||||
}
|
||||
|
||||
async drain(): Promise<void> {
|
||||
await this.delivery;
|
||||
}
|
||||
|
||||
async initializeStrategies(configs: StrategyConfig[]): Promise<void> {
|
||||
if (new Set(configs.map(config => config.id)).size !== configs.length) {
|
||||
throw new Error('Duplicate strategy IDs');
|
||||
}
|
||||
// Clear existing strategies
|
||||
for (const [_id, strategy] of this.strategies) {
|
||||
await strategy.shutdown();
|
||||
}
|
||||
this.strategies.clear();
|
||||
this.activeStrategies.clear();
|
||||
this.setupEventListeners();
|
||||
|
||||
// Initialize new strategies
|
||||
for (const config of configs) {
|
||||
try {
|
||||
const strategy = await this.createStrategy(config);
|
||||
this.strategies.set(config.id, strategy);
|
||||
|
||||
if (config.enabled) {
|
||||
await this.enableStrategy(config.id);
|
||||
}
|
||||
|
||||
this.dependencies.logger.info(`Initialized strategy: ${config.name} (${config.id})`);
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error(`Failed to initialize strategy ${config.name}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
await this.recover();
|
||||
}
|
||||
async restoreStrategies(): Promise<void> {
|
||||
this.setupEventListeners();
|
||||
const configs = await this.dependencies.execution.registeredStrategies();
|
||||
if (configs.length) {
|
||||
await this.initializeStrategies(configs);
|
||||
}
|
||||
}
|
||||
async attachStrategy(strategy: BaseStrategy): Promise<void> {
|
||||
this.setupEventListeners();
|
||||
const config = strategy.getConfig();
|
||||
if (this.strategies.has(config.id)) {
|
||||
throw new Error('Strategy ID already attached');
|
||||
}
|
||||
this.strategies.set(config.id, strategy);
|
||||
await this.enableStrategy(config.id);
|
||||
await this.recover();
|
||||
}
|
||||
|
||||
private async createStrategy(config: StrategyConfig): Promise<BaseStrategy> {
|
||||
const strategy = await this.dependencies.createStrategy(config);
|
||||
|
||||
// Set up strategy event handlers
|
||||
strategy.on('signal', signal => {
|
||||
this.handleStrategySignal(config.id, signal);
|
||||
});
|
||||
|
||||
strategy.on('error', (error: Error) => {
|
||||
this.dependencies.logger.error(`Strategy ${config.id} error:`, error);
|
||||
});
|
||||
|
||||
return strategy;
|
||||
}
|
||||
|
||||
async enableStrategy(strategyId: string): Promise<void> {
|
||||
const strategy = this.strategies.get(strategyId);
|
||||
if (!strategy) {
|
||||
throw new Error(`Strategy ${strategyId} not found`);
|
||||
}
|
||||
|
||||
const { execution } = this.dependencies;
|
||||
if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) {
|
||||
throw new Error('Paper strategies require a versioned checkpoint contract');
|
||||
}
|
||||
await strategy.initialize();
|
||||
await strategy.start(); // Start the strategy to make it active
|
||||
try {
|
||||
await execution.registerStrategy(strategy);
|
||||
} catch (error) {
|
||||
await strategy.suspend();
|
||||
throw error;
|
||||
}
|
||||
this.activeStrategies.add(strategyId);
|
||||
this.dependencies.logger.info(`Enabled strategy: ${strategyId}`);
|
||||
}
|
||||
|
||||
async disableStrategy(strategyId: string): Promise<void> {
|
||||
const strategy = this.strategies.get(strategyId);
|
||||
if (!strategy) {
|
||||
throw new Error(`Strategy ${strategyId} not found`);
|
||||
}
|
||||
|
||||
// Disable pauses new decisions; pending orders/intents remain explicit ledger work.
|
||||
await this.dependencies.execution.pauseStrategy(strategyId);
|
||||
await strategy.suspend();
|
||||
this.activeStrategies.delete(strategyId);
|
||||
this.dependencies.logger.info(`Disabled strategy: ${strategyId}`);
|
||||
}
|
||||
|
||||
private async handleStrategySignal(strategyId: string, signal: Signal): Promise<void> {
|
||||
this.dependencies.logger.info(`Strategy ${strategyId} generated signal:`, signal);
|
||||
// Signals are informational - strategies will convert strong signals to orders
|
||||
}
|
||||
|
||||
async onMarketData(data: MarketData): Promise<void> {
|
||||
await this.deliverBatch([data]);
|
||||
}
|
||||
|
||||
getActiveStrategies(): string[] {
|
||||
return Array.from(this.activeStrategies);
|
||||
}
|
||||
|
||||
getStrategy(strategyId: string): BaseStrategy | undefined {
|
||||
return this.strategies.get(strategyId);
|
||||
}
|
||||
|
||||
getAllStrategies(): BaseStrategy[] {
|
||||
return Array.from(this.strategies.values());
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.dependencies.logger.info('Shutting down strategy manager...');
|
||||
|
||||
this.dependencies.marketData.off('marketDataBatch', this.onBatch);
|
||||
this.listening = false;
|
||||
if (this.recoveryTimer) {
|
||||
clearInterval(this.recoveryTimer);
|
||||
this.recoveryTimer = undefined;
|
||||
}
|
||||
try {
|
||||
await this.drain();
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error('Leaving durable strategy backlog for restart', { error });
|
||||
}
|
||||
// Disable all strategies
|
||||
for (const strategyId of this.activeStrategies) {
|
||||
await this.strategies.get(strategyId)?.suspend();
|
||||
}
|
||||
|
||||
// Clear all strategies
|
||||
this.strategies.clear();
|
||||
this.activeStrategies.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
import { normalizeStrategyName } from '../contracts/strategy-names';
|
||||
import type { ModeManager } from '../core/ModeManager';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../types';
|
||||
import type { BaseStrategy } from './BaseStrategy';
|
||||
|
||||
export interface StrategyDependencies {
|
||||
modeManager: ModeManager;
|
||||
execution: ExecutionService;
|
||||
}
|
||||
export type StrategyFactory = (
|
||||
config: StrategyConfig,
|
||||
dependencies: StrategyDependencies
|
||||
) => BaseStrategy | Promise<BaseStrategy>;
|
||||
|
||||
/** Registration belongs to composition; strategy lifecycle belongs to the manager. */
|
||||
export class StrategyRegistry {
|
||||
private readonly factories = new Map<string, StrategyFactory>();
|
||||
|
||||
register(names: readonly string[], factory: StrategyFactory): this {
|
||||
const keys = names.map(normalizeStrategyName);
|
||||
if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) {
|
||||
throw new Error('Strategy aliases must be nonempty and distinct');
|
||||
}
|
||||
for (const key of keys) {
|
||||
if (this.factories.has(key)) {
|
||||
throw new Error(`Strategy alias already registered: ${key}`);
|
||||
}
|
||||
}
|
||||
for (const key of keys) {
|
||||
this.factories.set(key, factory);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise<BaseStrategy> {
|
||||
const factory = this.factories.get(normalizeStrategyName(config.name));
|
||||
if (!factory) {
|
||||
throw new Error(`Unknown strategy: ${config.name}`);
|
||||
}
|
||||
return factory(config, dependencies);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
import { strategyAliases } from '../contracts/strategy-names';
|
||||
import { StrategyRegistry } from './StrategyRegistry';
|
||||
|
||||
/** Lazy factories avoid loading every strategy (and ML dependency) at startup. */
|
||||
export function createBuiltinStrategyRegistry(): StrategyRegistry {
|
||||
return new StrategyRegistry()
|
||||
.register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => {
|
||||
const { MeanReversionStrategy } = await import('./builtin/MeanReversionStrategy');
|
||||
return new MeanReversionStrategy(config, modeManager, execution);
|
||||
})
|
||||
.register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => {
|
||||
const { SmaCrossoverStrategy } = await import('./builtin/SmaCrossoverStrategy');
|
||||
return new SmaCrossoverStrategy(config, modeManager, execution);
|
||||
})
|
||||
.register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => {
|
||||
const { MLEnhancedStrategy } = await import('./experimental/MLEnhancedStrategy');
|
||||
return new MLEnhancedStrategy(config, modeManager, execution);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,234 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
trailingSimpleRsi,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { MeanReversionParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import type { ExecutionService } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { priceHistoryState } from '../checkpoint-schemas';
|
||||
import { meanReversionConfig } from '../strategy-config';
|
||||
|
||||
const logger = getLogger('MeanReversionStrategy');
|
||||
|
||||
interface MeanReversionIndicators {
|
||||
mean: number;
|
||||
trendMean: number;
|
||||
stdDev: number;
|
||||
zScore: number;
|
||||
rsi: number;
|
||||
}
|
||||
|
||||
/** Versioned implementation used by the built-in mean-reversion aliases. */
|
||||
export class MeanReversionStrategy extends BaseStrategy {
|
||||
private priceHistory = new Map<string, number[]>();
|
||||
private indicators = new Map<string, MeanReversionIndicators>();
|
||||
override getCheckpointVersion() {
|
||||
return 'mean-reversion/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return { priceHistory: [...this.priceHistory], indicators: [...this.indicators] };
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const finite = z.number().finite();
|
||||
const state = z
|
||||
.object({
|
||||
priceHistory: priceHistoryState(this.historyCapacity),
|
||||
indicators: z.array(
|
||||
z.tuple([
|
||||
z.string(),
|
||||
z.object({
|
||||
mean: finite,
|
||||
trendMean: finite,
|
||||
stdDev: finite,
|
||||
zScore: finite,
|
||||
rsi: finite,
|
||||
}),
|
||||
])
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.parse(input);
|
||||
this.priceHistory = new Map(state.priceHistory);
|
||||
this.indicators = new Map(state.indicators);
|
||||
}
|
||||
|
||||
private settings: MeanReversionParameters;
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
const validated = meanReversionConfig(config);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
}
|
||||
|
||||
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
const validated = meanReversionConfig(config);
|
||||
this.settings = validated.parameters;
|
||||
return validated;
|
||||
}
|
||||
private get historyCapacity(): number {
|
||||
return Math.max(
|
||||
this.settings.lookbackPeriod * 3,
|
||||
this.settings.trendPeriod,
|
||||
this.settings.rsiPeriod + 1
|
||||
);
|
||||
}
|
||||
protected override calculatePositionSize(signal: Signal): number {
|
||||
return this.settings.quantity ?? super.calculatePositionSize(signal);
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const price = data.data.close;
|
||||
|
||||
// Update price history
|
||||
if (!this.priceHistory.has(symbol)) {
|
||||
this.priceHistory.set(symbol, []);
|
||||
}
|
||||
|
||||
const history = defined(this.priceHistory.get(symbol));
|
||||
history.push(price);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.historyCapacity) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Calculate indicators if we have enough data
|
||||
if (history.length >= Math.max(this.settings.lookbackPeriod, this.settings.rsiPeriod + 1)) {
|
||||
const indicators = this.calculateIndicators(history);
|
||||
this.indicators.set(symbol, indicators);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateIndicators(prices: number[]): MeanReversionIndicators {
|
||||
const len = prices.length;
|
||||
|
||||
const mean = defined(trailingMean(prices, this.settings.lookbackPeriod));
|
||||
const trendMean = trailingMean(prices, this.settings.trendPeriod) ?? mean;
|
||||
const stdDev = defined(trailingPopulationDeviation(prices, this.settings.lookbackPeriod));
|
||||
|
||||
// Calculate Z-score
|
||||
const currentPrice = at(prices, len - 1);
|
||||
const zScore = stdDev > 0 ? (currentPrice - mean) / stdDev : 0;
|
||||
|
||||
// Calculate RSI
|
||||
const rsi = this.calculateRSI(prices, this.settings.rsiPeriod);
|
||||
|
||||
return { mean, trendMean, stdDev, zScore, rsi };
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const indicators = this.indicators.get(symbol);
|
||||
|
||||
if (!indicators) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check volume filter
|
||||
if (data.data.volume * data.data.close < this.settings.minNotionalVolume) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const position = this.getPosition(symbol);
|
||||
const { zScore, rsi, mean, trendMean } = indicators;
|
||||
|
||||
// Entry signals
|
||||
if (position === 0) {
|
||||
// Long entry: Oversold conditions
|
||||
if (
|
||||
zScore < -this.settings.entryThreshold &&
|
||||
rsi < this.settings.rsiOversold &&
|
||||
mean > trendMean
|
||||
) {
|
||||
return {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: Math.min(Math.abs(zScore) / 3, 1),
|
||||
reason: `Mean reversion long: Z-score ${zScore.toFixed(2)}, RSI ${rsi.toFixed(0)}`,
|
||||
metadata: { indicators },
|
||||
};
|
||||
}
|
||||
|
||||
// Short entry: Overbought conditions
|
||||
if (
|
||||
zScore > this.settings.entryThreshold &&
|
||||
rsi > this.settings.rsiOverbought &&
|
||||
mean < trendMean
|
||||
) {
|
||||
return {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: Math.min(Math.abs(zScore) / 3, 1),
|
||||
reason: `Mean reversion short: Z-score ${zScore.toFixed(2)}, RSI ${rsi.toFixed(0)}`,
|
||||
metadata: { indicators },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Exit signals
|
||||
if (position > 0) {
|
||||
// Exit long: Price reverted to mean or stop loss
|
||||
if (zScore > -this.settings.exitZScore || zScore > this.settings.entryThreshold) {
|
||||
return {
|
||||
type: 'close',
|
||||
symbol,
|
||||
strength: 1,
|
||||
reason: `Exit long: Z-score ${zScore.toFixed(2)}`,
|
||||
metadata: { indicators },
|
||||
};
|
||||
}
|
||||
} else if (position < 0) {
|
||||
// Exit short: Price reverted to mean or stop loss
|
||||
if (zScore < this.settings.exitZScore || zScore < -this.settings.entryThreshold) {
|
||||
return {
|
||||
type: 'close',
|
||||
symbol,
|
||||
strength: 1,
|
||||
reason: `Exit short: Z-score ${zScore.toFixed(2)}`,
|
||||
metadata: { indicators },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private calculateRSI(prices: number[], period: number = 14): number {
|
||||
// v2 uses rolling simple averages and flat=100, NOT the new Wilder contract.
|
||||
return trailingSimpleRsi(prices, period, 100) ?? 50;
|
||||
}
|
||||
|
||||
protected override onStart(): void {
|
||||
logger.info(`Mean Reversion Strategy started with symbols: ${this.config.symbols.join(', ')}`);
|
||||
}
|
||||
|
||||
protected override onStop(): void {
|
||||
logger.info('Mean Reversion Strategy stopped');
|
||||
// Clear indicators
|
||||
this.priceHistory.clear();
|
||||
this.indicators.clear();
|
||||
}
|
||||
|
||||
protected override onConfigUpdate(updates: Partial<StrategyConfig>): void {
|
||||
logger.info('Mean Reversion Strategy config updated:', updates);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,310 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { SmaParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import { movingAverageCrossover } from '@stock-bot/calculations/indicators';
|
||||
import type { ExecutionService, StrategyFill } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
|
||||
import { smaConfig } from '../strategy-config';
|
||||
|
||||
const logger = getLogger('SimpleMovingAverageCrossover');
|
||||
|
||||
export class SmaCrossoverStrategy extends BaseStrategy {
|
||||
private priceHistory = new Map<string, number[]>();
|
||||
private lastSignalBar = new Map<string, number>();
|
||||
private barCount = new Map<string, number>();
|
||||
private totalSignals = 0;
|
||||
private lastCrossoverType = new Map<string, 'golden' | 'death' | null>();
|
||||
override getCheckpointVersion() {
|
||||
return 'sma-crossover-fixed/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return {
|
||||
priceHistory: [...this.priceHistory],
|
||||
lastSignalBar: [...this.lastSignalBar],
|
||||
barCount: [...this.barCount],
|
||||
totalSignals: this.totalSignals,
|
||||
lastCrossoverType: [...this.lastCrossoverType],
|
||||
};
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input);
|
||||
this.priceHistory = new Map(state.priceHistory);
|
||||
this.lastSignalBar = new Map(state.lastSignalBar);
|
||||
this.barCount = new Map(state.barCount);
|
||||
this.totalSignals = state.totalSignals;
|
||||
this.lastCrossoverType = new Map(state.lastCrossoverType);
|
||||
}
|
||||
|
||||
private settings: SmaParameters;
|
||||
private readonly DEBUG_INTERVAL = 10;
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
const validated = smaConfig(config);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
logger.info(
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
|
||||
);
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const price = data.data.close;
|
||||
|
||||
// Initialize or get price history
|
||||
if (!this.priceHistory.has(symbol)) {
|
||||
this.priceHistory.set(symbol, []);
|
||||
this.barCount.set(symbol, 0);
|
||||
logger.info(`📊 Starting to track ${symbol} @ ${price.toFixed(2)}`);
|
||||
}
|
||||
|
||||
const history = defined(this.priceHistory.get(symbol));
|
||||
history.push(price);
|
||||
|
||||
// Increment bar count
|
||||
const currentBar = (this.barCount.get(symbol) || 0) + 1;
|
||||
this.barCount.set(symbol, currentBar);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.settings.slowPeriod * 2) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Log when we have enough data to start trading
|
||||
if (history.length === this.settings.slowPeriod + 1) {
|
||||
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const history = this.priceHistory.get(symbol);
|
||||
|
||||
if (!history || history.length < this.settings.slowPeriod) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentPrice = data.data.close;
|
||||
const timestamp = data.data.timestamp;
|
||||
const currentBar = this.barCount.get(symbol) || 0;
|
||||
|
||||
const crossover = movingAverageCrossover(
|
||||
history,
|
||||
this.settings.fastPeriod,
|
||||
this.settings.slowPeriod
|
||||
);
|
||||
if (!crossover) {
|
||||
return null;
|
||||
}
|
||||
const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover;
|
||||
|
||||
// Get current position
|
||||
const currentPosition = this.getPosition(symbol);
|
||||
|
||||
// Track last signal bar
|
||||
const lastSignalBar = this.lastSignalBar.get(symbol) || 0;
|
||||
const barsSinceLastSignal = currentBar - lastSignalBar;
|
||||
|
||||
// Calculate MA difference for debugging
|
||||
const maDiff = fastMA - slowMA;
|
||||
const maDiffPct = (maDiff / slowMA) * 100;
|
||||
|
||||
// Debug logging every N bars
|
||||
if (currentBar % this.DEBUG_INTERVAL === 0 || goldenCross || deathCross) {
|
||||
logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`);
|
||||
logger.info(` Price: $${currentPrice.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`);
|
||||
logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`);
|
||||
logger.info(` Position: ${currentPosition} shares`);
|
||||
logger.info(` Bars since last signal: ${barsSinceLastSignal}`);
|
||||
|
||||
if (goldenCross) {
|
||||
logger.info(` 🟢 GOLDEN CROSS DETECTED!`);
|
||||
}
|
||||
if (deathCross) {
|
||||
logger.info(` 🔴 DEATH CROSS DETECTED!`);
|
||||
}
|
||||
}
|
||||
|
||||
// Store crossover type for position management
|
||||
if (goldenCross) {
|
||||
this.lastCrossoverType.set(symbol, 'golden');
|
||||
} else if (deathCross) {
|
||||
this.lastCrossoverType.set(symbol, 'death');
|
||||
}
|
||||
|
||||
// Check if we should enter a position based on the current trend
|
||||
const lastCrossover = this.lastCrossoverType.get(symbol);
|
||||
|
||||
if (currentPosition === 0 && barsSinceLastSignal >= this.settings.minHoldingBars) {
|
||||
// No position - check if we should enter based on last crossover
|
||||
if (lastCrossover === 'golden' && fastMA > slowMA) {
|
||||
// Trend is still bullish after golden cross - open long
|
||||
logger.info(`🟢 Opening LONG position - Bullish trend after golden cross`);
|
||||
logger.info(` Current position: 0 shares`);
|
||||
|
||||
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
||||
logger.info(` Opening long position: ${positionSize} shares`);
|
||||
|
||||
const signal: Signal = {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Bullish trend - Opening long position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'trend_long',
|
||||
price: currentPrice,
|
||||
quantity: positionSize,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastSignalBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
} else if (lastCrossover === 'death' && fastMA < slowMA) {
|
||||
// Trend is still bearish after death cross - open short
|
||||
logger.info(`🔴 Opening SHORT position - Bearish trend after death cross`);
|
||||
logger.info(` Current position: 0 shares`);
|
||||
|
||||
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
||||
logger.info(` Opening short position: ${positionSize} shares`);
|
||||
|
||||
const signal: Signal = {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Bearish trend - Opening short position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'trend_short',
|
||||
price: currentPrice,
|
||||
quantity: positionSize,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastSignalBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle crossovers for position changes
|
||||
if (goldenCross) {
|
||||
logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`);
|
||||
logger.info(` Current position: ${currentPosition} shares`);
|
||||
|
||||
if (currentPosition < 0) {
|
||||
// Close short position
|
||||
logger.info(` Closing short position of ${Math.abs(currentPosition)} shares`);
|
||||
const signal: Signal = {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Golden cross - Closing short position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'golden',
|
||||
price: currentPrice,
|
||||
quantity: Math.abs(currentPosition),
|
||||
},
|
||||
};
|
||||
|
||||
this.lastSignalBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
}
|
||||
} else if (deathCross) {
|
||||
logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`);
|
||||
logger.info(` Current position: ${currentPosition} shares`);
|
||||
|
||||
if (currentPosition > 0) {
|
||||
// Close long position
|
||||
logger.info(` Closing long position of ${currentPosition} shares`);
|
||||
const signal: Signal = {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Death cross - Closing long position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'death',
|
||||
price: currentPrice,
|
||||
quantity: currentPosition,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastSignalBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
const validated = smaConfig(config);
|
||||
this.settings = validated.parameters;
|
||||
return validated;
|
||||
}
|
||||
|
||||
private async calculateCrossoverPositionSize(price: number): Promise<number> {
|
||||
if (this.settings.quantity !== undefined) {
|
||||
return this.settings.quantity;
|
||||
}
|
||||
const accountBalance = (await this.executionService.getAccount()).equity;
|
||||
const positionValue = accountBalance * this.settings.positionFraction;
|
||||
const shares = Math.floor(positionValue / price);
|
||||
|
||||
logger.debug(
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
|
||||
);
|
||||
|
||||
return Math.max(1, shares); // At least 1 share
|
||||
}
|
||||
|
||||
protected onOrderFilled(fill: StrategyFill): void {
|
||||
const { symbol, side, quantity, price } = fill;
|
||||
|
||||
logger.info(`✅ ${side.toUpperCase()} filled: ${symbol} - ${quantity} shares @ ${price}`);
|
||||
|
||||
// Update our internal position tracking to match
|
||||
// This is redundant with BaseStrategy but helps with debugging
|
||||
const currentPosition = this.getPosition(symbol);
|
||||
logger.info(` Position after fill: ${currentPosition} shares`);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,9 +2,9 @@ import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
|||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { ReplayConfig } from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import type { ReplayConfig } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { createMeanReversionStrategy } from './canonical-mean-reversion';
|
||||
import { createSmaStrategy } from './canonical-sma';
|
||||
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import {
|
|||
meanReversionStrategySelectionSchema,
|
||||
type MeanReversionSignalParameters,
|
||||
type MeanReversionStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import { wholeShareTarget } from './canonical-sizing';
|
||||
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types';
|
|||
import {
|
||||
smaStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import { wholeShareTarget } from './canonical-sizing';
|
||||
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const priceHistoryState = (capacity: number) =>
|
||||
z.array(z.tuple([z.string(), z.array(z.number().finite().positive()).max(capacity)]));
|
||||
export const barCounterState = z.array(z.tuple([z.string(), z.number().int().nonnegative()]));
|
||||
export const crossoverCheckpointSchema = (capacity: number) =>
|
||||
z
|
||||
.object({
|
||||
priceHistory: priceHistoryState(capacity),
|
||||
barCount: barCounterState,
|
||||
lastSignalBar: barCounterState,
|
||||
totalSignals: z.number().int().nonnegative(),
|
||||
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
|
||||
})
|
||||
.strict();
|
||||
|
|
@ -1,472 +0,0 @@
|
|||
import type * as tf from '@tensorflow/tfjs-node';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { TechnicalAnalysis } from '../../indicators/TechnicalAnalysis';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
|
||||
const logger = getLogger('MLEnhancedStrategy');
|
||||
|
||||
interface MLModelConfig {
|
||||
modelPath?: string;
|
||||
features: string[];
|
||||
lookbackPeriod: number;
|
||||
updateFrequency: number; // How often to retrain in minutes
|
||||
minTrainingSize: number;
|
||||
}
|
||||
|
||||
/** Optional run-local experiment; deliberately lacks a durable paper checkpoint contract. */
|
||||
export class MLEnhancedStrategy extends BaseStrategy {
|
||||
private tensorflow: typeof tf | undefined;
|
||||
private get tf(): typeof tf {
|
||||
return defined(this.tensorflow, 'ML strategy has not been started');
|
||||
}
|
||||
private model: tf.LayersModel | null = null;
|
||||
private featureBuffer: Map<string, number[][]> = new Map();
|
||||
private predictions: Map<string, number> = new Map();
|
||||
private lastUpdate: number = 0;
|
||||
private trainingData: { features: number[][]; labels: number[] } = { features: [], labels: [] };
|
||||
|
||||
// Feature extractors
|
||||
private indicators: Map<
|
||||
string,
|
||||
{
|
||||
prices: number[];
|
||||
volumes: number[];
|
||||
returns: number[];
|
||||
sma20: number;
|
||||
sma50: number;
|
||||
rsi: number;
|
||||
macd: number;
|
||||
signal: number;
|
||||
volatility20?: number;
|
||||
}
|
||||
> = new Map();
|
||||
|
||||
// ML Configuration
|
||||
private mlConfig: MLModelConfig = {
|
||||
features: [
|
||||
'returns_20',
|
||||
'returns_50',
|
||||
'volatility_20',
|
||||
'rsi_14',
|
||||
'volume_ratio',
|
||||
'price_position',
|
||||
'macd_signal',
|
||||
],
|
||||
lookbackPeriod: 50,
|
||||
updateFrequency: 1440, // Daily
|
||||
minTrainingSize: 1000,
|
||||
};
|
||||
|
||||
protected override async onStart(): Promise<void> {
|
||||
logger.info('ML Enhanced Strategy starting...');
|
||||
this.tensorflow = await import('@tensorflow/tfjs-node');
|
||||
|
||||
// Try to load existing model
|
||||
if (this.mlConfig.modelPath) {
|
||||
try {
|
||||
this.model = await this.tf.loadLayersModel(`file://${this.mlConfig.modelPath}`);
|
||||
logger.info('Loaded existing ML model');
|
||||
} catch (_error) {
|
||||
logger.warn('Could not load model, will train new one');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize feature buffers for each symbol
|
||||
this.config.symbols.forEach(symbol => {
|
||||
this.featureBuffer.set(symbol, []);
|
||||
this.indicators.set(symbol, {
|
||||
prices: [],
|
||||
volumes: [],
|
||||
returns: [],
|
||||
sma20: 0,
|
||||
sma50: 0,
|
||||
rsi: 50,
|
||||
macd: 0,
|
||||
signal: 0,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const indicators = this.indicators.get(symbol);
|
||||
if (!indicators) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update price and volume history
|
||||
indicators.prices.push(data.data.close);
|
||||
indicators.volumes.push(data.data.volume);
|
||||
|
||||
if (indicators.prices.length > 200) {
|
||||
indicators.prices.shift();
|
||||
indicators.volumes.shift();
|
||||
}
|
||||
|
||||
// Calculate returns
|
||||
if (indicators.prices.length >= 2) {
|
||||
const ret =
|
||||
(data.data.close - at(indicators.prices, indicators.prices.length - 2)) /
|
||||
at(indicators.prices, indicators.prices.length - 2);
|
||||
indicators.returns.push(ret);
|
||||
|
||||
if (indicators.returns.length > 50) {
|
||||
indicators.returns.shift();
|
||||
}
|
||||
}
|
||||
|
||||
// Update technical indicators
|
||||
if (indicators.prices.length >= 20) {
|
||||
indicators.sma20 = this.calculateSMA(indicators.prices, 20);
|
||||
indicators.volatility20 = this.calculateVolatility(indicators.returns, 20);
|
||||
}
|
||||
|
||||
if (indicators.prices.length >= 50) {
|
||||
indicators.sma50 = this.calculateSMA(indicators.prices, 50);
|
||||
}
|
||||
|
||||
if (indicators.prices.length >= 14) {
|
||||
indicators.rsi = this.calculateRSI(indicators.prices, 14);
|
||||
}
|
||||
|
||||
// Extract features
|
||||
const features = this.extractFeatures(symbol, data);
|
||||
if (features) {
|
||||
const buffer = defined(this.featureBuffer.get(symbol));
|
||||
buffer.push(features);
|
||||
|
||||
if (buffer.length > this.mlConfig.lookbackPeriod) {
|
||||
buffer.shift();
|
||||
}
|
||||
|
||||
// Make prediction if we have enough data
|
||||
if (buffer.length === this.mlConfig.lookbackPeriod && this.model) {
|
||||
this.makePrediction(symbol, buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we should update the model
|
||||
const now = Date.now();
|
||||
if (now - this.lastUpdate > this.mlConfig.updateFrequency * 60 * 1000) {
|
||||
this.updateModel();
|
||||
this.lastUpdate = now;
|
||||
}
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const prediction = this.predictions.get(symbol);
|
||||
|
||||
if (!prediction || Math.abs(prediction) < 0.01) {
|
||||
return null; // No strong signal
|
||||
}
|
||||
|
||||
const position = this.getPosition(symbol);
|
||||
const indicators = this.indicators.get(symbol);
|
||||
|
||||
// Risk management checks
|
||||
const volatility = indicators?.volatility20 || 0.02;
|
||||
const maxPositionRisk = 0.02; // 2% max risk per position
|
||||
const _positionSize = this.calculateMLPositionSize(volatility, maxPositionRisk);
|
||||
|
||||
// Generate signals based on ML predictions
|
||||
if (prediction > 0.02 && position <= 0) {
|
||||
// Strong bullish prediction
|
||||
return {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: Math.min(prediction * 50, 1), // Scale prediction to 0-1
|
||||
reason: `ML prediction: ${(prediction * 100).toFixed(2)}% expected return`,
|
||||
metadata: {
|
||||
prediction,
|
||||
confidence: this.calculateConfidence(symbol),
|
||||
features: this.getLatestFeatures(symbol),
|
||||
},
|
||||
};
|
||||
} else if (prediction < -0.02 && position >= 0) {
|
||||
// Strong bearish prediction
|
||||
return {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: Math.min(Math.abs(prediction) * 50, 1),
|
||||
reason: `ML prediction: ${(prediction * 100).toFixed(2)}% expected return`,
|
||||
metadata: {
|
||||
prediction,
|
||||
confidence: this.calculateConfidence(symbol),
|
||||
features: this.getLatestFeatures(symbol),
|
||||
},
|
||||
};
|
||||
} else if (position !== 0 && Math.sign(position) !== Math.sign(prediction)) {
|
||||
// Exit if prediction reverses
|
||||
return {
|
||||
type: 'close',
|
||||
symbol,
|
||||
strength: 1,
|
||||
reason: 'ML prediction reversed',
|
||||
metadata: { prediction },
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractFeatures(symbol: string, data: MarketData): number[] | null {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
const indicators = this.indicators.get(symbol);
|
||||
if (!indicators || indicators.prices.length < 50) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const features: number[] = [];
|
||||
|
||||
// Price returns
|
||||
const currentPrice = at(indicators.prices, indicators.prices.length - 1);
|
||||
features.push(currentPrice / at(indicators.prices, indicators.prices.length - 20) - 1); // 20-day return
|
||||
features.push(currentPrice / at(indicators.prices, indicators.prices.length - 50) - 1); // 50-day return
|
||||
|
||||
// Volatility
|
||||
features.push(indicators.volatility20 || 0);
|
||||
|
||||
// RSI
|
||||
features.push((indicators.rsi - 50) / 50); // Normalize to -1 to 1
|
||||
|
||||
// Volume ratio
|
||||
const avgVolume = indicators.volumes.slice(-20).reduce((a: number, b: number) => a + b, 0) / 20;
|
||||
features.push(data.data.volume / avgVolume - 1);
|
||||
|
||||
// Price position in daily range
|
||||
const pricePosition = (data.data.close - data.data.low) / (data.data.high - data.data.low);
|
||||
features.push(pricePosition * 2 - 1); // Normalize to -1 to 1
|
||||
|
||||
// MACD signal
|
||||
if (indicators.macd && indicators.signal) {
|
||||
features.push((indicators.macd - indicators.signal) / currentPrice);
|
||||
} else {
|
||||
features.push(0);
|
||||
}
|
||||
|
||||
// Store for training
|
||||
if (indicators.returns.length >= 21) {
|
||||
const futureReturn = at(indicators.returns, indicators.returns.length - 1);
|
||||
this.trainingData.features.push([...features]);
|
||||
this.trainingData.labels.push(futureReturn);
|
||||
|
||||
// Limit training data size
|
||||
if (this.trainingData.features.length > 10000) {
|
||||
this.trainingData.features.shift();
|
||||
this.trainingData.labels.shift();
|
||||
}
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
private async makePrediction(symbol: string, featureBuffer: number[][]): Promise<void> {
|
||||
if (!this.model) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Prepare input tensor
|
||||
const input = this.tf.tensor3d([featureBuffer]);
|
||||
|
||||
// Make prediction
|
||||
const prediction = (await this.model.predict(input)) as tf.Tensor;
|
||||
const value = at(await prediction.data(), 0);
|
||||
|
||||
this.predictions.set(symbol, value);
|
||||
|
||||
// Cleanup tensors
|
||||
input.dispose();
|
||||
prediction.dispose();
|
||||
} catch (error) {
|
||||
logger.error('ML prediction error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateModel(): Promise<void> {
|
||||
if (this.trainingData.features.length < this.mlConfig.minTrainingSize) {
|
||||
logger.info('Not enough training data yet');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('Updating ML model...');
|
||||
|
||||
try {
|
||||
// Create or update model
|
||||
if (!this.model) {
|
||||
this.model = this.createModel();
|
||||
}
|
||||
|
||||
// Prepare training data
|
||||
const features = this.tf.tensor2d(this.trainingData.features);
|
||||
const labels = this.tf.tensor1d(this.trainingData.labels);
|
||||
|
||||
// Train model
|
||||
await this.model.fit(features, labels, {
|
||||
epochs: 50,
|
||||
batchSize: 32,
|
||||
validationSplit: 0.2,
|
||||
shuffle: true,
|
||||
callbacks: {
|
||||
onEpochEnd: (epoch, logs) => {
|
||||
if (epoch % 10 === 0) {
|
||||
logger.debug(`Epoch ${epoch}: loss = ${logs?.loss?.toFixed(4)}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
logger.info('Model updated successfully');
|
||||
|
||||
// Cleanup tensors
|
||||
features.dispose();
|
||||
labels.dispose();
|
||||
|
||||
// Save model if path provided
|
||||
if (this.mlConfig.modelPath) {
|
||||
await this.model.save(`file://${this.mlConfig.modelPath}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Model update error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private createModel(): tf.LayersModel {
|
||||
const model = this.tf.sequential({
|
||||
layers: [
|
||||
// LSTM layer for sequence processing
|
||||
this.tf.layers.lstm({
|
||||
units: 64,
|
||||
returnSequences: true,
|
||||
inputShape: [this.mlConfig.lookbackPeriod, this.mlConfig.features.length],
|
||||
}),
|
||||
this.tf.layers.dropout({ rate: 0.2 }),
|
||||
|
||||
// Second LSTM layer
|
||||
this.tf.layers.lstm({
|
||||
units: 32,
|
||||
returnSequences: false,
|
||||
}),
|
||||
this.tf.layers.dropout({ rate: 0.2 }),
|
||||
|
||||
// Dense layers
|
||||
this.tf.layers.dense({
|
||||
units: 16,
|
||||
activation: 'relu',
|
||||
}),
|
||||
this.tf.layers.dropout({ rate: 0.1 }),
|
||||
|
||||
// Output layer
|
||||
this.tf.layers.dense({
|
||||
units: 1,
|
||||
activation: 'tanh', // Output between -1 and 1
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
model.compile({
|
||||
optimizer: this.tf.train.adam(0.001),
|
||||
loss: 'meanSquaredError',
|
||||
metrics: ['mae'],
|
||||
});
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
private calculateConfidence(symbol: string): number {
|
||||
// Simple confidence based on prediction history accuracy
|
||||
// In practice, would track actual vs predicted returns
|
||||
const prediction = this.predictions.get(symbol) || 0;
|
||||
return Math.min(Math.abs(prediction) * 10, 1);
|
||||
}
|
||||
|
||||
private getLatestFeatures(symbol: string): Record<string, number> {
|
||||
const buffer = this.featureBuffer.get(symbol);
|
||||
if (!buffer || buffer.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const latest = at(buffer, buffer.length - 1);
|
||||
return {
|
||||
returns_20: at(latest, 0),
|
||||
returns_50: at(latest, 1),
|
||||
volatility_20: at(latest, 2),
|
||||
rsi_normalized: at(latest, 3),
|
||||
volume_ratio: at(latest, 4),
|
||||
price_position: at(latest, 5),
|
||||
macd_signal: at(latest, 6),
|
||||
};
|
||||
}
|
||||
|
||||
private calculateSMA(values: number[], period: number): number {
|
||||
return values.slice(-period).reduce((sum, value) => sum + value, 0) / period;
|
||||
}
|
||||
|
||||
private calculateRSI(values: number[], period: number): number {
|
||||
return TechnicalAnalysis.latest(new TechnicalAnalysis().rsi(values, period)) ?? 50;
|
||||
}
|
||||
|
||||
private calculateVolatility(returns: number[], period: number): number {
|
||||
if (returns.length < period) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const recentReturns = returns.slice(-period);
|
||||
const mean = recentReturns.reduce((a, b) => a + b, 0) / period;
|
||||
const variance = recentReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / period;
|
||||
|
||||
return Math.sqrt(variance * 252); // Annualized
|
||||
}
|
||||
|
||||
private calculateMLPositionSize(volatility: number, _maxRisk: number): number {
|
||||
// Kelly-inspired position sizing with volatility adjustment
|
||||
const targetVolatility = 0.15; // 15% annual target
|
||||
const volAdjustment = targetVolatility / volatility;
|
||||
|
||||
return Math.min(volAdjustment, 2.0); // Max 2x leverage
|
||||
}
|
||||
|
||||
protected override onStop(): void {
|
||||
logger.info('ML Enhanced Strategy stopped');
|
||||
|
||||
// Save final model if configured
|
||||
if (this.model && this.mlConfig.modelPath) {
|
||||
this.model
|
||||
.save(`file://${this.mlConfig.modelPath}`)
|
||||
.then(() => logger.info('Model saved'))
|
||||
.catch(err => logger.error('Failed to save model:', err));
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
this.featureBuffer.clear();
|
||||
this.predictions.clear();
|
||||
this.indicators.clear();
|
||||
if (this.model) {
|
||||
this.model.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
protected override onConfigUpdate(
|
||||
updates: Partial<StrategyConfig> & { mlConfig?: Partial<MLModelConfig> }
|
||||
): void {
|
||||
logger.info('ML Enhanced Strategy config updated:', updates);
|
||||
|
||||
if (updates.mlConfig) {
|
||||
this.mlConfig = { ...this.mlConfig, ...updates.mlConfig };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
import { freeze } from './strategy-decision';
|
||||
|
||||
export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import {
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../contracts/strategies';
|
||||
import type { StrategyConfig } from '../types';
|
||||
|
||||
export function smaConfig(config: StrategyConfig) {
|
||||
return { ...config, parameters: typescriptSmaParameters.parse(config.parameters) };
|
||||
}
|
||||
export function meanReversionConfig(config: StrategyConfig) {
|
||||
return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) };
|
||||
}
|
||||
|
|
@ -6,14 +6,14 @@ import type {
|
|||
StrategyDiagnostic,
|
||||
StrategyDiagnosticSnapshot,
|
||||
StrategyProgram,
|
||||
} from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import {
|
||||
nativeAdmissionOrders,
|
||||
type DecisionContext,
|
||||
type PublishedObservation,
|
||||
type ReplayIdentity,
|
||||
type ReplaySubmissionOutcome,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
freeze,
|
||||
increment,
|
||||
|
|
|
|||
|
|
@ -7,12 +7,12 @@ import type {
|
|||
StrategyAdmissionFeedback,
|
||||
StrategyDiagnostic,
|
||||
StrategyProgram,
|
||||
} from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import type {
|
||||
DecisionContext,
|
||||
nativeAdmissionOrders,
|
||||
PublishedObservation,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
export function freeze<T>(value: T): DeepReadonly<T> {
|
||||
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
||||
|
|
|
|||
|
|
@ -4,11 +4,9 @@ import { BacktestConfigSchema, RiskLimitsSchema } from '@stock-bot/stock-config/
|
|||
export { BacktestConfigSchema, RiskLimitsSchema };
|
||||
export type { BacktestConfig } from '@stock-bot/stock-config/backtest';
|
||||
|
||||
// Trading modes
|
||||
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);
|
||||
export type TradingMode = z.infer<typeof TradingModeSchema>;
|
||||
|
||||
// Mode configurations
|
||||
export const PaperConfigSchema = z.object({
|
||||
mode: z.literal('paper'),
|
||||
startingCapital: z.number().positive(),
|
||||
|
|
@ -48,14 +46,8 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [
|
|||
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
|
||||
custom?: Partial<{
|
||||
BacktestRunner: import('./backtest/ResearchBacktestPool').ResearchBacktestRuntime;
|
||||
StorageService: import('./services/StorageService').StorageService;
|
||||
MarketDataService: import('./services/MarketDataService').MarketDataService;
|
||||
ExecutionService: import('./services/ExecutionService').ExecutionService;
|
||||
AnalyticsService: import('./services/AnalyticsService').AnalyticsService;
|
||||
StrategyManager: import('./strategies/StrategyManager').StrategyManager;
|
||||
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
|
||||
ModeManager: import('./core/ModeManager').ModeManager;
|
||||
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;
|
||||
StorageService: import('@stock-bot/trading-runtime/historical-storage').StorageService;
|
||||
CanonicalPaperRuntime: import('@stock-bot/stock-config/paper-runtime').PaperRuntime;
|
||||
PaperDeploymentHost: import('./paper/PaperDeploymentHost').PaperDeploymentHost;
|
||||
}>;
|
||||
};
|
||||
|
|
@ -63,7 +55,6 @@ export type { BacktestResult } from './backtest/RustBacktestAdapter';
|
|||
|
||||
export type ModeConfig = z.infer<typeof ModeConfigSchema>;
|
||||
|
||||
// Market data types
|
||||
export const QuoteSchema = z.object({
|
||||
symbol: z.string(),
|
||||
bid: z.number(),
|
||||
|
|
@ -114,56 +105,3 @@ export type MarketData = z.infer<typeof MarketDataSchema>;
|
|||
export type Quote = z.infer<typeof QuoteSchema>;
|
||||
export type Trade = z.infer<typeof TradeSchema>;
|
||||
export type Bar = z.infer<typeof BarSchema>;
|
||||
|
||||
// Order types
|
||||
export const OrderSideSchema = z.enum(['buy', 'sell']);
|
||||
export const OrderTypeSchema = z.enum(['market', 'limit', 'stop', 'stop_limit']);
|
||||
export const TimeInForceSchema = z.enum(['DAY', 'GTC', 'IOC', 'FOK']);
|
||||
|
||||
export const OrderRequestSchema = z.object({
|
||||
symbol: z.string().trim().min(1).max(50),
|
||||
side: OrderSideSchema,
|
||||
quantity: z.number().finite().min(1e-8).max(1e9),
|
||||
orderType: OrderTypeSchema,
|
||||
limitPrice: z.number().finite().positive().optional(),
|
||||
stopPrice: z.number().finite().positive().optional(),
|
||||
timeInForce: TimeInForceSchema.default('DAY'),
|
||||
clientOrderId: z.string().min(1).max(256).optional(),
|
||||
});
|
||||
|
||||
export type OrderRequest = z.infer<typeof OrderRequestSchema>;
|
||||
|
||||
// Position types
|
||||
export const PositionSchema = z.object({
|
||||
symbol: z.string(),
|
||||
quantity: z.number(),
|
||||
averagePrice: z.number(),
|
||||
realizedPnl: z.number(),
|
||||
unrealizedPnl: z.number(),
|
||||
totalCost: z.number(),
|
||||
lastUpdate: z.string().datetime(),
|
||||
});
|
||||
|
||||
export type Position = z.infer<typeof PositionSchema>;
|
||||
|
||||
// Strategy types
|
||||
export const StrategyConfigSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
enabled: z.boolean(),
|
||||
parameters: z.record(z.unknown()),
|
||||
symbols: z.array(z.string()),
|
||||
allocation: z.number().min(0).max(1),
|
||||
});
|
||||
|
||||
export type StrategyConfig = z.infer<typeof StrategyConfigSchema>;
|
||||
|
||||
export { PerformanceMetricsSchema, RiskMetricsSchema } from './contracts/analytics';
|
||||
export type { PerformanceMetrics, RiskMetrics } from './contracts/analytics';
|
||||
|
||||
// Re-export specialized types
|
||||
export type {
|
||||
MarketMicrostructure,
|
||||
PriceLevel,
|
||||
OrderBookSnapshot,
|
||||
} from './types/MarketMicrostructure';
|
||||
|
|
|
|||
|
|
@ -1,29 +0,0 @@
|
|||
export interface MarketMicrostructure {
|
||||
symbol: string;
|
||||
avgSpreadBps: number;
|
||||
dailyVolume: number;
|
||||
avgTradeSize: number;
|
||||
volatility: number;
|
||||
tickSize: number;
|
||||
lotSize: number;
|
||||
intradayVolumeProfile: number[]; // 24 hourly buckets as percentages
|
||||
}
|
||||
|
||||
export interface PriceLevel {
|
||||
price: number;
|
||||
size: number;
|
||||
orderCount?: number;
|
||||
hiddenSize?: number; // For modeling iceberg orders
|
||||
}
|
||||
|
||||
export interface OrderBookSnapshot {
|
||||
symbol: string;
|
||||
timestamp: Date;
|
||||
bids: PriceLevel[];
|
||||
asks: PriceLevel[];
|
||||
lastTrade?: {
|
||||
price: number;
|
||||
size: number;
|
||||
side: 'buy' | 'sell';
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue