2

此代码正在生成每个市场的当前出价。但是当将它与历史数据进行比较时,它无法更新存储在 this.high 或 this.low 中的历史数据。

import com.ib.client.*;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

public class a1 implements EWrapper {

    private EJavaSignal clientignal = new EJavaSignal();
    private final EClientSocket client = new EClientSocket(this, clientignal);
 private static List<String> lines = Arrays.asList(new String[]{
       "EUR",
        "GBP",  
        "AUD",

    });
    // Keep track of the next ID
    private int nextOrderID = 0;
    // The IB API Client Socket object
  private static int nextId = 1; //auto increment for each request
    private int myId;
    private double high = Double.MAX_VALUE;
    private double low = -Double.MAX_VALUE;
 private double xx  = 0;
    private Integer currentPosition = 0;

    private Contract contract = new Contract();
    private int nextValidId_prev;
    private EReader reader = null;

    private String twsAccountNumber = "999"; // "999" 888;

    public static void main(String[] args) {
        System.out.print("main function");
        //new a1().startTws();
        a1 a1 = new a1();
        a1.twsConnectionChecker();
    }


    private void twsConnectionChecker() {
        new Thread(() -> {
            while (!Thread.interrupted()) {

                if (client.isConnected()) {
                    //log.info("tws connected");
                    client.reqCurrentTime();
                } else {
                   System.out.print("tws is not connected");
                    connectingToTWS();
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print("exiting reader thread");
        }).start();
    }

    private void connectingToTWS() {
       System.out.print("run is called");

        client.eConnect("127.0.0.1", 7497, 123);

        reader = new EReader(client, clientignal);
        reader.start();

        new Thread(() -> {
            while (client.isConnected()) {
                clientignal.waitForSignal();
                try {
                    reader.processMsgs();
                } catch (Exception e) {
                    error(e);
                }
                //log.info("processMsgs thread running");
            }
            System.err.println("thread exiting");
        }).start();

        //Contract contract = new Contract();
        //Order order = new Order();
        client.reqMarketDataType(3);
        //contract.m_localSymbol = "ESM7";

 lines.stream().forEach(line -> {
contract.symbol(line.split(",")[0]);
contract.exchange("IDEALPRO");
contract.secType("CASH");
contract.currency("USD");

System.out.print("request hst data");
requestHistoricalData();
requestStreamingData();
 client.reqAccountUpdates(true, twsAccountNumber);
}); 
    }


    public void requestHistoricalData() {
        /*
        client.reqHistoricalData(1, contract,
                LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + " 16:00:00",
                "1 D", "1 day", "MIDPOINT", 1, 1, null);
        */
        String requestDateTime = LocalDate.now().minusDays(1).format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("requestDateTime = " + requestDateTime);

        String requestDateTimeFull = requestDateTime + " 23:00:00";
        System.out.println("requestDateTimeFull = " + requestDateTimeFull);

        client.reqHistoricalData(1, contract, requestDateTimeFull, "1 D", "1 day", "MIDPOINT", 1, 1, null);

    }

    public void requestStreamingData() {
         myId = nextId++;
        System.out.println("requestStreamingData is being called");
        client.reqMktData(myId, contract, "", false,false, null);
        System.out.println("requestStreamingData is finished");


    }



    public void sendOrder(String orderSide, int parentOrderId) {
            new Thread(() -> {

           System.out.print("before getting ids, nextOrderID = " + nextOrderID + ", nextValidId_prev = " + nextValidId_prev);
            while (nextOrderID == nextValidId_prev) {
                System.out.print("waiting for next valid id...");
                client.reqIds(1);
                System.out.print("waiting for next valid id done");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.print("new nextOrderID = " + nextOrderID);
            nextValidId_prev = nextOrderID;

           System.out.print("sendOrder is called");

            Order order = new Order();
            order.action(orderSide);
            order.totalQuantity(20000);

            //log.info("sendOrder, this.high = " + this.high);


            DecimalFormat df = new DecimalFormat("0.0000"); 
// TODO get digit according

            if(orderSide.equals("SELL")){
                double xx = this.low;
            }else if(orderSide.equals("BUY")){
                double xx = this.high;
            }
df.setDecimalSeparatorAlwaysShown(true);
            String formatedEntryPrice = df.format(xx);
            formatedEntryPrice = formatedEntryPrice.replace(",", ".");

            System.out.print("formatedEntryPrice = " + formatedEntryPrice);
            order.lmtPrice(Double.valueOf(formatedEntryPrice)); // TODO stop limit at prior day high
            order.orderType("LMT");
 order.account ( "U1836253");
            order.account(twsAccountNumber);
            //int randomNum = ThreadLocalRandom.current().nextInt(1, 5564 + 1);
            //log.info("after creating order");

            String trailingOrderSide = "";
            if(orderSide.equals("SELL")){
                trailingOrderSide = "BUY";
            }else if(orderSide.equals("BUY")){
                trailingOrderSide = "SELL";
            }

            Order trailOrder = new Order();
            trailOrder.action(trailingOrderSide);
            //trailOrder.auxPrice(Double.valueOf("1.07000"));
            trailOrder.trailingPercent(1);
            trailOrder.orderType("TRAIL");
              trailOrder.account ( "U1836253");
            trailOrder.totalQuantity(20000);
            trailOrder.parentId(nextOrderID);
            trailOrder.transmit(true);
///
//            order.orderType("TRAIL");
//            order.totalQuantity(20000);
//            order.trailingPercent(1);
//            order.trailStopPrice(low);
//            stopLoss.parentId(nextOrderID);
//            order.transmit(true);

            //client.reqIds(1);


            client.placeOrder(nextOrderID, contract, order);
            client.placeOrder(nextOrderID + 1, contract, trailOrder);

            //attachOrder();
        }).start();
      System.out.print("sendOrder is finished");
    }

    @Override
    public void nextValidId(int orderId) {
        System.out.println("nextValidId " + orderId);
        nextOrderID = orderId;
        //contract.m_localSymbol = "ESM7";
        //Contract c = new Contract();
        //contract.m_localSymbol = "ESM7";

        /*
        contract.clientymbol = "AUY";
        contract.m_exchange = "SMART";
        contract.clientecType = "STK";
        contract.m_currency = "USD";

        client.reqHistoricalData(1, contract,
                LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + " 16:00:00",
                "2 D", "1 day", "MIDPOINT", 1, 1, null);
        client.reqMktData(1, contract, "", false, null);




        */
    }

    @Override
    public void error(int id, int errorCode, String errorMsg) {
        System.out.println(id + " " + errorCode + " " + errorMsg);
    }

    @Override
    public void historicalData(int reqId, String date, double open, double high, double low, double close, int volume, int count, double WAP, boolean hasGaps) {
        //if being run on the next calendar day, this works
        //System.out.println("historicalData = " + date + " h: " + high + " l: " + low);
        //if (now().minusDays(1).format(DateTimeFormatter.BASIC_ISO_DATE).equals(date)) {

       lines.stream().forEach(line -> {
                if (high > 0) {
            //this.high = high;
            this.high = high;

            this.low = low;
            System.out.println("historicalData = " + date + " this.high: " + this.high + " this.low: " + this.low);

        } 
    });
    return;
    }

   @Override
    public void tickPrice(int tickerId, int field, double price, TickAttr attrib) {
 lines.stream().forEach(line -> {
        //System.out.println("id: " + tickerId + " " + TickType.getField(field) + " price: " + price);
        //System.out.println(" h: " + high + " l: " + low);

        if (field == TickType.BID.index()) {
            System.out.println(high +"bid price filtered. bid = " + price);

            if (price >high  && currentPosition <= 1) {
                System.out.println("buy");
                currentPosition++;
                sendOrder("BUY",0);
            }

            if (price < low && currentPosition <= 1) {
                System.out.println("sell");
                currentPosition--;
                sendOrder("SELL",0);
            }

            if (price < high && price > low) {
                System.out.println("inside prev day range");
                System.out.println(high);
                System.out.println(low);
            }

        }
         return;


  });
         }

    @Override
    public void error(Exception e) {
    }


    @Override
    public void connectionClosed() {
    }

    @Override
    public void error(String str) {
    }


    @Override
    public void tickSize(int tickerId, int field, int size) {
    }

    @Override
    public void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) {
    }

    @Override
    public void tickGeneric(int tickerId, int tickType, double value) {
    }

    @Override
    public void tickString(int tickerId, int tickType, String value) {
    }

    @Override
    public void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints, double impliedFuture, int holdDays, String futureLastTradeDate, double dividendImpact,
                        double dividendsToLastTradeDate) {
    }

    @Override
    public void orderStatus(int orderId, String status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {

      System.out.println("first ID " + orderId+"first status " + status);
    }

    @Override
    public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) {

       System.out.println("another ID " + order+"another ID " + orderState);
    }

    @Override
    public void openOrderEnd() {
    }

    @Override
    public void updateAccountValue(String key, String value, String currency, String accountName) {
    }

    @Override
    public void updatePortfolio(Contract contract, double position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
    DecimalFormat df = new DecimalFormat("0.0000"); // TODO get digit according
        df.setDecimalSeparatorAlwaysShown(true);
        String formatedPosition = df.format(position);
        formatedPosition = formatedPosition.replace(",", ".");

        System.out.println("contract = " + contract.localSymbol() + ", contract.description() = " + contract.description() + ", unrealizedPNL = " + unrealizedPNL + ", formatedPosition = " + formatedPosition);


    }

    @Override
    public void updateAccountTime(String timeStamp) {
    }

    @Override
    public void accountDownloadEnd(String accountName) {
    }

    @Override
    public void contractDetails(int reqId, ContractDetails contractDetails) {


    }

    @Override
    public void bondContractDetails(int reqId, ContractDetails contractDetails) {
    }

    @Override
    public void contractDetailsEnd(int reqId) {
    }

    @Override
    public void execDetails(int reqId, Contract contract, Execution execution) {
    }

    @Override
    public void execDetailsEnd(int reqId) {
    }

    @Override
    public void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) {
    }

