Newer
Older
scalping-bot / src / main / java / com / scalping / bot / api / StateManager.java
package com.scalping.bot.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
public class StateManager {
    private final String dbPath;
    private final ObjectMapper mapper = new ObjectMapper();

    public StateManager(String dbPath) {
        this.dbPath = dbPath;
        new File(dbPath).mkdirs();
    }

    public void saveTradeState(TradeState state) {
        try {
            String filename = dbPath + "/trade_" + state.tradeId + ".json";
            String json = mapper.writeValueAsString(state);
            Files.write(Paths.get(filename), json.getBytes());
            log.info("Trade state saved: {}", state.tradeId);
        } catch (Exception e) {
            log.error("Failed to save trade state", e);
        }
    }

    public TradeState loadTradeState(String tradeId) {
        try {
            String filename = dbPath + "/trade_" + tradeId + ".json";
            String json = Files.readString(Paths.get(filename));
            return mapper.readValue(json, TradeState.class);
        } catch (Exception e) {
            log.error("Failed to load trade state: {}", tradeId, e);
            return null;
        }
    }

    public List<TradeState> recoverAllTrades() {
        List<TradeState> trades = new ArrayList<>();
        try {
            Files.list(Paths.get(dbPath))
                    .filter(p -> p.toString().endsWith(".json"))
                    .forEach(p -> {
                        try {
                            String json = Files.readString(p);
                            trades.add(mapper.readValue(json, TradeState.class));
                        } catch (Exception e) {
                            log.error("Failed to recover trade from {}", p, e);
                        }
                    });
            log.info("Recovered {} trades", trades.size());
        } catch (Exception e) {
            log.error("Recovery failed", e);
        }
        return trades;
    }

    public static class TradeState {
        public String tradeId;
        public String symbol;
        public double entryPrice;
        public double quantity;
        public LocalDateTime entryTime;
        public double stopLoss;
        public double takeProfit;
        public String status; // ACTIVE, CLOSED, WAITING
    }
}