Subversion Repositories Integrator Subversion

Rev

Blame | Last modification | View Log | Download | RSS feed

package br.com.robo.sim;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import br.com.ec.core.util.VerificadorUtil;
import br.com.kronus.core.Candle;
import br.com.kronus.core.Timeframe;

public class CandleExcelReader {

    private static final DateTimeFormatter STRING_DATA_FORMATTER =
            DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
   
    private static final DateTimeFormatter STRING_DATE_TIME_FORMATTER =
            DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    /**
     * Lê o arquivo Excel dentro do resources.
     * Exemplo de uso:
     *    lerCandles("/dados/Dados Trade 20251117.xlsx");
     */

    public List<Candle> lerCandles(String resourcePath) throws IOException {
        List<Candle> candles = new ArrayList<>();

        // Arquivo dentro de src/main/resources
        InputStream is = getClass().getResourceAsStream(resourcePath);
        if (is == null) {
            throw new IOException("Arquivo não encontrado no resources: " + resourcePath);
        }

        try (Workbook workbook = WorkbookFactory.create(is)) {
            int numberOfSheets = workbook.getNumberOfSheets();

            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();
                boolean firstRow = true;

                for (Row row : sheet) {
                    if (firstRow) {
                        firstRow = false; // pula o cabeçalho
                        continue;
                    }

                    // 0 = Ativo
                    // 1 = Dia
                    // 2 = Hora
                    // 3 = Abertura
                    // 4 = Máxima
                    // 5 = Mínima
                    // 6 = Fechamento
                    // 7 = Volume
                    // 8 = ...

                    Cell ativoCell      = row.getCell(0);
                    Cell diaCell        = row.getCell(1);
                    Cell horaCell       = row.getCell(2);
                    Cell aberturaCell   = row.getCell(3);
                    Cell maximaCell     = row.getCell(4);
                    Cell minimaCell     = row.getCell(5);
                    Cell fechamentoCell = row.getCell(6);

                    if (!isNumeric(aberturaCell) || !isNumeric(maximaCell)
                                || !isNumeric(minimaCell) || !isNumeric(fechamentoCell)) {
                        continue;
                    }
                   
                    Date data = diaCell.getDateCellValue();
                    String dia = new SimpleDateFormat("dd/MM/yyyy").format(data);
                    String hora = horaCell.getStringCellValue();
//                    String hora = Double.toString(horaCell.getNumericCellValue());

//                    Date dataHora = horaCell.getDateCellValue();
//                    String hora = new SimpleDateFormat("hh:MM:ss").format(dataHora);
//                    String hora = String.valueOf(horaCell.getNumericCellValue());
                   
                    LocalDateTime time = getLocalDateTime(dia + " " + hora, STRING_DATA_FORMATTER);

                    double abertura   = aberturaCell.getNumericCellValue();
                    double topo       = maximaCell.getNumericCellValue();
                    double fundo      = minimaCell.getNumericCellValue();
                    double fechamento = fechamentoCell.getNumericCellValue();

                    Candle candle = new Candle(time, abertura, topo, fundo, fechamento, Timeframe.M1);
                        candles.add(candle);
                }
            }
        } catch (EncryptedDocumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (InvalidFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

        return adicionarContadores(inverterLista(candles));
    }
   
    public static List<Candle> inverterLista(List<Candle> candles) {
        List<Candle> invertida = new ArrayList<>(candles);
        Collections.reverse(invertida);
        return invertida;
    }

    public static List<Candle> adicionarContadores(List<Candle> candles) {
        Integer contador = 1;
        List<Candle> comContadores = new ArrayList<>();
        for (Candle candle : candles) {
                candle.setContador(contador);
                comContadores.add(candle);
                contador++;
        }
        return comContadores;
    }
   
    public List<Candle> lerCandles(String resourcePath, Timeframe selecionarTipoTemporizador) throws IOException {
        List<Candle> candles = new ArrayList<>();

        // Arquivo dentro de src/main/resources
        InputStream is = getClass().getResourceAsStream(resourcePath);
        if (is == null) {
            throw new IOException("Arquivo não encontrado no resources: " + resourcePath);
        }

        try (Workbook workbook = WorkbookFactory.create(is)) {

            int numberOfSheets = workbook.getNumberOfSheets();

            for (int i = 0; i < numberOfSheets; i++) {

                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();

                Timeframe tipoTemporizador = resolveTipoTemporizador(sheetName);
                if (tipoTemporizador == selecionarTipoTemporizador) {
                        boolean firstRow = true;
       
                        for (Row row : sheet) {
                            if (firstRow) {
                                firstRow = false; // pula o cabeçalho
                                continue;
                            }
       
                            // 0 = Data (data+hora)
                            // 1 = Abertura
                            // 2 = Máxima
                            // 3 = Mínima
                            // 4 = Fechamento
       
                            Cell dataCell       = row.getCell(0);
                            Cell aberturaCell   = row.getCell(1);
                            Cell maximaCell     = row.getCell(2);
                            Cell minimaCell     = row.getCell(3);
                            Cell fechamentoCell = row.getCell(4);
       
                            if (!isNumeric(aberturaCell) || !isNumeric(maximaCell)
                                    || !isNumeric(minimaCell) || !isNumeric(fechamentoCell)) {
                                // linha vazia ou inválida
                                continue;
                            }
       
                            LocalDateTime time = getLocalDateTime(dataCell, STRING_DATE_TIME_FORMATTER);
                            if (time == null) {
                                // se não conseguir converter a data/hora, pode pular ou manter null
                                // aqui vou pular para evitar candle "incompleto"
                                continue;
                            }
       
                            double abertura   = aberturaCell.getNumericCellValue();
                            double topo       = maximaCell.getNumericCellValue();
                            double fundo      = minimaCell.getNumericCellValue();
                            double fechamento = fechamentoCell.getNumericCellValue();
       
                            Candle candle = new Candle(time, abertura, topo, fundo, fechamento, tipoTemporizador);
                            candles.add(candle);
                        }
                }
            }
        } catch (EncryptedDocumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (InvalidFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

        return candles;
    }

    /**
     * 1 minuto = 1, 5 minutos = 2, 15 minutos = 3, 1 dia = 4
     */

    private Timeframe resolveTipoTemporizador(String sheetName) {
        if (sheetName == null) return null;

        String name = sheetName.toUpperCase(Locale.ROOT);

        if (name.startsWith("1 MIN"))  return Timeframe.M1;
        if (name.startsWith("5 MIN"))  return Timeframe.M5;
        if (name.startsWith("15 MIN")) return Timeframe.M15;
        if (name.startsWith("1 DIA"))  return Timeframe.D1;

        return null;
    }

    private boolean isNumeric(Cell cell) {
        if (cell == null) return false;

        if (cell.getCellType() == CellType.NUMERIC.getCode()) {
            return true;
        }

        if (cell.getCellType() == CellType.STRING.getCode()) {
            try {
                Double.parseDouble(cell.getStringCellValue().replace(",", "."));
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }

        return false;
    }

    /**
     * Converte a célula de data/hora do Excel para LocalDateTime.
     */

    private LocalDateTime getLocalDateTime(Cell cell, DateTimeFormatter formatacaoDataTime) {
        if (cell == null) {
            return null;
        }

        // Caso seja data/hora numérica do Excel
        if (cell.getCellType() == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
            Date date = cell.getDateCellValue(); // disponível em todas as versões
            if (date == null) {
                return null;
            }
            return date.toInstant()
                       .atZone(ZoneId.systemDefault())
                       .toLocalDateTime();
        }

        // Caso venha como TEXT (por exemplo num CSV importado)
        if (cell.getCellType() == CellType.STRING.getCode()) {
            String text = cell.getStringCellValue();
            if (text == null || text.trim().isEmpty()) {
                return null;
            }
            text = text.trim();
            try {
                // Ajuste o pattern se seu Excel estiver em outro formato
                return LocalDateTime.parse(text, formatacaoDataTime);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
   
    /**
     * Converte a célula de data/hora do Excel para LocalDateTime.
     */

    private LocalDateTime getLocalDateTime(String cell, DateTimeFormatter formatacaoDataTime) {
        if (cell == null || cell.trim().isEmpty()) {
            return null;
        }
        cell = cell.trim();
        try {
            return LocalDateTime.parse(cell, formatacaoDataTime);
        } catch (Exception e) {
            return null;
        }
    }
   
}