    @Override
    public void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation, int side, double price, int size) {
    }

    @Override
    public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) {
    }

    @Override
    public void managedAccounts(String accountsList) {
    }

    @Override
    public void receiveFA(int faDataType, String xml) {
    }


    @Override
    public void scannerParameters(String xml) {
    }

    @Override
    public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection, String legsStr) {
    }

    @Override
    public void scannerDataEnd(int reqId) {
    }

    @Override
    public void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) {

        // Display the Real-Time bar
        // reqId is the integer specified as the first parameter to reqRealTimeBars()
        try {
            System.out.println("realtimeBar:" + time + "," + open + "," +
                    high + "," + low + "," + close + "," +
                    volume);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void currentTime(long time) {
    }

    @Override
    public void fundamentalData(int reqId, String data) {
    }

    @Override
    public void deltaNeutralValidation(int reqId, DeltaNeutralContract underComp) {
    }

    @Override
    public void tickSnapshotEnd(int reqId) {
    }

    @Override
    public void marketDataType(int reqId, int marketDataType) {
    }

    @Override
    public void commissionReport(CommissionReport commissionReport) {
    }

    @Override
    public void position(String account, Contract contract, double pos, double avgCost) {
      System.out.println("contract " + contract);
    }

    @Override
    public void positionEnd() {
    }

    @Override
    public void accountSummary(int reqId, String account, String tag, String value, String currency) {
       System.out.println("value " + value);
    }

    @Override
    public void accountSummaryEnd(int reqId) {
    }

    @Override
    public void verifyMessageAPI(String apiData) {
    }

    @Override
    public void verifyCompleted(boolean isSuccessful, String errorText) {
    }

    @Override
    public void verifyAndAuthMessageAPI(String apiData, String xyzChallenge) {
    }

    @Override
    public void verifyAndAuthCompleted(boolean isSuccessful, String errorText) {
    }

    @Override
    public void displayGroupList(int reqId, String groups) {
    }

    @Override
    public void displayGroupUpdated(int reqId, String contractInfo) {
    }

    @Override
    public void positionMulti(int reqId, String account, String modelCode, Contract contract, double pos, double avgCost) {
    }

    @Override
    public void positionMultiEnd(int reqId) {
    }

    @Override
    public void accountUpdateMulti(int reqId, String account, String modelCode, String key, String value, String currency) {
    }

    @Override
    public void accountUpdateMultiEnd(int reqId) {
    }

    public void connectAck() {
    }

    @Override
    public void securityDefinitionOptionalParameter(int reqId, String exchange, int underlyingConId, String tradingClass,
                                                    String multiplier, Set<String> expirations, Set<Double> strikes) {
        System.out.print(reqId + ", " + exchange + ", " + underlyingConId + ", " + tradingClass + ", " + multiplier);

        for (String exp : expirations) {
            System.out.print(", " + exp);
        }

        for (double strk : strikes) {
            System.out.print(", " + strk);
        }

        System.out.println();
    }

    @Override
    public void securityDefinitionOptionalParameterEnd(int reqId) {
        System.out.println("done");
    }

    @Override
    public void softDollarTiers(int reqId, SoftDollarTier[] tiers) {
    }



    @Override
    public void familyCodes(FamilyCode[] familyCodes) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void symbolSamples(int reqId, ContractDescription[] contractDescriptions) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void historicalDataEnd(int reqId, String startDateStr, String endDateStr) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mktDepthExchanges(DepthMktDataDescription[] depthMktDataDescriptions) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void tickNews(int tickerId, long timeStamp, String providerCode, String articleId, String headline, String extraData) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void smartComponents(int reqId, Map<Integer, Map.Entry<String, Character>> theMap) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void tickReqParams(int tickerId, double minTick, String bboExchange, int snapshotPermissions) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void newsProviders(NewsProvider[] newsProviders) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void newsArticle(int requestId, int articleType, String articleText) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void historicalNews(int requestId, String time, String providerCode, String articleId, String headline) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void historicalNewsEnd(int requestId, boolean hasMore) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void headTimestamp(int reqId, String headTimestamp) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void histogramData(int reqId, List<Map.Entry<Double, Long>> items) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }


}

它正在输出:

0.75404bid price filtered. bid = 1.09067
0.75404bid price filtered. bid = 1.09067
0.75404bid price filtered. bid = 1.09067
0.75404bid price filtered. bid = 1.28989
0.75404bid price filtered. bid = 1.28989
0.75404bid price filtered. bid = 1.28989

如您所见,它输出不同市场的高点,但随后显示不同市场的出价。

4

0 回答 0