commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
|
|
@ -1,179 +1,215 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { AnalyticsService } from '../../services/AnalyticsService';
|
||||
|
||||
const DateRangeSchema = z.object({
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime()
|
||||
});
|
||||
|
||||
const OptimizationRequestSchema = z.object({
|
||||
symbols: z.array(z.string()),
|
||||
returns: z.array(z.array(z.number())),
|
||||
constraints: z.object({
|
||||
minWeight: z.number().optional(),
|
||||
maxWeight: z.number().optional(),
|
||||
targetReturn: z.number().optional(),
|
||||
maxRisk: z.number().optional()
|
||||
}).optional()
|
||||
});
|
||||
|
||||
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
|
||||
|
||||
// Get performance metrics
|
||||
app.get('/performance/:portfolioId', async (c) => {
|
||||
try {
|
||||
const portfolioId = c.req.param('portfolioId');
|
||||
const query = c.req.query();
|
||||
|
||||
const { startDate, endDate } = DateRangeSchema.parse({
|
||||
startDate: query.start_date,
|
||||
endDate: query.end_date
|
||||
});
|
||||
|
||||
const metrics = await analyticsService.getPerformanceMetrics(
|
||||
portfolioId,
|
||||
new Date(startDate),
|
||||
new Date(endDate)
|
||||
);
|
||||
|
||||
return c.json(metrics);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid date range',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error getting performance metrics:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to get performance metrics'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Portfolio optimization
|
||||
app.post('/optimize', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const request = OptimizationRequestSchema.parse(body);
|
||||
|
||||
const result = await analyticsService.optimizePortfolio({
|
||||
returns: request.returns,
|
||||
constraints: request.constraints
|
||||
});
|
||||
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid optimization request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error optimizing portfolio:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to optimize portfolio'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get risk metrics
|
||||
app.get('/risk/:portfolioId', async (c) => {
|
||||
try {
|
||||
const portfolioId = c.req.param('portfolioId');
|
||||
const metrics = await analyticsService.getRiskMetrics(portfolioId);
|
||||
|
||||
return c.json(metrics);
|
||||
} 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);
|
||||
}
|
||||
});
|
||||
|
||||
// Market regime detection
|
||||
app.get('/regime', async (c) => {
|
||||
try {
|
||||
const regime = await analyticsService.detectMarketRegime();
|
||||
|
||||
return c.json({
|
||||
regime,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error detecting market regime:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to detect market regime'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Calculate correlation matrix
|
||||
app.post('/correlation', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { symbols } = z.object({
|
||||
symbols: z.array(z.string()).min(2)
|
||||
}).parse(body);
|
||||
|
||||
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
|
||||
|
||||
return c.json({
|
||||
symbols,
|
||||
matrix
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid correlation request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error calculating correlation:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to calculate correlation'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ML model prediction
|
||||
app.post('/predict', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { modelId, features } = z.object({
|
||||
modelId: z.string(),
|
||||
features: z.record(z.number())
|
||||
}).parse(body);
|
||||
|
||||
const prediction = await analyticsService.predictWithModel(modelId, features);
|
||||
|
||||
if (prediction) {
|
||||
return c.json(prediction);
|
||||
} else {
|
||||
return c.json({ error: 'Model not found or prediction failed' }, 404);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid prediction request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error making prediction:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to make prediction'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { AnalyticsService } from '../../services/AnalyticsService';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../../types';
|
||||
|
||||
const DateRangeSchema = z.object({
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
});
|
||||
|
||||
const OptimizationRequestSchema = z.object({
|
||||
symbols: z.array(z.string()),
|
||||
returns: z.array(z.array(z.number())),
|
||||
constraints: z
|
||||
.object({
|
||||
minWeight: z.number().optional(),
|
||||
maxWeight: z.number().optional(),
|
||||
targetReturn: z.number().optional(),
|
||||
maxRisk: z.number().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
|
||||
|
||||
// Get performance metrics
|
||||
app.get('/performance/:portfolioId', async c => {
|
||||
try {
|
||||
const portfolioId = c.req.param('portfolioId');
|
||||
const query = c.req.query();
|
||||
|
||||
const { startDate, endDate } = DateRangeSchema.parse({
|
||||
startDate: query.start_date,
|
||||
endDate: query.end_date,
|
||||
});
|
||||
|
||||
const metrics = await analyticsService.getPerformanceMetrics(
|
||||
portfolioId,
|
||||
new Date(startDate),
|
||||
new Date(endDate)
|
||||
);
|
||||
|
||||
return c.json(metrics);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid date range',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error getting performance metrics:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get performance metrics',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Portfolio optimization
|
||||
app.post('/optimize', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const request = OptimizationRequestSchema.parse(body);
|
||||
|
||||
const result = await analyticsService.optimizePortfolio({
|
||||
returns: request.returns,
|
||||
constraints: request.constraints,
|
||||
});
|
||||
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid optimization request',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error optimizing portfolio:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to optimize portfolio',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Get risk metrics
|
||||
app.get('/risk/:portfolioId', async c => {
|
||||
try {
|
||||
const portfolioId = c.req.param('portfolioId');
|
||||
const metrics = await analyticsService.getRiskMetrics(portfolioId);
|
||||
|
||||
return c.json(metrics);
|
||||
} 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
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Market regime detection
|
||||
app.get('/regime', async c => {
|
||||
try {
|
||||
const regime = await analyticsService.detectMarketRegime();
|
||||
|
||||
return c.json({
|
||||
regime,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error detecting market regime:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to detect market regime',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Calculate correlation matrix
|
||||
app.post('/correlation', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { symbols } = z
|
||||
.object({
|
||||
symbols: z.array(z.string()).min(2),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
|
||||
|
||||
return c.json({
|
||||
symbols,
|
||||
matrix,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid correlation request',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error calculating correlation:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to calculate correlation',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// ML model prediction
|
||||
app.post('/predict', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { modelId, features } = z
|
||||
.object({
|
||||
modelId: z.string(),
|
||||
features: z.record(z.number()),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
const prediction = await analyticsService.predictWithModel(modelId, features);
|
||||
|
||||
if (prediction) {
|
||||
return c.json(prediction);
|
||||
} else {
|
||||
return c.json({ error: 'Model not found or prediction failed' }, 404);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid prediction request',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error making prediction:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to make prediction',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,245 +1,278 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { BacktestConfigSchema } from '../../types';
|
||||
import { BacktestEngine } from '../../backtest/BacktestEngine';
|
||||
import { ModeManager } from '../../core/ModeManager';
|
||||
|
||||
const BacktestIdSchema = z.object({
|
||||
backtestId: z.string()
|
||||
});
|
||||
|
||||
export function createBacktestRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
const backtestEngine = container.custom?.BacktestEngine as BacktestEngine;
|
||||
const modeManager = container.custom?.ModeManager as ModeManager;
|
||||
|
||||
// Default POST to / is the same as /run for backward compatibility
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode(config);
|
||||
|
||||
// Run backtest
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Run new backtest (same as above but at /run)
|
||||
app.post('/run', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode(config);
|
||||
|
||||
// Run backtest
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Stop running backtest
|
||||
app.post('/stop', async (c) => {
|
||||
try {
|
||||
await backtestEngine.stopBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest stop requested',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error stopping backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to stop backtest'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Pause running backtest
|
||||
app.post('/pause', async (c) => {
|
||||
try {
|
||||
await backtestEngine.pauseBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest paused',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error pausing backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to pause backtest'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Resume paused backtest
|
||||
app.post('/resume', async (c) => {
|
||||
try {
|
||||
await backtestEngine.resumeBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest resumed',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error resuming backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to resume backtest'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Set backtest speed
|
||||
app.post('/speed', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const speed = body.speed ?? 1;
|
||||
|
||||
backtestEngine.setSpeedMultiplier(speed);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest speed updated',
|
||||
speed: speed === null ? 'unlimited' : speed,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error setting backtest speed:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to set speed'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest progress
|
||||
app.get('/progress', async (c) => {
|
||||
try {
|
||||
const status = backtestEngine.getStatus();
|
||||
|
||||
return c.json({
|
||||
status: status.isPaused ? 'paused' : (status.isRunning ? 'running' : 'idle'),
|
||||
progress: status.progress,
|
||||
currentTime: new Date(status.currentTime).toISOString(),
|
||||
isRunning: status.isRunning,
|
||||
isPaused: status.isPaused
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error getting backtest progress:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to get progress'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Stream backtest events (Server-Sent Events)
|
||||
app.get('/stream', async (c) => {
|
||||
c.header('Content-Type', 'text/event-stream');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
c.header('Connection', 'keep-alive');
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
// Listen for backtest events
|
||||
const onProgress = (data: any) => {
|
||||
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
const onComplete = (data: any) => {
|
||||
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
|
||||
controller.close();
|
||||
};
|
||||
|
||||
backtestEngine.on('progress', onProgress);
|
||||
backtestEngine.on('complete', onComplete);
|
||||
|
||||
// Cleanup on close
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
backtestEngine.off('progress', onProgress);
|
||||
backtestEngine.off('complete', onComplete);
|
||||
controller.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return new Response(stream);
|
||||
});
|
||||
|
||||
// Validate backtest configuration
|
||||
app.post('/validate', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Additional validation logic
|
||||
const validation = {
|
||||
valid: true,
|
||||
warnings: [] as string[],
|
||||
estimatedDuration: 0
|
||||
};
|
||||
|
||||
// Check data availability
|
||||
const startDate = new Date(config.startDate);
|
||||
const endDate = new Date(config.endDate);
|
||||
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
|
||||
|
||||
if (days > 365) {
|
||||
validation.warnings.push('Large date range may take significant time to process');
|
||||
}
|
||||
|
||||
if (config.symbols.length > 100) {
|
||||
validation.warnings.push('Large number of symbols may impact performance');
|
||||
}
|
||||
|
||||
// Estimate duration (simplified)
|
||||
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds
|
||||
|
||||
return c.json(validation);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
valid: false,
|
||||
error: 'Invalid configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
valid: false,
|
||||
error: error instanceof Error ? error.message : 'Validation failed'
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
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';
|
||||
import { BacktestConfigSchema } from '../../types';
|
||||
|
||||
const _BacktestIdSchema = z.object({
|
||||
backtestId: z.string(),
|
||||
});
|
||||
|
||||
export function createBacktestRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
const backtestEngine = defined(container.custom?.BacktestEngine);
|
||||
const modeManager = container.custom?.ModeManager as ModeManager;
|
||||
|
||||
// Default POST to / is the same as /run for backward compatibility
|
||||
app.post('/', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode(config);
|
||||
|
||||
// Run backtest
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Run new backtest (same as above but at /run)
|
||||
app.post('/run', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode(config);
|
||||
|
||||
// Run backtest
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Stop running backtest
|
||||
app.post('/stop', async c => {
|
||||
try {
|
||||
await backtestEngine.stopBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest stop requested',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error stopping backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to stop backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Pause running backtest
|
||||
app.post('/pause', async c => {
|
||||
try {
|
||||
await backtestEngine.pauseBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest paused',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error pausing backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to pause backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Resume paused backtest
|
||||
app.post('/resume', async c => {
|
||||
try {
|
||||
await backtestEngine.resumeBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest resumed',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error resuming backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to resume backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Set backtest speed
|
||||
app.post('/speed', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const speed = body.speed ?? 1;
|
||||
|
||||
backtestEngine.setSpeedMultiplier(speed);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest speed updated',
|
||||
speed: speed === null ? 'unlimited' : speed,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error setting backtest speed:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to set speed',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest progress
|
||||
app.get('/progress', async c => {
|
||||
try {
|
||||
const status = backtestEngine.getStatus();
|
||||
|
||||
return c.json({
|
||||
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
|
||||
progress: status.progress,
|
||||
currentTime: new Date(status.currentTime).toISOString(),
|
||||
isRunning: status.isRunning,
|
||||
isPaused: status.isPaused,
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error getting backtest progress:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get progress',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Stream backtest events (Server-Sent Events)
|
||||
app.get('/stream', async c => {
|
||||
c.header('Content-Type', 'text/event-stream');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
c.header('Connection', 'keep-alive');
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
// Listen for backtest events
|
||||
const onProgress = (data: unknown) => {
|
||||
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
const onComplete = (data: unknown) => {
|
||||
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
|
||||
controller.close();
|
||||
};
|
||||
|
||||
backtestEngine.on('progress', onProgress);
|
||||
backtestEngine.on('complete', onComplete);
|
||||
|
||||
// Cleanup on close
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
backtestEngine.off('progress', onProgress);
|
||||
backtestEngine.off('complete', onComplete);
|
||||
controller.close();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream);
|
||||
});
|
||||
|
||||
// Validate backtest configuration
|
||||
app.post('/validate', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
||||
// Additional validation logic
|
||||
const validation = {
|
||||
valid: true,
|
||||
warnings: [] as string[],
|
||||
estimatedDuration: 0,
|
||||
};
|
||||
|
||||
// Check data availability
|
||||
const startDate = new Date(config.startDate);
|
||||
const endDate = new Date(config.endDate);
|
||||
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
|
||||
|
||||
if (days > 365) {
|
||||
validation.warnings.push('Large date range may take significant time to process');
|
||||
}
|
||||
|
||||
if (config.symbols.length > 100) {
|
||||
validation.warnings.push('Large number of symbols may impact performance');
|
||||
}
|
||||
|
||||
// Estimate duration (simplified)
|
||||
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds
|
||||
|
||||
return c.json(validation);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json(
|
||||
{
|
||||
valid: false,
|
||||
error: 'Invalid configuration',
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
return c.json(
|
||||
{
|
||||
valid: false,
|
||||
error: error instanceof Error ? error.message : 'Validation failed',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,111 +1,129 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { OrderRequestSchema } from '../../types';
|
||||
import { ExecutionService } from '../../services/ExecutionService';
|
||||
|
||||
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.parse(body);
|
||||
|
||||
const result = await executionService.submitOrder(orderRequest);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
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).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;
|
||||
}
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { ExecutionService } 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.parse(body);
|
||||
|
||||
const result = await executionService.submitOrder(orderRequest);
|
||||
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
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).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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,121 +1,139 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { ModeManager } from '../../core/ModeManager';
|
||||
|
||||
const SymbolSchema = z.object({
|
||||
symbol: z.string()
|
||||
});
|
||||
|
||||
export function createPositionRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
const modeManager = container.custom?.ModeManager as ModeManager;
|
||||
|
||||
// Get all positions
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
const tradingEngine = modeManager.getTradingEngine();
|
||||
const positions = JSON.parse(tradingEngine.getAllPositions());
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const positions = JSON.parse(tradingEngine.getOpenPositions());
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
|
||||
const positionJson = tradingEngine.getPosition(symbol);
|
||||
const position = positionJson ? JSON.parse(positionJson) : null;
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const [realizedPnl, unrealizedPnl] = tradingEngine.getTotalPnl();
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const metrics = JSON.parse(tradingEngine.getRiskMetrics());
|
||||
|
||||
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;
|
||||
}
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
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 modeManager = container.custom?.ModeManager as ModeManager;
|
||||
|
||||
// Get all positions
|
||||
app.get('/', async c => {
|
||||
try {
|
||||
const tradingEngine = modeManager.getTradingEngine();
|
||||
const positions = JSON.parse(tradingEngine.getAllPositions());
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const positions = JSON.parse(tradingEngine.getOpenPositions());
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
|
||||
const positionJson = tradingEngine.getPosition(symbol);
|
||||
const position = positionJson ? JSON.parse(positionJson) : null;
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const [realizedPnl = 0, unrealizedPnl = 0] = tradingEngine.getTotalPnl();
|
||||
|
||||
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 tradingEngine = modeManager.getTradingEngine();
|
||||
const metrics = JSON.parse(tradingEngine.getRiskMetrics());
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue