Subversion Repositories Integrator Subversion

Rev

Rev 796 | Details | Compare with Previous | 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
 
797 blopes 22
        // ➜ MESMOS PARAMETROS QUE DERAM isConnected = true
23
        client.eConnect("127.0.0.1", 7497, 2);
24
 
25
        // espera um pouco pra conexão estabilizar
26
        try { Thread.sleep(2000); } catch (Exception ignored) {}
27
 
28
        System.out.println("isConnected = " + client.isConnected());
796 blopes 29
        if (!client.isConnected()) {
797 blopes 30
            System.err.println("Ainda não conectado ao TWS. Saindo.");
796 blopes 31
            return;
797 blopes 32
        }
796 blopes 33
 
34
        // tipo de market data: 1 = realtime (se assinado), 3 = delayed
35
        client.reqMarketDataType(1);
36
 
797 blopes 37
        // Cria o EReader somente DEPOIS da conexão estar ok
796 blopes 38
        reader = new EReader(client, signal);
39
        reader.start();
40
 
41
        // Thread que fica processando as mensagens
42
        new Thread(() -> {
43
            while (client.isConnected()) {
44
                try {
45
                    signal.waitForSignal();
46
                    reader.processMsgs();
47
                } catch (Exception e) {
48
                    e.printStackTrace();
797 blopes 49
                    break;
796 blopes 50
                }
51
            }
52
        }, "IBKR-Reader-Thread").start();
53
 
797 blopes 54
        // --------- CONTRATO PARA TESTE: AAPL (mais garantido) ----------
796 blopes 55
        Contract c = new Contract();
797 blopes 56
        c.symbol("AAPL");
57
        c.secType("STK");
58
        c.currency("USD");
59
        c.exchange("SMART");
60
//        c.primaryExch("NASDAQ");
61
 
62
        // ---------------------------------------------------------------
796 blopes 63
 
64
        System.out.println("Solicitando market data tick-by-tick...");
65
        client.reqTickByTickData(reqId, c, "Last", 0, true);
66
    }
67
 
68
    // ===========================================
69
    // CALLBACK DOS TICKS
70
    // ===========================================
71
    @Override
72
    public void tickByTickAllLast(int reqId, int tickType, long time,
73
                                  double price, Decimal size, TickAttribLast attrib,
74
                                  String exchange, String specialConditions) {
75
 
76
        ZonedDateTime zdt = Instant.ofEpochSecond(time)
77
                .atZone(ZoneId.of("America/Maceio"));
78
 
79
        String hora = zdt.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
80
 
81
        System.out.println(
82
                "[TICK] Preço: " + price +
83
                " | Hora IBKR: " + hora +
84
                " | Epoch IBKR: " + time
85
        );
86
 
87
        long agora = Instant.now().getEpochSecond();
88
        long difSegundos = Math.abs(agora - time);
89
 
90
        if (difSegundos <= 5) {
91
            System.out.println("🔥 DADOS EM TEMPO REAL! (OK)");
92
        } else if (difSegundos >= 800 && difSegundos <= 1000) {
93
            System.out.println("⏳ DADOS ATRASADOS ~15 MIN (DELAYED)");
94
        } else {
95
            System.out.println("⚠️ Diferença de tempo: " + difSegundos + "s");
96
        }
97
    }
98
 
99
    // ===========================================
100
    // ERROS (apenas esse já basta)
101
    // ===========================================
102
    @Override
103
    public void error(int id, long code, int arg2, String arg3, String msg) {
104
        System.err.println("IBKR ERROR: id=" + id + " code=" + arg2 + " msg=" + arg3);
105
    }
106
}