我正在对算法交易和 IB API 进行一些自学和实验。我决定使用 Java,但我愿意切换到 C++。我浏览了一个在线教程,该教程将引导您完成下面显示的代码,但想知道是否将其扩展到一只股票之外。我想查看所有 SP500 股票并检查代码数据以据此做出决策。
下面的代码将为 Microsoft 创建合同并获取数据,但我想获取所有 500 只股票的数据。为了便于阅读,EWrapper 接口中定义的所有其他方法都被排除在帖子之外。
我在想我需要将股票代码存储在一个文件中,解析它,然后将每个合约一个一个地添加到一个向量中。但是,我不确定之后如何监控数据。如果我可以按顺序循环遍历每个代码并发出数据请求,那就太好了,但我相信流是在异步线程上处理的(如果错了,请纠正我。)
那么我如何浏览所有 500 只股票并检查它们的代码数据呢?
代码片段和解释将不胜感激。谢谢!
// Import Java utilities and Interactive Brokers API
import java.util.Vector;
import com.ib.client.Contract;
import com.ib.client.ContractDetails;
import com.ib.client.EClientSocket;
import com.ib.client.EWrapper;
import com.ib.client.Execution;
import com.ib.client.Order;
import com.ib.client.OrderState;
import com.ib.client.TagValue;
import com.ib.client.CommissionReport;
import com.ib.client.UnderComp;
// RealTimeBars Class is an implementation of the
// IB API EWrapper class
public class RealTimeBars implements EWrapper
{
// Keep track of the next ID
private int nextOrderID = 0;
// The IB API Client Socket object
private EClientSocket client = null;
public RealTimeBars ()
{
// Create a new EClientSocket object
client = new EClientSocket (this);
// Connect to the TWS or IB Gateway application
// Leave null for localhost
// Port Number (should match TWS/IB Gateway configuration
client.eConnect (null, 7496, 0);
// Pause here for connection to complete
try
{
// Thread.sleep (1000);
while (! (client.isConnected()));
} catch (Exception e) {
e.printStackTrace ();
};
// Create a new contract
Contract contract = new Contract ();
contract.m_symbol = "MSFT";
contract.m_exchange = "SMART";
contract.m_secType = "STK";
contract.m_primaryExch = "NASDAQ";
contract.m_currency = "USD";
// Create a TagValue list
Vector<TagValue> realTimeBarsOptions = new Vector<TagValue>();
// Make a call to start off data retrieval
client.reqRealTimeBars(0, contract,
5, // Bar Size 5 seconds
"TRADES", // whatToShow
false, // useRTH
realTimeBarsOptions);
// At this point our call is done and any market data events
// will be returned via the realtimeBar method
}
public static void main (String args[])
{
try
{
// Create an instance
// At this time a connection will be made
// and the request for market data will happen
RealTimeBars myData = new RealTimeBars();
}
catch (Exception e)
{
e.printStackTrace ();
}
}
}