|
|
@@ -206,6 +206,65 @@ class CandleController {
|
|
|
next(error);
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ // Clean up old candles, keep latest N candles
|
|
|
+ async cleanupCandles(req, res, next) {
|
|
|
+ try {
|
|
|
+ const { symbolId } = req.params;
|
|
|
+ const { keep = 1000 } = req.query;
|
|
|
+
|
|
|
+ // Verify symbol exists
|
|
|
+ const symbol = await Symbol.findByPk(symbolId);
|
|
|
+ if (!symbol) {
|
|
|
+ const error = new Error('Symbol not found');
|
|
|
+ error.statusCode = 404;
|
|
|
+ return next(error);
|
|
|
+ }
|
|
|
+
|
|
|
+ // Get total count of candles for this symbol
|
|
|
+ const totalCandles = await Candle1h.count({
|
|
|
+ where: { symbolId: parseInt(symbolId) }
|
|
|
+ });
|
|
|
+
|
|
|
+ if (totalCandles <= keep) {
|
|
|
+ return res.json({
|
|
|
+ success: true,
|
|
|
+ message: `No cleanup needed. Only ${totalCandles} candles exist (keep: ${keep})`,
|
|
|
+ deletedCount: 0
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ // Get the IDs of candles to keep (latest N candles)
|
|
|
+ const candlesToKeep = await Candle1h.findAll({
|
|
|
+ where: { symbolId: parseInt(symbolId) },
|
|
|
+ order: [['openTime', 'DESC']],
|
|
|
+ limit: parseInt(keep),
|
|
|
+ attributes: ['id']
|
|
|
+ });
|
|
|
+
|
|
|
+ const keepIds = candlesToKeep.map(candle => candle.id);
|
|
|
+
|
|
|
+ // Delete older candles (those not in keepIds)
|
|
|
+ const deletedCount = await Candle1h.destroy({
|
|
|
+ where: {
|
|
|
+ symbolId: parseInt(symbolId),
|
|
|
+ id: {
|
|
|
+ [Op.notIn]: keepIds
|
|
|
+ }
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ res.json({
|
|
|
+ success: true,
|
|
|
+ message: `Cleanup completed. Deleted ${deletedCount} old candles, kept ${keepIds.length} latest candles`,
|
|
|
+ deletedCount,
|
|
|
+ keptCount: keepIds.length,
|
|
|
+ symbol: symbol.symbol
|
|
|
+ });
|
|
|
+ } catch (error) {
|
|
|
+ next(error);
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
module.exports = new CandleController();
|