Subversion Repositories Integrator Subversion

Rev

Rev 796 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

package br.com.kronus.ibkr.robos;

import com.ib.client.*;
import java.time.*;
import java.time.format.DateTimeFormatter;

public class TesteRealtimeIBKR extends DefaultEWrapper {

    private final EJavaSignal signal = new EJavaSignal();
    private final EClientSocket client = new EClientSocket(this, signal);
    private EReader reader;
    private final int reqId = 1001;

    public static void main(String[] args) {
        new TesteRealtimeIBKR().iniciar();
    }

    public void iniciar() {

        System.out.println("Conectando ao TWS...");

        // ➜ MESMOS PARAMETROS QUE DERAM isConnected = true
        client.eConnect("127.0.0.1", 7497, 2);

        // espera um pouco pra conexão estabilizar
        try { Thread.sleep(2000); } catch (Exception ignored) {}

        System.out.println("isConnected = " + client.isConnected());
        if (!client.isConnected()) {
            System.err.println("Ainda não conectado ao TWS. Saindo.");
            return;
        }

        // tipo de market data: 1 = realtime (se assinado), 3 = delayed
        client.reqMarketDataType(1);

        // Cria o EReader somente DEPOIS da conexão estar ok
        reader = new EReader(client, signal);
        reader.start();

        // Thread que fica processando as mensagens
        new Thread(() -> {
            while (client.isConnected()) {
                try {
                    signal.waitForSignal();
                    reader.processMsgs();
                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }
        }, "IBKR-Reader-Thread").start();

        // --------- CONTRATO PARA TESTE: AAPL (mais garantido) ----------
        Contract c = new Contract();
        c.symbol("AAPL");
        c.secType("STK");
        c.currency("USD");
        c.exchange("SMART");
//        c.primaryExch("NASDAQ");
       
        // ---------------------------------------------------------------

        System.out.println("Solicitando market data tick-by-tick...");
        client.reqTickByTickData(reqId, c, "Last", 0, true);
    }

    // ===========================================
    // CALLBACK DOS TICKS
    // ===========================================
    @Override
    public void tickByTickAllLast(int reqId, int tickType, long time,
                                  double price, Decimal size, TickAttribLast attrib,
                                  String exchange, String specialConditions) {

        ZonedDateTime zdt = Instant.ofEpochSecond(time)
                .atZone(ZoneId.of("America/Maceio"));

        String hora = zdt.format(DateTimeFormatter.ofPattern("HH:mm:ss"));

        System.out.println(
                "[TICK] Preço: " + price +
                " | Hora IBKR: " + hora +
                " | Epoch IBKR: " + time
        );

        long agora = Instant.now().getEpochSecond();
        long difSegundos = Math.abs(agora - time);

        if (difSegundos <= 5) {
            System.out.println("🔥 DADOS EM TEMPO REAL! (OK)");
        } else if (difSegundos >= 800 && difSegundos <= 1000) {
            System.out.println("⏳ DADOS ATRASADOS ~15 MIN (DELAYED)");
        } else {
            System.out.println("⚠️ Diferença de tempo: " + difSegundos + "s");
        }
    }

    // ===========================================
    // ERROS (apenas esse já basta)
    // ===========================================
    @Override
    public void error(int id, long code, int arg2, String arg3, String msg) {
        System.err.println("IBKR ERROR: id=" + id + " code=" + arg2 + " msg=" + arg3);
    }
}