Subversion Repositories Integrator Subversion

Rev

Rev 761 | Rev 767 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
761 blopes 1
package br.com.sl.core;
2
 
3
import java.io.IOException;
4
import java.io.InputStream;
5
import java.math.BigDecimal;
6
import java.text.SimpleDateFormat;
7
import java.time.LocalDateTime;
8
import java.time.ZoneId;
9
import java.time.format.DateTimeFormatter;
10
import java.util.ArrayList;
11
import java.util.Collections;
12
import java.util.Date;
13
import java.util.List;
14
import java.util.Locale;
15
import java.util.Map;
16
 
17
import org.apache.poi.EncryptedDocumentException;
18
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
19
import org.apache.poi.ss.usermodel.Cell;
20
import org.apache.poi.ss.usermodel.CellType;
21
import org.apache.poi.ss.usermodel.DateUtil;
22
import org.apache.poi.ss.usermodel.Row;
23
import org.apache.poi.ss.usermodel.Sheet;
24
import org.apache.poi.ss.usermodel.Workbook;
25
import org.apache.poi.ss.usermodel.WorkbookFactory;
26
 
27
import br.com.kronus.core.Timeframe;
28
import br.com.sl.domain.dto.robo.ProfitTick;
29
import br.com.sl.domain.model.Candle;
30
import br.com.sl.domain.model.tipos.TipoPeriodo;
31
import br.com.sl.domain.model.tipos.TipoPeriodoCandle;
32
 
