package br.com.kronus.ibkr.history;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import com.ib.client.Contract;
import br.com.kronus.ibkr.api.IbkrClient;
public class IbkrRealtimeBarsService
{
private final IbkrClient ibkr
;
private final ZoneId zoneId
;
private static final DateTimeFormatter DATA =
DateTimeFormatter.
ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter HORA =
DateTimeFormatter.
ofPattern("HH:mm:ss");
public IbkrRealtimeBarsService
(IbkrClient ibkr, ZoneId zoneId
) {
this.
ibkr = ibkr
;
this.
zoneId = zoneId
;
}
/**
* Inicia o stream de realtime bars (5s) e grava em CSV.
* CabeƧalho: data;hora;open;high;low;close;volume;wap;count
*/
public int iniciarStreamCsv
(int reqId, Contract contract, Path arquivoCsv
) throws IOException {
if (!Files.
exists(arquivoCsv.
getParent())) {
Files.
createDirectories(arquivoCsv.
getParent());
}
boolean novo = Files.
notExists(arquivoCsv
);
BufferedWriter writer = Files.
newBufferedWriter(arquivoCsv,
java.
nio.
file.
StandardOpenOption.
CREATE,
java.
nio.
file.
StandardOpenOption.
APPEND);
if (novo
) {
writer.
write("data;hora;open;high;low;close;volume;wap;count");
writer.
newLine();
writer.
flush();
}
ibkr.
registrarRealtimeBarListener(reqId,
(id, time, open, high, low, close, volume, wap, count
) -
> {
try {
Instant inst = Instant.
ofEpochMilli(time
);
String dataStr = DATA.
format(inst.
atZone(zoneId
));
String horaStr = HORA.
format(inst.
atZone(zoneId
));
String linha =
String.
join(";",
dataStr,
horaStr,
String.
valueOf(open
),
String.
valueOf(high
),
String.
valueOf(low
),
String.
valueOf(close
),
String.
valueOf(volume
),
String.
valueOf(wap
),
String.
valueOf(count
)
);
writer.
write(linha
);
writer.
newLine();
writer.
flush();
} catch (IOException e
) {
e.
printStackTrace();
}
});
ibkr.
getClient().
reqRealTimeBars(
reqId,
contract,
5,
"TRADES",
true,
null
);
return reqId
;
}
public static LocalDateTime converterIbkrTime
(long timeMillis
) {
return Instant.
ofEpochMilli(timeMillis
)
.
atZone(ZoneId.
of("America/Sao_Paulo"))
.
toLocalDateTime();
}
}