JButton butReqESData = new JButton( "Req ES Data");
butClose.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onReqESData();
}
});
JButton butBuyES = new JButton( "Buy ES");
butClose.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onBuyES();
}
});
JButton butSellES = new JButton( "Sell ES");
butClose.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onSellES();
}
});
buttonPanel.add( new JPanel() );
buttonPanel.add( butReqESData );
buttonPanel.add( butBuyES );
buttonPanel.add( butSellES );
void onReqESData() {
}
void onBuyES() {
}
void onSellES() {
}
JButton butReqESData = new JButton( "Req ES Data");
butReqESData.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onReqESData();
}
});
JButton butBuyES = new JButton( "Buy ES");
butBuyES.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onBuyES();
}
});
JButton butSellES = new JButton( "Sell ES");
butSellES.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
onSellES();
}
});
void onReqESData() {
Contract c = new Contract();
int id = 4;
c.m_symbol = "ES";
c.m_secType = "FUT";
c.m_expiry = "20070315";
c.m_right = "";
c.m_multiplier = "";
c.m_strike = 0.0;
c.m_exchange = "GLOBEX";
c.m_primaryExch = "GLOBEX";
c.m_currency = "USD";
c.m_localSymbol = "ESH7";
c.m_includeExpired = false;
m_client.reqMktData(id, c, "100,101,104,106,162,165,221,225");
}
/*
* Main.java
*
*/
package TestJavaClient;
import java.io.*;
import com.ib.client.Contract;
import com.ib.client.ContractDetails;
import com.ib.client.EClientSocket;
import com.ib.client.EReader;
import com.ib.client.EWrapper;
import com.ib.client.Execution;
import com.ib.client.Order;
import com.ib.client.TickType;
class Wrapper implements EWrapper {
int nextOrderId;
EClientSocket client = new EClientSocket(this);
Wrapper() {
client.eConnect("127.0.0.1", 7496, 0);
if (!client.isConnected()) {
System.out.printf("Failed to connect\n");
System.exit(1);
}
else
;
}
public void error(String s) {
System.out.printf("%s\n", s);
}
public void error(int id, int code, String msg) {
System.out.printf("%s\n", msg);
}
public void error(Exception e) {
System.out.printf("%s\n", e);
}
public void nextValidId(int id) {
System.out.printf("Next order id is %d\n", id);
nextOrderId = id;
}
public void connectionClosed() {
System.out.printf("Connection closed\n");
}
public EReader createReader(EClientSocket socket, DataInputStream dis) {
return new EReader(socket, dis);
}
// to be implemented:
public void tickPrice(int id, int field, double price, int canAutoExecute) {
}
public void tickSize(int id, int field, int size) {
}
public void tickOptionComputation(int id, int field, double impliedVol, double delta, double modelPrice, double pvDividend) {
}
public void orderStatus(int id, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId) {
}
public void openOrder(int id, Contract contract, Order order) {
}
public void updateAccountValue(String key, String value, String currency, String accountName) {
}
public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
}
public void updateAccountTime(String timeStamp) {
}
public void contractDetails(ContractDetails contractDetails) {
}
public void bondContractDetails(ContractDetails contractDetails) {
}
public void execDetails(int id, Contract contract, Execution execution) {
}
public void updateMktDepth(int id, int position, int operation, int side, double price, int size) {
}
public void updateMktDepthL2(int id, int position, String marketMaker, int operation, int side, double price, int size) {
}
public void updateNewsBulletin(int id, int msgType, String message, String origExchange) {
}
public void managedAccounts(String accountsList) {
}
public void receiveFA(int faDataType, String xml) {
}
public void historicalData(int reqId, String date, double open, double high, double low, double close, int volume, int count, double WAP, boolean hasGaps) {
}
public void scannerParameters(String xml) {
}
public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection) {
}
public void tickGeneric(int tickerId, int tickType, double value) {
}
public void tickString(int tickerId, int tickType, String value) {
}
}
public class Main {
public static void main (String args[]) {
Wrapper wrapper = new Wrapper();
try {
for (;;)
Thread.sleep(1000);
} catch (Exception e) { wrapper.error(e); }
}
}
Server Version:31
TWS Time at connection:20070123 16:29:19 MST
Next order id is 4
Market data farm connection is OK:hkfarm
Market data farm connection is OK:usfuture
Market data farm connection is OK:usfarm
HMDS data farm connection is inactive but should be available upon demand.:ushmds2a
HMDS data farm connection is inactive but should be available upon demand.:hkhmds2
Quote from doli:
I have several questions about the last code:
1. Should 'Wrapper' be run as a separate thread? Note the 'sleep' in 'main'. When 'main' sleeps, does 'Wrapper' sleep, too?
class EReader extends Thread
3. In 'Wrapper', what is the difference between instantiating 'client' outside the constructor vs. inside the constructor?
4. Could a server socket be implemented, too? If so, things like market data could be distributed to other apps. Several bots could run at the same time. There is a limit to the number of connections that tws will accept; there may also be a limit to the number of messages that tws and tws' server will process, so it may not be possible to run a 1000 active trader bots at once. Another possible client is a "chart," and as a client to this rather than tws, its subscription to and processing of data wouldn't depend on any particular API.
/*
* Main.java
*
*/
import java.io.*;
import java.net.*;
import java.util.*;
import com.ib.client.Contract;
import com.ib.client.ContractDetails;
import com.ib.client.EClientSocket;
import com.ib.client.EReader;
import com.ib.client.EWrapper;
import com.ib.client.Execution;
import com.ib.client.Order;
import com.ib.client.TickType;
class Subscriber {
Connection client;
Subscriber(Connection c) {
client = c;
}
}
class Connection extends Thread {
Socket sock;
BufferedReader in;
DataOutputStream out;
Connection(Socket s) throws Exception {
try {
sock = s;
in = new BufferedReader(
new InputStreamReader(sock.getInputStream())
);
out = new DataOutputStream(sock.getOutputStream());
}
catch (Exception e) {
System.out.printf("Connection: caught %s\n", e);
System.exit(1);
}
}
class OutOfGas extends Exception {
OutOfGas(String s) {super(s);}
}
public void run() {
String s;
for (;;) {
try {
s = getRequest();
// handle the request:
reply("Not much ...\n");
} catch (Exception e) {
System.out.printf("Connection.run: caught %s\n", e);
// break out of the loop,
// which will then cause a fall off the end of run(),
// which should kill this thread.
break;
}
}
}
String getRequest() throws Exception {
String s = null;
s = in.readLine();
if (s == null)
throw new OutOfGas("whoops!");
else
return s;
}
void reply(String s) throws Exception {
out.writeBytes(s);
}
}
class Distributor extends Thread {
LinkedList <Subscriber> subscriber = new LinkedList<Subscriber>();
public void run() {
try {
ServerSocket ssock = new ServerSocket(6500);
for (;;) {
System.out.printf("Distributor: listening\n");
Socket sock = ssock.accept();
System.out.printf("Distributor: client connected\n");
Connection client = new Connection(sock);
// save each 'client', on a 'Subscriber' list
synchronized(subscriber) {
subscriber.add(new Subscriber(client));
}
client.start();
System.out.printf("no. of threads is %d\n", Thread.activeCount());
}
}
catch (Exception e) {
System.out.printf("Distributor.run: caught %s\n", e);
System.exit(1);
}
}
public void echo(String s) throws Exception { // BUG? throws?
synchronized(subscriber) {
Iterator<Subscriber> sub = subscriber.listIterator();
while (sub.hasNext()) {
try {
sub.next().client.reply(s);
}
catch (Exception e) {
System.out.printf("Distributor.echo: caught %s\n", e);
System.out.printf("no. of threads is %d\n", Thread.activeCount());
sub.remove(); // zombie clients are removed from the list
}
}
}
}
}
class Wrapper implements EWrapper {
int nextOrderId;
Distributor distribute;
EClientSocket client = new EClientSocket(this);
Wrapper(Distributor distributor) {
this.distribute = distributor;
client.eConnect("127.0.0.1", 7496, 0);
if (!client.isConnected()) {
System.out.printf("Failed to connect\n");
System.exit(1);
}
else
;
}
public void error(String s) {
System.out.printf("%s\n", s);
}
public void error(int id, int code, String msg) {
System.out.printf("%s\n", msg);
}
public void error(Exception e) {
System.out.printf("%s\n", e);
}
public EReader createReader(EClientSocket socket, DataInputStream dis) {
return new EReader(socket, dis);
}
public void nextValidId(int id) {
System.out.printf("Next order id is %d\n", id);
nextOrderId = id;
}
public void tickPrice(int id, int field, double price, int canAutoExecute) {
}
public void tickSize(int id, int field, int size) {
}
public void tickOptionComputation(int id, int field, double impliedVol, double delta, double modelPrice, double pvDividend) {
}
public void orderStatus(int id, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId) {
}
public void openOrder(int id, Contract contract, Order order) {
}
public void updateAccountValue(String key, String value, String currency, String accountName) {
}
public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
}
public void updateAccountTime(String timeStamp) {
}
public void contractDetails(ContractDetails contractDetails) {
}
public void bondContractDetails(ContractDetails contractDetails) {
}
public void execDetails(int id, Contract contract, Execution execution) {
}
public void updateMktDepth(int id, int position, int operation, int side, double price, int size) {
}
public void updateMktDepthL2(int id, int position, String marketMaker, int operation, int side, double price, int size) {
}
public void updateNewsBulletin(int id, int msgType, String message, String origExchange) {
}
public void managedAccounts(String accountsList) {
}
public void receiveFA(int faDataType, String xml) {
}
public void historicalData(int id, String date, double open, double high, double low, double close, int volume, int count, double WAP, boolean hasGaps) {
}
public void scannerParameters(String xml) {
}
public void scannerData(int id, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection) {
}
public void tickGeneric(int id, int tickType, double value) {
}
public void tickString(int id, int tickType, String value) {
}
public void connectionClosed() {
System.out.printf("Connection closed\n");
}
}
public class Main {
public static void main (String args[]) {
Distributor distribute = new Distributor();
new Thread(distribute).start();
Wrapper wrapper = new Wrapper(distribute);
try {
for (;;) {
Thread.sleep(10000);
distribute.echo("main is awake\n");
}
} catch (Exception e) { wrapper.error(e); }
}
}