Files
trading_bot_v4/lib/database/trades.ts
mindesbunister d64f6d84c4 feat: implement dual stop system and database tracking
- Add PostgreSQL database with Prisma ORM
  - Trade model: tracks entry/exit, P&L, order signatures, config snapshots
  - PriceUpdate model: tracks price movements for drawdown analysis
  - SystemEvent model: logs errors and system events
  - DailyStats model: aggregated performance metrics

- Implement dual stop loss system (enabled by default)
  - Soft stop (TRIGGER_LIMIT) at -1.5% to avoid wicks
  - Hard stop (TRIGGER_MARKET) at -2.5% to guarantee exit
  - Configurable via USE_DUAL_STOPS, SOFT_STOP_PERCENT, HARD_STOP_PERCENT
  - Backward compatible with single stop modes

- Add database service layer (lib/database/trades.ts)
  - createTrade(): save new trades with all details
  - updateTradeExit(): close trades with P&L calculations
  - addPriceUpdate(): track price movements during trade
  - getTradeStats(): calculate win rate, profit factor, avg win/loss
  - logSystemEvent(): log errors and system events

- Update execute endpoint to use dual stops and save to database
  - Calculate dual stop prices when enabled
  - Pass dual stop parameters to placeExitOrders
  - Save complete trade record to database after execution

- Add test trade button to settings page
  - New /api/trading/test endpoint for executing test trades
  - Displays detailed results including dual stop prices
  - Confirmation dialog before execution
  - Shows entry price, position size, stops, and TX signature

- Generate Prisma client in Docker build
- Update DATABASE_URL for container networking
2025-10-26 21:29:27 +01:00

246 lines
6.3 KiB
TypeScript