33
public class ExcelProfitHistoricoDataProvider implements ProfitDataProvider {
34
 
35
        private final String excelPasta;
36
    private final String sheetName;
37
 
38
        private static final DateTimeFormatter STRING_DATA_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
39
    private static final DateTimeFormatter STRING_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
40
 
41
    public ExcelProfitHistoricoDataProvider(String excelPasta, String sheetName) {
42
        this.excelPasta = excelPasta;
43
        this.sheetName = sheetName;
44
    }
45
 
46
    @Override
47
    public Map<String, ProfitTick> readCurrentTicks() {
48
        // TODO Auto-generated method stub
49
        return null;
50
    }
51
 
52
    /**
53
     * Lê o arquivo Excel dentro do resources.
54
     * Exemplo de uso:
55
     *    lerCandles("/dados/Dados Trade 20251117.xlsx");
56
     * @throws IOException
57
     */
58
    public List<Candle> lerCandles() throws IOException {
59
        List<Candle> candles = new ArrayList<>();
60
 
61
        // Arquivo dentro de src/main/resources
62
        InputStream is = getClass().getResourceAsStream(excelPasta);
63
        if (is == null) {
64
            throw new IOException("Arquivo não encontrado no resources: " + excelPasta);
65
        }
66
 
67
        try (Workbook workbook = WorkbookFactory.create(is)) {
68
            int numberOfSheets = workbook.getNumberOfSheets();
69
 
70
            for (int i = 0; i < numberOfSheets; i++) {
71
                Sheet sheet = workbook.getSheetAt(i);
72
                String sheetName = sheet.getSheetName();
73
                boolean firstRow = true;
74
 
75
                for (Row row : sheet) {
76
                    if (firstRow) {
77
                        firstRow = false; // pula o cabeçalho
78
                        continue;
79
                    }
80
 
81
                    // 0 = Ativo
82
                    // 1 = Dia
83
                    // 2 = Hora
84
                    // 3 = Abertura
85
                    // 4 = Máxima
86
                    // 5 = Mínima
87
                    // 6 = Fechamento
88
                    // 7 = Volume
89
                    // 8 = ...
90
 
91
                    Cell ativoCell      = row.getCell(0);
92
                    Cell diaCell        = row.getCell(1);
93
                    Cell horaCell       = row.getCell(2);
94
                    Cell aberturaCell   = row.getCell(3);
95
                    Cell maximaCell     = row.getCell(4);
96
                    Cell minimaCell     = row.getCell(5);
97
                    Cell fechamentoCell = row.getCell(6);
98
 
99
                    if (!isNumeric(aberturaCell) || !isNumeric(maximaCell)
100
                                || !isNumeric(minimaCell) || !isNumeric(fechamentoCell)) {
101
                        continue;
102
                    }
103
 
104
                    Date data = diaCell.getDateCellValue();
105
                    String dia = new SimpleDateFormat("dd/MM/yyyy").format(data);
106
                    String hora = horaCell.getStringCellValue();
107
                    LocalDateTime time = getLocalDateTime(dia + " " + hora, STRING_DATA_FORMATTER);
108
                    String ativoDescricao = ativoCell.getStringCellValue();
109
                    BigDecimal abertura = BigDecimal.valueOf(aberturaCell.getNumericCellValue());
110
                    BigDecimal topo = BigDecimal.valueOf(maximaCell.getNumericCellValue());
111
                    BigDecimal fundo = BigDecimal.valueOf(minimaCell.getNumericCellValue());
112
                    BigDecimal fechamento = BigDecimal.valueOf(fechamentoCell.getNumericCellValue());
113
 
764 blopes 114
                    Candle candle = new Candle(null, ativoDescricao, time, abertura, topo, fundo, fechamento, TipoPeriodoCandle.M1.getValor());
761 blopes 115
                        candles.add(candle);
116
                }
117
            }
118
        } catch (EncryptedDocumentException e) {
119
                        // TODO Auto-generated catch block
120
                        e.printStackTrace();
121
                } catch (InvalidFormatException e) {
122
                        // TODO Auto-generated catch block
123
                        e.printStackTrace();
124
                }
125
 
126
        return adicionarContadores(inverterLista(candles));
127
    }
128
 
129
    public static List<Candle> inverterLista(List<Candle> candles) {
130
        List<Candle> invertida = new ArrayList<>(candles);
131
        Collections.reverse(invertida);
132
        return invertida;
133
    }
134
 
135
    public static List<Candle> adicionarContadores(List<Candle> candles) {
136
        Integer contador = 1;
137
        List<Candle> comContadores = new ArrayList<>();
138
        for (Candle candle : candles) {
139
                candle.setContadorCandle(contador);
140
                comContadores.add(candle);
141
                contador++;
142
        }
143
        return comContadores;
144
    }
145
 
146
    /*
147
    public List<Candle> lerCandles(String resourcePath, Timeframe selecionarTipoTemporizador) throws IOException {
148
        List<Candle> candles = new ArrayList<>();
149
 
150
        // Arquivo dentro de src/main/resources
151
        InputStream is = getClass().getResourceAsStream(resourcePath);
152
        if (is == null) {
153
            throw new IOException("Arquivo não encontrado no resources: " + resourcePath);
154
        }
155
 
156
        try (Workbook workbook = WorkbookFactory.create(is)) {
157
 
158
            int numberOfSheets = workbook.getNumberOfSheets();
159
 
160
            for (int i = 0; i < numberOfSheets; i++) {
161
 
162
                Sheet sheet = workbook.getSheetAt(i);
163
                String sheetName = sheet.getSheetName();
164
 
165
                Timeframe tipoTemporizador = resolveTipoTemporizador(sheetName);
166
                if (tipoTemporizador == selecionarTipoTemporizador) {
167
                        boolean firstRow = true;
168
 
169
                        for (Row row : sheet) {
170
                            if (firstRow) {
171
                                firstRow = false; // pula o cabeçalho
172
                                continue;
173
                            }
174
 
175
                            // 0 = Data (data+hora)
176
                            // 1 = Abertura
177
                            // 2 = Máxima
178
                            // 3 = Mínima
179
                            // 4 = Fechamento
180
 
181
                            Cell dataCell       = row.getCell(0);
182
                            Cell aberturaCell   = row.getCell(1);
183
                            Cell maximaCell     = row.getCell(2);
184
                            Cell minimaCell     = row.getCell(3);
185
                            Cell fechamentoCell = row.getCell(4);
186
 
187
                            if (!isNumeric(aberturaCell) || !isNumeric(maximaCell)
188
                                    || !isNumeric(minimaCell) || !isNumeric(fechamentoCell)) {
189
                                // linha vazia ou inválida
190
                                continue;
191
                            }
192
 
193
                            LocalDateTime time = getLocalDateTime(dataCell, STRING_DATE_TIME_FORMATTER);
194
                            if (time == null) {
195
                                // se não conseguir converter a data/hora, pode pular ou manter null
196
                                // aqui vou pular para evitar candle "incompleto"
197
                                continue;
198
                            }
199
 
200
                            BigDecimal abertura = BigDecimal.valueOf(aberturaCell.getNumericCellValue());
201
                            BigDecimal topo = BigDecimal.valueOf(maximaCell.getNumericCellValue());
202
                            BigDecimal fundo = BigDecimal.valueOf(minimaCell.getNumericCellValue());
203
                            BigDecimal fechamento = BigDecimal.valueOf(fechamentoCell.getNumericCellValue());
204
 
205
                            Candle candle = new Candle(time, abertura, topo, fundo, fechamento, TipoPeriodoCandle.M1.getValor());
206
                            candles.add(candle);
207
                        }
208
                }
209
            }
210
        } catch (EncryptedDocumentException e) {
211
                        // TODO Auto-generated catch block
212
                        e.printStackTrace();
213
                } catch (InvalidFormatException e) {
214
                        // TODO Auto-generated catch block
215
                        e.printStackTrace();
216
                }
217
 
218
        return candles;
219
    }
220
    */
221
 
222
    /**
223
     * 1 minuto = 1, 5 minutos = 2, 15 minutos = 3, 1 dia = 4
224
     */
225
    private Timeframe resolveTipoTemporizador(String sheetName) {
226
        if (sheetName == null) return null;
227
 
228
        String name = sheetName.toUpperCase(Locale.ROOT);
229
 
230
        if (name.startsWith("1 MIN"))  return Timeframe.M1;
231
        if (name.startsWith("5 MIN"))  return Timeframe.M5;
232
        if (name.startsWith("15 MIN")) return Timeframe.M15;
233
        if (name.startsWith("1 DIA"))  return Timeframe.D1;
234
 
235
        return null;
236
    }
237
 
238
    private boolean isNumeric(Cell cell) {
239
        if (cell == null) return false;
240
 
241
        if (cell.getCellType() == CellType.NUMERIC.getCode()) {
242
            return true;
243
        }
244
 
245
        if (cell.getCellType() == CellType.STRING.getCode()) {
246
            try {
247
                Double.parseDouble(cell.getStringCellValue().replace(",", "."));
248
                return true;
249
            } catch (NumberFormatException e) {
250
                return false;
251
            }
252
        }
253
 
254
        return false;
255
    }
256
 
257
    /**
258
     * Converte a célula de data/hora do Excel para LocalDateTime.
259
     */
260
    private LocalDateTime getLocalDateTime(Cell cell, DateTimeFormatter formatacaoDataTime) {
261
        if (cell == null) {
262
            return null;
263
        }
264
 
265
        // Caso seja data/hora numérica do Excel
266
        if (cell.getCellType() == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
267
            Date date = cell.getDateCellValue(); // disponível em todas as versões
268
            if (date == null) {
269
                return null;
270
            }
271
            return date.toInstant()
272
                       .atZone(ZoneId.systemDefault())
273
                       .toLocalDateTime();
274
        }
275
 
276
        // Caso venha como TEXT (por exemplo num CSV importado)
277
        if (cell.getCellType() == CellType.STRING.getCode()) {
278
            String text = cell.getStringCellValue();
279
            if (text == null || text.trim().isEmpty()) {
280
                return null;
281
            }
282
            text = text.trim();
283
            try {
284
                // Ajuste o pattern se seu Excel estiver em outro formato
285
                return LocalDateTime.parse(text, formatacaoDataTime);
286
            } catch (Exception e) {
287
                return null;
288
            }
289
        }
290
        return null;
291
    }
292
 
293
    /**
294
     * Converte a célula de data/hora do Excel para LocalDateTime.
295
     */
296
    private LocalDateTime getLocalDateTime(String cell, DateTimeFormatter formatacaoDataTime) {
297
        if (cell == null || cell.trim().isEmpty()) {
298
            return null;
299
        }
300
        cell = cell.trim();
301
        try {
302
            return LocalDateTime.parse(cell, formatacaoDataTime);
303
        } catch (Exception e) {
304
            return null;
305
        }
306
    }
307
 
308
}