Subversion Repositories Integrator Subversion

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
796 blopes 1
package br.com.kronus.ibkr.robos;
2
 
3
import com.ib.client.*;
4
import java.time.*;
5
import java.time.format.DateTimeFormatter;
6
 
7
public class TesteRealtimeIBKR extends DefaultEWrapper {
8
 
9
    private final EJavaSignal signal = new EJavaSignal();
10
    private final EClientSocket client = new EClientSocket(this, signal);
11
    private EReader reader;
12
    private final int reqId = 1001;
13
 
14
    public static void main(String[] args) {
15
        new TesteRealtimeIBKR().iniciar();
16
    }
17
 
18
    public void iniciar() {
19
 
20
        System.out.println("Conectando ao TWS...");
21
        client.eConnect("127.0.0.1", 7496, 2); // 7496 = live, 7497 = paper
22
 
23
        if (!client.isConnected()) {
24
            System.err.println("Falha ao conectar!");
25
            return;
26
        }      
27
 
28
        // tipo de market data: 1 = realtime (se assinado), 3 = delayed
29
        client.reqMarketDataType(1);
30
 
31
        // Cria o EReader que vai processar as mensagens da IBKR
32
        reader = new EReader(client, signal);
33
        reader.start();
34
 
35
        // Thread que fica processando as mensagens
36
        new Thread(() -> {
37
            while (client.isConnected()) {
38
                try {
39
                    signal.waitForSignal();
40
                    reader.processMsgs();
41
                } catch (Exception e) {
42
                    e.printStackTrace();
43
                }
44
            }
45
        }, "IBKR-Reader-Thread").start();
46
 
47
        try { Thread.sleep(1000); } catch (Exception ignored) {}
48
 
49
        // --------------------------------------
50
        // CONTRATO DO MINI ÍNDICE (ajuste se precisar)
51
        // --------------------------------------
52
        Contract c = new Contract();
53
        c.symbol("PETR4");                          // símbolo na IB
54
        c.secType("FUT");
55
        c.exchange("B3");                         // teste "BMF" ou "BVMF" se der erro 200
56
        c.currency("BRL");
57
        c.lastTradeDateOrContractMonth("202512"); // Z25 = Dez/2025
58
        // --------------------------------------
59
 
60
        System.out.println("Solicitando market data tick-by-tick...");
61
        client.reqTickByTickData(reqId, c, "Last", 0, true);
62
    }
63
 
64
    // ===========================================
65
    // CALLBACK DOS TICKS
66
    // ===========================================
67
    @Override
68
    public void tickByTickAllLast(int reqId, int tickType, long time,
69
                                  double price, Decimal size, TickAttribLast attrib,
70
                                  String exchange, String specialConditions) {
71
 
72
        ZonedDateTime zdt = Instant.ofEpochSecond(time)
73
                .atZone(ZoneId.of("America/Maceio"));
74
 
75
        String hora = zdt.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
76
 
77
        System.out.println(
78
                "[TICK] Preço: " + price +
79
                " | Hora IBKR: " + hora +
80
                " | Epoch IBKR: " + time
81
        );
82
 
83
        long agora = Instant.now().getEpochSecond();
84
        long difSegundos = Math.abs(agora - time);
85
 
86
        if (difSegundos <= 5) {
87
            System.out.println("🔥 DADOS EM TEMPO REAL! (OK)");
88
        } else if (difSegundos >= 800 && difSegundos <= 1000) {
89
            System.out.println("⏳ DADOS ATRASADOS ~15 MIN (DELAYED)");
90
        } else {
91
            System.out.println("⚠️ Diferença de tempo: " + difSegundos + "s");
92
        }
93
    }
94
 
95
    // ===========================================
96
    // ERROS (apenas esse já basta)
97
    // ===========================================
98
    @Override
99
    public void error(int id, long code, int arg2, String arg3, String msg) {
100
        System.err.println("IBKR ERROR: id=" + id + " code=" + arg2 + " msg=" + arg3);
101
    }
102
}