/**
* Database Service for Trade Tracking and Analytics
*/
import { PrismaClient } from '@prisma/client'
// Singleton Prisma client
let prisma: PrismaClient | null = null
export function getPrismaClient(): PrismaClient {
if (!prisma) {
prisma = new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
})
console.log('✅ Prisma client initialized')
}
return prisma
}
export interface CreateTradeParams {
positionId: string
symbol: string
direction: 'long' | 'short'
entryPrice: number
entrySlippage?: number
positionSizeUSD: number
leverage: number
stopLossPrice: number
softStopPrice?: number
hardStopPrice?: number
takeProfit1Price: number
takeProfit2Price: number
tp1SizePercent: number
tp2SizePercent: number
entryOrderTx: string
tp1OrderTx?: string
tp2OrderTx?: string
slOrderTx?: string
softStopOrderTx?: string
hardStopOrderTx?: string
configSnapshot: any
signalSource?: string
signalStrength?: string
timeframe?: string
}
export interface UpdateTradeExitParams {
positionId: string
exitPrice: number
exitReason: 'TP1' | 'TP2' | 'SL' | 'SOFT_SL' | 'HARD_SL' | 'manual' | 'emergency'
realizedPnL: number
exitOrderTx: string
holdTimeSeconds: number
maxDrawdown?: number
maxGain?: number
}
/**
* Create a new trade record
*/
export async function createTrade(params: CreateTradeParams) {
const prisma = getPrismaClient()
try {
const trade = await prisma.trade.create({
data: {
positionId: params.positionId,
symbol: params.symbol,
direction: params.direction,
entryPrice: params.entryPrice,
entryTime: new Date(),
entrySlippage: params.entrySlippage,
positionSizeUSD: params.positionSizeUSD,
leverage: params.leverage,
stopLossPrice: params.stopLossPrice,
softStopPrice: params.softStopPrice,
hardStopPrice: params.hardStopPrice,
takeProfit1Price: params.takeProfit1Price,
takeProfit2Price: params.takeProfit2Price,
tp1SizePercent: params.tp1SizePercent,
tp2SizePercent: params.tp2SizePercent,
entryOrderTx: params.entryOrderTx,
tp1OrderTx: params.tp1OrderTx,
tp2OrderTx: params.tp2OrderTx,
slOrderTx: params.slOrderTx,
softStopOrderTx: params.softStopOrderTx,
hardStopOrderTx: params.hardStopOrderTx,
configSnapshot: params.configSnapshot,
signalSource: params.signalSource,
signalStrength: params.signalStrength,
timeframe: params.timeframe,
status: 'open',
},
})
console.log(`📊 Trade record created: ${trade.id}`)
return trade
} catch (error) {
console.error('❌ Failed to create trade record:', error)
throw error
}
}
/**
* Update trade when position exits
*/
export async function updateTradeExit(params: UpdateTradeExitParams) {
const prisma = getPrismaClient()
try {
// First fetch the trade to get positionSizeUSD
const existingTrade = await prisma.trade.findUnique({
where: { positionId: params.positionId },
select: { positionSizeUSD: true },
})
if (!existingTrade) {
throw new Error(`Trade not found: ${params.positionId}`)
}
const trade = await prisma.trade.update({
where: { positionId: params.positionId },
data: {
exitPrice: params.exitPrice,
exitTime: new Date(),
exitReason: params.exitReason,
realizedPnL: params.realizedPnL,
realizedPnLPercent: (params.realizedPnL / existingTrade.positionSizeUSD) * 100,
exitOrderTx: params.exitOrderTx,
holdTimeSeconds: params.holdTimeSeconds,
maxDrawdown: params.maxDrawdown,
maxGain: params.maxGain,
status: 'closed',
},
})
console.log(`📊 Trade closed: ${trade.id} | P&L: $${params.realizedPnL.toFixed(2)}`)
return trade
} catch (error) {
console.error('❌ Failed to update trade exit:', error)
throw error
}
}
/**
* Add price update for a trade (for tracking max gain/drawdown)
*/
export async function addPriceUpdate(
tradeId: string,
price: number,
pnl: number,
pnlPercent: number
) {
const prisma = getPrismaClient()
try {
await prisma.priceUpdate.create({
data: {
tradeId,
price,
pnl,
pnlPercent,
},
})
} catch (error) {
console.error('❌ Failed to add price update:', error)
// Don't throw - price updates are non-critical
}
}
/**
* Log system event
*/
export async function logSystemEvent(
eventType: string,
message: string,
details?: any
) {
const prisma = getPrismaClient()
try {
await prisma.systemEvent.create({
data: {
eventType,
message,
details: details ? JSON.parse(JSON.stringify(details)) : null,
},
})
} catch (error) {
console.error('❌ Failed to log system event:', error)
}
}
/**
* Get trade statistics
*/
export async function getTradeStats(days: number = 30) {
const prisma = getPrismaClient()
const since = new Date()
since.setDate(since.getDate() - days)
const trades = await prisma.trade.findMany({
where: {
createdAt: { gte: since },
status: 'closed',
},
})
const winning = trades.filter((t) => (t.realizedPnL ?? 0) > 0)
const losing = trades.filter((t) => (t.realizedPnL ?? 0) < 0)
const totalPnL = trades.reduce((sum, t) => sum + (t.realizedPnL ?? 0), 0)
const winRate = trades.length > 0 ? (winning.length / trades.length) * 100 : 0
const avgWin = winning.length > 0
? winning.reduce((sum, t) => sum + (t.realizedPnL ?? 0), 0) / winning.length
: 0
const avgLoss = losing.length > 0
? losing.reduce((sum, t) => sum + (t.realizedPnL ?? 0), 0) / losing.length
: 0
return {
totalTrades: trades.length,
winningTrades: winning.length,
losingTrades: losing.length,
winRate: winRate.toFixed(2),
totalPnL: totalPnL.toFixed(2),
avgWin: avgWin.toFixed(2),
avgLoss: avgLoss.toFixed(2),
profitFactor: avgLoss !== 0 ? (avgWin / Math.abs(avgLoss)).toFixed(2) : 'N/A',
}
}
/**
* Disconnect Prisma client (for graceful shutdown)
*/
export async function disconnectPrisma() {
if (prisma) {
await prisma.$disconnect()
prisma = null
console.log('✅ Prisma client disconnected')
}
}