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
This commit is contained in:
@@ -11,6 +11,7 @@ import { openPosition, placeExitOrders } from '@/lib/drift/orders'
|
||||
import { normalizeTradingViewSymbol } from '@/config/trading'
|
||||
import { getMergedConfig } from '@/config/trading'
|
||||
import { getPositionManager, ActiveTrade } from '@/lib/trading/position-manager'
|
||||
import { createTrade } from '@/lib/database/trades'
|
||||
|
||||
export interface ExecuteTradeRequest {
|
||||
symbol: string // TradingView symbol (e.g., 'SOLUSDT')
|
||||
@@ -135,6 +136,26 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
|
||||
body.direction
|
||||
)
|
||||
|
||||
// Calculate dual stop prices if enabled
|
||||
let softStopPrice: number | undefined
|
||||
let hardStopPrice: number | undefined
|
||||
|
||||
if (config.useDualStops) {
|
||||
softStopPrice = calculatePrice(
|
||||
entryPrice,
|
||||
config.softStopPercent,
|
||||
body.direction
|
||||
)
|
||||
hardStopPrice = calculatePrice(
|
||||
entryPrice,
|
||||
config.hardStopPercent,
|
||||
body.direction
|
||||
)
|
||||
console.log('🛡️🛡️ Dual stop system enabled:')
|
||||
console.log(` Soft stop: $${softStopPrice.toFixed(4)} (${config.softStopPercent}%)`)
|
||||
console.log(` Hard stop: $${hardStopPrice.toFixed(4)} (${config.hardStopPercent}%)`)
|
||||
}
|
||||
|
||||
const tp1Price = calculatePrice(
|
||||
entryPrice,
|
||||
config.takeProfit1Percent,
|
||||
@@ -211,6 +232,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
|
||||
}
|
||||
|
||||
// Place on-chain TP/SL orders so they appear in Drift UI (reduce-only LIMIT orders)
|
||||
let exitOrderSignatures: string[] = []
|
||||
try {
|
||||
const exitRes = await placeExitOrders({
|
||||
symbol: driftSymbol,
|
||||
@@ -221,12 +243,18 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
|
||||
tp1SizePercent: config.takeProfit1SizePercent || 50,
|
||||
tp2SizePercent: config.takeProfit2SizePercent || 100,
|
||||
direction: body.direction,
|
||||
// Dual stop parameters
|
||||
useDualStops: config.useDualStops,
|
||||
softStopPrice: softStopPrice,
|
||||
softStopBuffer: config.softStopBuffer,
|
||||
hardStopPrice: hardStopPrice,
|
||||
})
|
||||
|
||||
if (!exitRes.success) {
|
||||
console.error('❌ Failed to place on-chain exit orders:', exitRes.error)
|
||||
} else {
|
||||
console.log('📨 Exit orders placed on-chain:', exitRes.signatures)
|
||||
exitOrderSignatures = exitRes.signatures || []
|
||||
}
|
||||
|
||||
// Attach signatures to response when available
|
||||
@@ -237,7 +265,38 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
|
||||
console.error('❌ Unexpected error placing exit orders:', err)
|
||||
}
|
||||
|
||||
// TODO: Save trade to database (add Prisma integration later)
|
||||
// Save trade to database
|
||||
try {
|
||||
await createTrade({
|
||||
positionId: openResult.transactionSignature!,
|
||||
symbol: driftSymbol,
|
||||
direction: body.direction,
|
||||
entryPrice,
|
||||
positionSizeUSD: positionSizeUSD,
|
||||
leverage: config.leverage,
|
||||
stopLossPrice,
|
||||
takeProfit1Price: tp1Price,
|
||||
takeProfit2Price: tp2Price,
|
||||
tp1SizePercent: config.takeProfit1SizePercent || 50,
|
||||
tp2SizePercent: config.takeProfit2SizePercent || 100,
|
||||
configSnapshot: config,
|
||||
entryOrderTx: openResult.transactionSignature!,
|
||||
tp1OrderTx: exitOrderSignatures[0],
|
||||
tp2OrderTx: exitOrderSignatures[1],
|
||||
slOrderTx: config.useDualStops ? undefined : exitOrderSignatures[2],
|
||||
softStopOrderTx: config.useDualStops ? exitOrderSignatures[2] : undefined,
|
||||
hardStopOrderTx: config.useDualStops ? exitOrderSignatures[3] : undefined,
|
||||
softStopPrice,
|
||||
hardStopPrice,
|
||||
signalStrength: body.signalStrength,
|
||||
timeframe: body.timeframe,
|
||||
})
|
||||
|
||||
console.log('💾 Trade saved to database')
|
||||
} catch (dbError) {
|
||||
console.error('❌ Failed to save trade to database:', dbError)
|
||||
// Don't fail the trade if database save fails
|
||||
}
|
||||
|
||||
console.log('✅ Trade executed successfully!')
|
||||
|
||||
|
||||
Reference in New Issue
Block a user