|
|
@@ -206,6 +206,65 @@ class CandleController {
|
|
206
|
206
|
next(error);
|
|
207
|
207
|
}
|
|
208
|
208
|
}
|
|
|
209
|
+
|
|
|
210
|
+ // Clean up old candles, keep latest N candles
|
|
|
211
|
+ async cleanupCandles(req, res, next) {
|
|
|
212
|
+ try {
|
|
|
213
|
+ const { symbolId } = req.params;
|
|
|
214
|
+ const { keep = 1000 } = req.query;
|
|
|
215
|
+
|
|
|
216
|
+ // Verify symbol exists
|
|
|
217
|
+ const symbol = await Symbol.findByPk(symbolId);
|
|
|
218
|
+ if (!symbol) {
|
|
|
219
|
+ const error = new Error('Symbol not found');
|
|
|
220
|
+ error.statusCode = 404;
|
|
|
221
|
+ return next(error);
|
|
|
222
|
+ }
|
|
|
223
|
+
|
|
|
224
|
+ // Get total count of candles for this symbol
|
|
|
225
|
+ const totalCandles = await Candle1h.count({
|
|
|
226
|
+ where: { symbolId: parseInt(symbolId) }
|
|
|
227
|
+ });
|
|
|
228
|
+
|
|
|
229
|
+ if (totalCandles <= keep) {
|
|
|
230
|
+ return res.json({
|
|
|
231
|
+ success: true,
|
|
|
232
|
+ message: `No cleanup needed. Only ${totalCandles} candles exist (keep: ${keep})`,
|
|
|
233
|
+ deletedCount: 0
|
|
|
234
|
+ });
|
|
|
235
|
+ }
|
|
|
236
|
+
|
|
|
237
|
+ // Get the IDs of candles to keep (latest N candles)
|
|
|
238
|
+ const candlesToKeep = await Candle1h.findAll({
|
|
|
239
|
+ where: { symbolId: parseInt(symbolId) },
|
|
|
240
|
+ order: [['openTime', 'DESC']],
|
|
|
241
|
+ limit: parseInt(keep),
|
|
|
242
|
+ attributes: ['id']
|
|
|
243
|
+ });
|
|
|
244
|
+
|
|
|
245
|
+ const keepIds = candlesToKeep.map(candle => candle.id);
|
|
|
246
|
+
|
|
|
247
|
+ // Delete older candles (those not in keepIds)
|
|
|
248
|
+ const deletedCount = await Candle1h.destroy({
|
|
|
249
|
+ where: {
|
|
|
250
|
+ symbolId: parseInt(symbolId),
|
|
|
251
|
+ id: {
|
|
|
252
|
+ [Op.notIn]: keepIds
|
|
|
253
|
+ }
|
|
|
254
|
+ }
|
|
|
255
|
+ });
|
|
|
256
|
+
|
|
|
257
|
+ res.json({
|
|
|
258
|
+ success: true,
|
|
|
259
|
+ message: `Cleanup completed. Deleted ${deletedCount} old candles, kept ${keepIds.length} latest candles`,
|
|
|
260
|
+ deletedCount,
|
|
|
261
|
+ keptCount: keepIds.length,
|
|
|
262
|
+ symbol: symbol.symbol
|
|
|
263
|
+ });
|
|
|
264
|
+ } catch (error) {
|
|
|
265
|
+ next(error);
|
|
|
266
|
+ }
|
|
|
267
|
+ }
|
|
209
|
268
|
}
|
|
210
|
269
|
|
|
211
|
270
|
module.exports = new CandleController();
|