Files
trading_bot_v4/app/api/trading/close/route.ts
mindesbunister 2405bff68a feat: Complete Trading Bot v4 with Drift Protocol integration
Features:
- Autonomous trading system with Drift Protocol on Solana
- Real-time position monitoring with Pyth price feeds
- Dynamic stop-loss and take-profit management
- n8n workflow integration for TradingView signals
- Beautiful web UI for settings management
- REST API for trade execution and monitoring

- Next.js 15 with standalone output mode
- TypeScript with strict typing
- Docker containerization with multi-stage builds
- PostgreSQL database for trade history
- Singleton pattern for Drift client connection pooling
- BN.js for BigNumber handling (Drift SDK requirement)

- Configurable stop-loss and take-profit levels
- Breakeven trigger and profit locking
- Daily loss limits and trade cooldowns
- Slippage tolerance controls
- DRY_RUN mode for safe testing

- Real-time risk calculator
- Interactive sliders for all parameters
- Live preview of trade outcomes
- Position sizing and leverage controls
- Beautiful gradient design with Tailwind CSS

- POST /api/trading/execute - Execute trades
- POST /api/trading/close - Close positions
- GET /api/trading/positions - Monitor active trades
- GET /api/trading/check-risk - Validate trade signals
- GET /api/settings - View configuration
- POST /api/settings - Update configuration

- Fixed Borsh serialization errors (simplified order params)
- Resolved RPC rate limiting with singleton pattern
- Fixed BigInt vs BN type mismatches
- Corrected order execution flow
- Improved position state management

- Complete setup guides
- Docker deployment instructions
- n8n workflow configuration
- API reference documentation
- Risk management guidelines

- Runs on port 3001 (external), 3000 (internal)
- Uses Helius RPC for optimal performance
- Production-ready with error handling
- Health monitoring and logging
2025-10-24 14:24:36 +02:00

94 lines
2.4 KiB
TypeScript

/**
* Close Position API Endpoint
*
* Closes an existing position (partially or fully)
*/
import { NextRequest, NextResponse } from 'next/server'
import { closePosition } from '@/lib/drift/orders'
import { initializeDriftService } from '@/lib/drift/client'
export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'
interface CloseRequest {
symbol: string // e.g., 'SOL-PERP'
percentToClose?: number // 0-100, default 100 (close entire position)
}
export async function POST(request: NextRequest) {
try {
// Verify authorization
const authHeader = request.headers.get('authorization')
const expectedAuth = `Bearer ${process.env.API_SECRET_KEY}`
if (!authHeader || authHeader !== expectedAuth) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
)
}
const body: CloseRequest = await request.json()
const { symbol, percentToClose = 100 } = body
if (!symbol) {
return NextResponse.json(
{ success: false, error: 'Missing symbol' },
{ status: 400 }
)
}
if (percentToClose < 0 || percentToClose > 100) {
return NextResponse.json(
{ success: false, error: 'percentToClose must be between 0 and 100' },
{ status: 400 }
)
}
console.log(`📊 Closing position: ${symbol} (${percentToClose}%)`)
// Initialize Drift service if not already initialized
await initializeDriftService()
// Close position
const result = await closePosition({
symbol,
percentToClose,
slippageTolerance: 1.0,
})
if (!result.success) {
return NextResponse.json(
{
success: false,
error: 'Position close failed',
message: result.error,
},
{ status: 500 }
)
}
return NextResponse.json({
success: true,
transactionSignature: result.transactionSignature,
symbol,
closePrice: result.closePrice,
closedSize: result.closedSize,
realizedPnL: result.realizedPnL,
percentClosed: percentToClose,
})
} catch (error) {
console.error('❌ Close position error:', error)
return NextResponse.json(
{
success: false,
error: 'Internal server error',
message: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
)
}
}