improved dashboard
This commit is contained in:
parent
114c280734
commit
90168ba619
8 changed files with 781 additions and 47 deletions
245
apps/core-services/risk-guardian/src/index.ts
Normal file
245
apps/core-services/risk-guardian/src/index.ts
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
import { Hono } from 'hono';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import Redis from 'ioredis';
|
||||
|
||||
const app = new Hono();
|
||||
const redis = new Redis({
|
||||
host: process.env.REDIS_HOST || 'localhost',
|
||||
port: parseInt(process.env.REDIS_PORT || '6379'),
|
||||
enableReadyCheck: false,
|
||||
maxRetriesPerRequest: null,
|
||||
});
|
||||
|
||||
// WebSocket server for real-time risk alerts
|
||||
const wss = new WebSocketServer({ port: 8081 });
|
||||
|
||||
// Risk thresholds configuration
|
||||
interface RiskThresholds {
|
||||
maxPositionSize: number;
|
||||
maxDailyLoss: number;
|
||||
maxPortfolioRisk: number;
|
||||
volatilityLimit: number;
|
||||
}
|
||||
|
||||
const defaultThresholds: RiskThresholds = {
|
||||
maxPositionSize: 100000, // $100k max position
|
||||
maxDailyLoss: 10000, // $10k max daily loss
|
||||
maxPortfolioRisk: 0.02, // 2% portfolio risk
|
||||
volatilityLimit: 0.3 // 30% volatility limit
|
||||
};
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', (c) => {
|
||||
return c.json({
|
||||
service: 'risk-guardian',
|
||||
status: 'healthy',
|
||||
timestamp: new Date(),
|
||||
version: '1.0.0',
|
||||
connections: wss.clients.size
|
||||
});
|
||||
});
|
||||
|
||||
// Get risk thresholds
|
||||
app.get('/api/risk/thresholds', async (c) => {
|
||||
try {
|
||||
const thresholds = await redis.hgetall('risk:thresholds');
|
||||
const parsedThresholds = Object.keys(thresholds).length > 0
|
||||
? Object.fromEntries(
|
||||
Object.entries(thresholds).map(([k, v]) => [k, parseFloat(v as string)])
|
||||
)
|
||||
: defaultThresholds;
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
data: parsedThresholds
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching risk thresholds:', error);
|
||||
return c.json({ success: false, error: 'Failed to fetch thresholds' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Update risk thresholds
|
||||
app.put('/api/risk/thresholds', async (c) => {
|
||||
try {
|
||||
const thresholds = await c.req.json();
|
||||
await redis.hmset('risk:thresholds', thresholds);
|
||||
|
||||
// Broadcast threshold update to connected clients
|
||||
const message = JSON.stringify({
|
||||
type: 'THRESHOLD_UPDATE',
|
||||
data: thresholds,
|
||||
timestamp: new Date()
|
||||
});
|
||||
|
||||
wss.clients.forEach(client => {
|
||||
if (client.readyState === 1) { // WebSocket.OPEN
|
||||
client.send(message);
|
||||
}
|
||||
});
|
||||
|
||||
return c.json({ success: true, data: thresholds });
|
||||
} catch (error) {
|
||||
console.error('Error updating risk thresholds:', error);
|
||||
return c.json({ success: false, error: 'Failed to update thresholds' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Real-time risk monitoring endpoint
|
||||
app.post('/api/risk/evaluate', async (c) => {
|
||||
try {
|
||||
const { symbol, quantity, price, portfolioValue } = await c.req.json();
|
||||
|
||||
const thresholds = await redis.hgetall('risk:thresholds');
|
||||
const activeThresholds = Object.keys(thresholds).length > 0
|
||||
? Object.fromEntries(
|
||||
Object.entries(thresholds).map(([k, v]) => [k, parseFloat(v as string)])
|
||||
)
|
||||
: defaultThresholds;
|
||||
|
||||
const positionValue = quantity * price;
|
||||
const positionRisk = positionValue / portfolioValue;
|
||||
|
||||
const riskEvaluation = {
|
||||
symbol,
|
||||
positionValue,
|
||||
positionRisk,
|
||||
violations: [] as string[],
|
||||
riskLevel: 'LOW' as 'LOW' | 'MEDIUM' | 'HIGH'
|
||||
};
|
||||
|
||||
// Check risk violations
|
||||
if (positionValue > activeThresholds.maxPositionSize) {
|
||||
riskEvaluation.violations.push(`Position size exceeds limit: $${positionValue.toLocaleString()}`);
|
||||
}
|
||||
|
||||
if (positionRisk > activeThresholds.maxPortfolioRisk) {
|
||||
riskEvaluation.violations.push(`Portfolio risk exceeds limit: ${(positionRisk * 100).toFixed(2)}%`);
|
||||
}
|
||||
|
||||
// Determine risk level
|
||||
if (riskEvaluation.violations.length > 0) {
|
||||
riskEvaluation.riskLevel = 'HIGH';
|
||||
} else if (positionRisk > activeThresholds.maxPortfolioRisk * 0.7) {
|
||||
riskEvaluation.riskLevel = 'MEDIUM';
|
||||
}
|
||||
|
||||
// Store risk evaluation
|
||||
await redis.setex(
|
||||
`risk:evaluation:${symbol}:${Date.now()}`,
|
||||
3600, // 1 hour TTL
|
||||
JSON.stringify(riskEvaluation)
|
||||
);
|
||||
|
||||
// Send real-time alert if high risk
|
||||
if (riskEvaluation.riskLevel === 'HIGH') {
|
||||
const alert = {
|
||||
type: 'RISK_ALERT',
|
||||
level: 'HIGH',
|
||||
data: riskEvaluation,
|
||||
timestamp: new Date()
|
||||
};
|
||||
|
||||
wss.clients.forEach(client => {
|
||||
if (client.readyState === 1) {
|
||||
client.send(JSON.stringify(alert));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return c.json({ success: true, data: riskEvaluation });
|
||||
} catch (error) {
|
||||
console.error('Error evaluating risk:', error);
|
||||
return c.json({ success: false, error: 'Failed to evaluate risk' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Get risk history
|
||||
app.get('/api/risk/history', async (c) => {
|
||||
try {
|
||||
const keys = await redis.keys('risk:evaluation:*');
|
||||
const evaluations: any[] = [];
|
||||
|
||||
for (const key of keys.slice(0, 100)) { // Limit to 100 recent evaluations
|
||||
const data = await redis.get(key);
|
||||
if (data) {
|
||||
evaluations.push(JSON.parse(data));
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
data: evaluations.sort((a: any, b: any) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching risk history:', error);
|
||||
return c.json({ success: false, error: 'Failed to fetch risk history' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// WebSocket connection handling
|
||||
wss.on('connection', (ws) => {
|
||||
console.log('New risk monitoring client connected');
|
||||
|
||||
// Send welcome message
|
||||
ws.send(JSON.stringify({
|
||||
type: 'CONNECTED',
|
||||
message: 'Connected to Risk Guardian',
|
||||
timestamp: new Date()
|
||||
}));
|
||||
|
||||
ws.on('close', () => {
|
||||
console.log('Risk monitoring client disconnected');
|
||||
});
|
||||
|
||||
ws.on('error', (error) => {
|
||||
console.error('WebSocket error:', error);
|
||||
});
|
||||
});
|
||||
|
||||
// Redis event subscriptions for cross-service communication
|
||||
redis.subscribe('trading:position:opened', 'trading:position:closed');
|
||||
|
||||
redis.on('message', async (channel, message) => {
|
||||
try {
|
||||
const data = JSON.parse(message);
|
||||
|
||||
if (channel === 'trading:position:opened') {
|
||||
// Auto-evaluate risk for new positions
|
||||
const evaluation = await evaluatePositionRisk(data);
|
||||
|
||||
// Broadcast to connected clients
|
||||
wss.clients.forEach(client => {
|
||||
if (client.readyState === 1) {
|
||||
client.send(JSON.stringify({
|
||||
type: 'POSITION_RISK_UPDATE',
|
||||
data: evaluation,
|
||||
timestamp: new Date()
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing Redis message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
async function evaluatePositionRisk(position: any) {
|
||||
// Implementation would evaluate position against current thresholds
|
||||
// This is a simplified version
|
||||
return {
|
||||
symbol: position.symbol,
|
||||
riskLevel: 'LOW',
|
||||
timestamp: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
const port = parseInt(process.env.PORT || '3002');
|
||||
|
||||
console.log(`🛡️ Risk Guardian starting on port ${port}`);
|
||||
console.log(`📡 WebSocket server running on port 8081`);
|
||||
|
||||
export default {
|
||||
port,
|
||||
fetch: app.fetch,
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue