当前位置: 首页 > 知识库问答 >
问题:

交互式经纪人API-执行多笔交易

漆雕宏浚
2023-03-14

我正在尝试为API创建一个程序,一次进行多个交易,然后获取股票价格,然后每隔一段时间重新平衡一次。我使用了一个在线教程来获取一些代码,并做了一些调整。

但是,当我运行代码时,它经常连接,如果我重新启动IB TWS,它会下订单。但是如果我再次运行代码,它就不起作用,或者显示它将连接的任何指示。有人能帮我弄清楚如何保持连接,这样我就可以运行main.java文件,它会执行多个交易,然后结束连接吗?我需要在代码或TWS的设置中更改客户端ID号吗?

有三个文件:

订单管理。爪哇:

package SendMarketOrder;
//import statements//

class OrderManagement extends Thread implements EWrapper{

private EClientSocket client = null; //IB API client Socket Object
private Stock stock = new Stock();
private Order order = new Order();
private int orderId;
private double limitprice;
private String Ticker;

//method to create connection class. It's the constructor
public OrderManagement() throws InterruptedException, ClassNotFoundException, SQLException {
    // Create a new EClientSocket object
    System.out.println("////////////// Creating a Connection ////////////");
    client = new EClientSocket(this); //Creation of a socket to connect
    //connect to the TWS Demo
    client.eConnect(null,7497,1);

    try {
        Thread.sleep(3000); //waits 3 seconds for user to accept
        while (!(client.isConnected()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("/////////      Connected /////////");
}
public void sendMarketOrder(String cusip, String buyorSell, int shares) throws SQLException, ClassNotFoundException{
    //New Order ID
    orderId++;
    order.m_action = buyorSell;
    order.m_orderId = orderId;
    order.m_orderType = "MKT";
    order.m_totalQuantity = shares;
    order.m_account = "DU33xxxxx"; //write own account
    order.m_clientId = 1;

    //Create a new contract
    stock.createContract(cusip);
    client.placeOrder(orderId, stock.contract, order);

    //Show order in console
    SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
    String current_time_str = time_formatter.format(System.currentTimeMillis());
    System.out.println("////////////////////////////////////////////////\n" + 
    "#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n" + 
    "#Client number: " + order.m_clientId + "///////////////////////////\n" + 
    "#OrderType: " + order.m_orderType + "///////////////////////////\n" + 
    "#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n" + 
    "#Account number: " + order.m_account + "///////////////////////////\n" + 
    "#Symbol: " + stock.contract.m_secId + "///////////////////////////\n" + 
    "///////////////////////////////////////"
    );
    }

股票JAVA

public class Stock{
private int StockId; //we can identify the stock
private String Symbol; //Ticker

    public Stock() { //default constructor
    }

    public Stock(int StockId, String Symbol) { //constructor
        this.StockId = StockId;
        this.Symbol = Symbol;
    }
    //getter and setters
    public int getStockId() {
        return StockId;
    }

    public String getSymbol() {
        return Symbol;
    }

Contract contract = new Contract ();
public void createContract(String cusip){
    contract.m_secId = cusip;
    contract.m_secIdType = "CUSIP";
    contract.m_exchange = "SMART";
    contract.m_secType = "STK";
    contract.m_currency = "USD";

}
}

主要的爪哇:

package SendMarketOrder;
import java.sql.SQLException;

public class Main {

public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
    OrderManagement order = new OrderManagement();
    order.sendMarketOrder("922908363","BUY", 100);
    order.sendMarketOrder("92204A504","BUY", 50);
    order.sendMarketOrder("92204A702","BUY", 100);
    System.exit(0);
}
}

以下是我的当前设置TWS设置(如果有帮助):

提前感谢您的帮助!

共有1个答案

闾丘谦
2023-03-14

我在代码中做了一些改动,并添加了注释。

package sendmarketorder;//usually lower case pkg names

public class Main {

    //you throw a bunch of exceptions that are never encountered 
    public static void main(String[] args) { 
        //since there's a Thread.sleep in this class
        //it will block until ready
        OrderManagement order = new OrderManagement();

        //obviously you need some logic to buy/sell
        //you can use command line args here if you want
        order.sendMarketOrder("922908363", "BUY", 100);
        order.sendMarketOrder("92204A504", "BUY", 50);
        order.sendMarketOrder("92204A702", "BUY", 100);

        //the socket creates a reader thread so this will stop it.
        //if you didn't have this line the non-daemon thread would keep a 
        //connection to TWS and that's why you couldn't reconnect
        //System.exit(0);//use better exit logic
    }
}

...

package sendmarketorder;

import com.ib.client.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

//doesn't extend thread and if you implement EWrapper you have to implement all methods
//in API 9.72 you can extend DefaultWrapper and just override the methods you need
public class OrderManagement implements EWrapper{

    private EClientSocket client = null; //IB API client Socket Object
    private int orderId = -1;//use as flag to send orders
    //private double limitprice;
    //private String Ticker;

    //keep track of all working orders
    private Map<Integer, Order> workingOrders = new HashMap<>();

    //method to create connection class. It's the constructor
    public OrderManagement(){
        // Create a new EClientSocket object
        System.out.println("////////////// Creating a Connection ////////////");
        client = new EClientSocket(this); //Creation of a socket to connect
        //connect to the TWS Demo
        client.eConnect(null, 7497, 123);//starts reader thread

        try {
            while (orderId < 0){ //not best practice but it works
                System.out.println("waiting for orderId");
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("/////////      Connected /////////");
    }

    public void sendMarketOrder(String cusip, String buyorSell, int shares) {
        //make new stock and order for each stock
        Stock stock = new Stock();
        Order order = new Order();
        //New Order ID, but get from API as you have to increment on every run for life
        orderId++;
        order.m_action = buyorSell;
        order.m_orderId = orderId;
        order.m_orderType = "MKT";
        order.m_totalQuantity = shares;
        //I don't think you're supposed to use these fields
        //order.m_account = "DU33xxxxx"; //write own account
        //order.m_clientId = 1;

        //Create a new contract
        stock.createContract(cusip);

        //remember which orders are working
        workingOrders.put(orderId, order);
        client.placeOrder(orderId, stock.contract, order);

        //Show order in console
        SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
        String current_time_str = time_formatter.format(System.currentTimeMillis());
        System.out.println("////////////////////////////////////////////////\n"
                + "#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n"
                + "#Client number: " + order.m_clientId + "///////////////////////////\n"
                + "#OrderType: " + order.m_orderType + "///////////////////////////\n"
                + "#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n"
                + "#Account number: " + order.m_account + "///////////////////////////\n"
                + "#Symbol: " + stock.contract.m_secId + "///////////////////////////\n"
                + "///////////////////////////////////////"
        );
    }

    //always impl the error callback so you know what's happening
    @Override
    public void error(int id, int errorCode, String errorMsg) {
        System.out.println(id + " " + errorCode + " " + errorMsg);
    }

    @Override
    public void nextValidId(int orderId) {
        System.out.println("next order id "+orderId);
        this.orderId = orderId;
    }

    @Override
    public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
        //so you know it's been filled
        System.out.println(EWrapperMsgGenerator.orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld));
        //completely filled when remaining == 0, or possible to cancel order from TWS
        if (remaining == 0 || status.equals("Cancelled")){
            //remove from map, should always be there
            if (workingOrders.remove(orderId) == null) System.out.println("not my order!");
        }

        //if map is empty then exit program as all  orders have been filled
        if (workingOrders.isEmpty()){
            System.out.println("all done");
            client.eDisconnect();//will stop reader thread
            //now is when you stop the program, but since all 
            //non-daemon threads have finished, the jvm will close.
            //System.exit(0);
        }
    }

    //impl rest of interface...
}
 类似资料:
  • 我正在尝试为Python应用编程接口创建一个程序,以便一次下多个交易/市场订单。我在网上使用了一个教程来获取一些代码,并做了一些更改。但是,我不能一次下多个订单。我使用了2个列表1是用于符号,另一个是用于它们的数量。(例如:购买3只苹果股票)。我的代码只执行最后一个订单:即“购买3只客户关系管理股票”。有人能帮我弄清楚如何下多个订单吗? 下面是我的Python代码:

  • 我曾尝试在VisualStudio2008中设置Interactive Broker的C API,但我知道的C非常有限,并且不断出现错误: 1)是否有任何方法可以使用某种轻量级的脚本语言来连接到Interactive Brokers并进行交易。 像Python这样轻量级的东西就可以了,是的,我已经研究过IBMY,但我不明白java2python系统是如何工作的。 2) 您是如何设置您的自动系统的,

  • 我想使用IB Api,但无法计算我们如何请求完整的符号列表和信息。 在我找到的文档中:reqScannerParameters()——但不清楚如何获得纳斯达克股票的列表? 有更好的办法吗?

  • Noob是个问题,但我正试图弄清楚Matlab交易工具箱使用的是哪种API,以便我可以参考适当的指南。 Matlab网站表示,有关如何实现交易系统的详细信息,请参考交互式经纪人API指南。。http://www.mathworks.com/help/trading/ibtws.createorder.html#inputarg_ibContract 但是,当我打开Interactive Broke

  • 基本上,我想使用python来查询我的IB订单历史,然后进行一些分析。但我找不到任何现有的API来查询这些数据,有人有这样做的经验吗?

  • 我希望在座的人能够帮助澄清如何在python API链接和交互式经纪人API中构建期货订单的IB Insync合同格式。我正在尝试使用IB Insync将autobot API链接开发成交互式代理API。我的系统现在运行得很好,自动以“库存”合同格式下订单;详情如下: 但是,当我根据文档将相同的python脚本应用于我对期货订单所需的IB Insync合同格式的理解时,什么都没有发生,API日志中