Files
trading_bot_v3/app/api/drift/cancel-all-orders/route.js
mindesbunister 236e2b0d31 feat: Complete AI Learning Integration & Position Scaling DCA System
- Integrated SimplifiedStopLossLearner into automation
- Every AI decision now recorded for learning (stop loss, take profit, confidence)
- Trade outcomes tracked and compared to AI predictions
- Learning patterns improve future AI decisions
- Enhanced status dashboard with learning insights

- Proper DCA: increase position size + adjust existing SL/TP (not create new)
- AI-calculated optimal levels for scaled positions
- Prevents order fragmentation (fixes 24+ order problem)
- Unified risk management for entire scaled position

 TIMEFRAME-AWARE INTERVALS:
- Scalping (5m/15m): 5-15 minute analysis intervals
- Day Trading (1h/4h): 10-30 minute intervals
- Swing Trading (4h/1d): 23-68 minute intervals
- Perfect for 5-minute scalping with DCA protection

- 2-hour DCA cooldown prevents order spam
- Position existence checks before new trades
- Direction matching validation
- Learning-based decision improvements

- AI calculates ALL levels (entry, SL, TP, leverage, scaling)
- Every calculation recorded and learned from
- Position scaling uses AI intelligence
- Timeframe-appropriate analysis frequency
- Professional order management
- Continuous learning and improvement

 ADDRESSES ALL USER CONCERNS:
- 5-minute scalping compatibility 
- Position scaling DCA (adjust existing SL/TP) 
- AI calculations being learned from 
- No order fragmentation 
- Intelligent automation with learning 

Files: automation, consolidation APIs, learning integration, tests, documentation
2025-07-27 23:46:52 +02:00

116 lines
3.4 KiB
JavaScript

import { NextResponse } from 'next/server';
export async function POST(request) {
try {
console.log('🧹 CANCELING ALL ORDERS');
// Import Drift SDK
const { DriftClient, initialize, Wallet } = await import('@drift-labs/sdk');
const { Connection, Keypair } = await import('@solana/web3.js');
// Setup connection and wallet
const rpcEndpoint = process.env.SOLANA_RPC_URL || 'https://mainnet.helius-rpc.com/?api-key=5e236449-f936-4af7-ae38-f15e2f1a3757';
const connection = new Connection(rpcEndpoint, 'confirmed');
if (!process.env.SOLANA_PRIVATE_KEY) {
return NextResponse.json({
success: false,
error: 'SOLANA_PRIVATE_KEY not configured'
}, { status: 400 });
}
const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY);
const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray));
const wallet = new Wallet(keypair);
// Initialize Drift client
const env = 'mainnet-beta';
const sdkConfig = initialize({ env });
const driftClient = new DriftClient({
connection,
wallet,
programID: sdkConfig.DRIFT_PROGRAM_ID,
accountSubscription: {
type: 'polling',
accountLoader: {
commitment: 'confirmed'
}
}
});
await driftClient.subscribe();
// Get all open orders
const user = driftClient.getUser();
const orders = user.getOpenOrders();
console.log(`📋 Found ${orders.length} open orders to cancel`);
const cancelResults = [];
let successCount = 0;
let failCount = 0;
// Cancel orders in batches to avoid rate limits
const batchSize = 5;
for (let i = 0; i < orders.length; i += batchSize) {
const batch = orders.slice(i, i + batchSize);
const batchPromises = batch.map(async (order) => {
try {
console.log(`🚫 Canceling order ${order.orderId}...`);
const txSig = await driftClient.cancelOrder(order.orderId);
console.log(` ✅ Order ${order.orderId} canceled: ${txSig}`);
successCount++;
return {
orderId: order.orderId,
success: true,
txSig: txSig
};
} catch (error) {
console.log(` ❌ Failed to cancel order ${order.orderId}: ${error.message}`);
failCount++;
return {
orderId: order.orderId,
success: false,
error: error.message
};
}
});
const batchResults = await Promise.allSettled(batchPromises);
cancelResults.push(...batchResults.map(r => r.value || r.reason));
// Small delay between batches
if (i + batchSize < orders.length) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
await driftClient.unsubscribe();
console.log(`✅ Order cancellation complete: ${successCount} success, ${failCount} failed`);
return NextResponse.json({
success: true,
message: `Canceled ${successCount} orders`,
totalOrders: orders.length,
totalCanceled: successCount,
totalFailed: failCount,
results: cancelResults
});
} catch (error) {
console.error('❌ Cancel all orders error:', error);
return NextResponse.json({
success: false,
error: 'Failed to cancel orders',
details: error.message
}, { status: 500 });
}
}