IB Java API, placeorder in wrapper causes problems. Why?

Discussion in 'Programming' started by tchow, May 8, 2013.

  1. tchow

    tchow

    I am using the Java API and I've made a simple Swing GUI with a push button. When I push the button it executes:

    anInstance.connection.reqRealTimeBars(id, contract, 5,"TRADES",false); // note that connection = new EClientSocket(Wrapper) which is assigned in constructor

    This causes my overrided Wrapper function realtimeBar to execute. I use Joda Time and `getSecondOfMinute` to convert the Time in the wrapper function into what second it is. If it is 55 seconds, I want to place a trade. (I.e. I want my program to place a trade every minute at the 55 second mark).

    However whenever I place the trade, there is something which disconnects my connection with the API. The trade goes through, but subsequently I am no longer connected and get a nullPointerException.

    I think it might have to do with synchronization and perhaps some deadlock forcing a disconnect. Anyways, the error closes my connection to the API which is not what I want since the point of my program is to trade constantly.

    Does anyone know why this issue is coming up? More importantly, how do I get around this? I noticed it occurs when I use placeOrder in any wrapper function so I'm hoping someone has come across this before and can clarify for me.

    This seemed like the correct forum to put it in but let me know if I should put it somewhere else.


    Sample Code

    Code:
    someWrapper.java which overrides EWrapper: 
    
        public class someWrapper implements EWrapper {
            private IBProgram anInstance;
    
        public void setReference(IBProgram anInstance){
            this.anInstance = anInstance    
         }
    
        // overide and implement various EWrapper methods. 
        // The Ewrapper method below is a sample of placing an Order 
        // causing problems in an EWrapper method
    
        public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue,
                double averageCost, double unrealizedPNL, double realizedPNL, String accountName){
        
        Order myFakeOrder = new Order();
        Contract myFakeContract = new Contract();
        myFakeContract.m_symbol = "GOOG";
        myFakeContract.m_exchange = "SMART";
        myFakeContract.m_secType = "STK";
        myFakeContract.m_currency = "USD";
        myFakeOrder.m_action = "BUY";
        myFakeOrder.m_totalQuantity = 1;
        myFakeOrder.m_orderType = "LMT";
        myFakeOrder.m_lmtPrice = 1;
        myFakeOrder.m_tif = "DAY";
        anInstance.connection.placeOrder(2124124,myFakeContract,myFakeOrder);
        }
        }
    
    
    IBProgram.java
    
        public class IBProgram {
         someWrapper wrapper;
         public EClientSocket connection;
    
         public IBProgram() {
    
         this.wrapper = new someWrapper();
         this.connection = new EClientSocket(wrapper);
         }
        }
    
    GUI
    
        public class GUI extends javax.swing.JFrame{
             private IBProgram IBProgramInstance;
    
        public GUI(){
             initComponents();
        }
    
        private void initComponents() {
             myButton = new javax.swing.JButton();
             myButton.setText("Start Trading");
             myButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    myButtonActionPerformed(evt);
                }
            });
        }
    
        public void setReference(IBProgram Instance){
              this.IBProgramInstance = Instance;
        }
    
        private void myButtonActionPerformed (java.awt.event.ActionEvent evt) {     
                  IBProgramInstance.connection.reqAccountUpdates(true,"myaccountid");
        }
    
        public static void main(String args[]){
               IBProgram IBPInstance = new IBProgram();
               IBProgramInstance.wrapper.setReference(IBPInstance);
               IBProgram.connection.eConnect("127.0.0.1",7496,12);
               GUI guiInstance = new GUI();
               guiInstance.setReference(IBPInstance);
               guiInstance.setVisible(true);
               
        }
    
    
     
  2. Probably event wrappers, like any firm of exit or call-back, should not initiate new actions themselves, but just update in-memory flags and data structures, and new actions should be initiated only out of your main program loop.
     
  3. vicirek

    vicirek

    post it on tws api yahoo group. IB also has message board with API questions on their website.
     
  4. vicirek

    vicirek

    How do you increment your order Id?

    When you connect you should get NextValidId and then each consecutive order Id should be different.

    Normally you have to increment order id by 1 unless you have another method of assigning unique id number to your orders.

    In addition limit price of your order shows 1 for goog which can be rejected by TWS or at least you should get error message from tws.
     
  5. tchow

    tchow

    Regarding the EWrapper issue, I tested trying to place the order straight from my main and still couldn't get it working. Here is my code and log of my other program that has no GUI and simply connects, gets an order id and then tries placing an order.

    Again, the order is placed, but then i'm disconnected and receive a null pointer exception.

    Code:
    TradingProgram.java
    
    public class TradingProgram {
        static someWrapper wrapper;
        static EClientSocket connection;
        static int idsForReqs;
    
    public static void main(String[] args) {
            wrapper = new someWrapper();
            connection = new EClientSocket(wrapper);
            connection.eConnect("127.0.0.1", 7496, 1);
    
            // this sets the idsForReqs through the nextValidId wrapper method. idsForReqs is used to place the order
            connection.reqIds(1);
            
    	//placing a test order
    
            final Contract test = new Contract();
            test.m_exchange = "GLOBEX";
            test.m_currency = "USD";
            test.m_symbol = "ES";
            test.m_secType = "FUT";
            test.m_expiry = "201306";
            
            Order order = new Order();
            order.m_action = "BUY";
            order.m_totalQuantity = 1;
            order.m_lmtPrice = 1600;
            order.m_orderType = "LMT";  
                                
            connection.placeOrder(idsForReqs, test, order);
                    
        }
    }
    
    In someWrapper.java
    Code:
    public class someWrapper implements EWrapper {
    	private HashMap currentPositions;
    
    	public someWrapper(){
    	currentPositions = new HashMap();
    	}
    
    	public void nextValidId( int orderId){
    	 TradingProgram.idsForReqs = orderId;
    	    };
    
    
    //I have my errors printing to the console
    
    public void error( Exception e){
            System.out.println(EWrapperMsgGenerator.error(e));
        };
        public void error( String str){
            System.out.println(EWrapperMsgGenerator.error(str));
        };
        public void error(int id, int errorCode, String errorMsg){
            System.out.println(EWrapperMsgGenerator.error(id, errorCode, errorMsg));
        };
    
    Log
    Code:
    ER 12:49:02:957 JTS-EServerSocket-98: [0:0:67:1:0:0:0:SYS]Starting new conversation with client on 127.0.0.1/127.0.0.1
    ER 12:49:02:958 JTS-EServerSocketNotifier-97: Starting
    ER 12:49:02:958 JTS-EServerSocket-98: [0:60:67:1:0:0:0:SYS]TWS socket server version is 67
    ER 12:49:02:958 JTS-EServerSocket-98: [0:60:67:1:0:0:0:SYS]Client version is 60
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0:SYS]Client ID is 1
    ER 12:49:02:961 JTS-EServerSocket-98:[1:60:67:1:0:15:1:INFO] Sending list of managed accounts.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:15:1: DET][15;1;DU94676]
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:15:1:INFO]Sent the list of managed accounts.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:9:1:INFO]Sending next valid order id.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:9:1: DET][9;1;20]
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:9:1:INFO]Next valid order id sent.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:4:2: DET]Sending error.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:4:2: DET][4;2;-1;2104;Market data farm connection is OK:usfuture]
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:4:2: DET]Error sent.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Start processing incoming messages for client {1}.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Handling incoming ReqNextValidId message.
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Started reading message:
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished reading message:
    ER 12:49:02:961 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]kd::[version=1,numIds=1]
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Start validating message:
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished validating message:
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Started processing message:
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:9:1:INFO]Sending next valid order id.
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:9:1: DET][9;1;20]
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:9:1:INFO]Next valid order id sent.
    ER 12:49:02:962 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished processing message:
    ER 12:49:02:963 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Handling incoming PlaceOrder message.
    ER 12:49:02:964 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Started reading message:
    ER 12:49:02:966 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished reading message:
    ER 12:49:02:966 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]qc::[version=39,ID=20,reqDesc=Symbol=ES Type=FUT  Expiry=201306  Strike=0.0 Put/Call=?  Exchange=GLOBEX  CompExch=null Currency=USD  Multiplier=null  IbLocalSymbol=null  SecIdType=NULL  SecId=null includeExpired=false newsSource=null  Legs=null  Special Info=null,transmit=true,combo=null]
    ER 12:49:02:968 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET][39;20;ES;FUT;201306;0;2;null;GLOBEX;null;USD;null;NULL;null;1;1;LMT;Value;1550.0;Default;1.7976931348623157E308;1.7976931348623157E308;
    1.7976931348623157E308;0;DU94676.;true;0;null;ExpireDateTime[null];Reduce on Fill withoutBlock;null;SweepToFill=false;Hidden=false;NbboPriceCap=1.7976931348623157E308;StockRangeLower=1.7976931348623157E308;
    OpenCloseAttrib=O;StockRangeUpper=1.7976931348623157E308;ContinuousUpdate=false;TriggerMethod=Default;Clearing=null/IB;
    StockRefPrice=1.7976931348623157E308;PercentOffset=1.7976931348623157E308;AllOrNone=false;DeltaNeutralOrderType=None;
    StartingPrice=1.7976931348623157E308;OptionAcctAttrib=c;OptOutSmartRouting=false;DeltaNeutralAuxPrice=1.7976931348623157E308;
    FirmQuoteOnly=false;ETradeOnly=false;VolatilityType=None;ReferencePriceType=None;NotHeld=false;MinimumQuantity=2147483647;
    Delta=1.7976931348623157E308;DisplaySize=2147483647;Volatility=1.7976931348623157E308;BlockOrder=false;OutsideRth=false]
    ER 12:49:02:968 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Start validating message:
    ER 12:49:02:968 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished validating message:
    ER 12:49:02:968 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Started processing message:
    ER 12:49:02:968 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Placing orderId - 20
    ER 12:49:02:973 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Processing of order {20} completed.
    ER 12:49:02:974 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]Finished processing message:
    ER 12:49:03:168 JTS-CCPDispatcher-31: Storing ES on pendingpage
    ER 12:49:03:253 JTS-CCPDispatcher-31:[1:60:67:1:0:5:31:INFO] Sending open order.
    ER 12:49:03:257 JTS-CCPDispatcher-31: [1:60:67:1:0:5:31: DET][5;31;20;ES;FUT;20130621;0;?;GLOBEX;USD;ESM3;BUY;1;LMT;1550.0;0.0;DAY;null;DU94676;O;0;null;1;1743508218;0;0;1.7976931348623157E308;;
    1743508218.0/DU94676/100;null;1.7976931348623157E308;null;0;null;;1.7976931348623157E308;1.7976931348623157E308;
    1.7976931348623157E308;1.7976931348623157E308;1.7976931348623157E308;2147483647;false;false;false;false;2147483647;3.0;false;false;
    1.7976931348623157E308;0;0;1.7976931348623157E308;0;None;1.7976931348623157E308;0;0;1.7976931348623157E308;
    1.7976931348623157E308;2147483647;;2147483647;2147483647;1.7976931348623157E308;null;IB;0;null;false;Submitted;
    1.7976931348623157E308;1.7976931348623157E308;1.7976931348623157E308;
    1.7976931348623157E308;1.7976931348623157E308;1.7976931348623157E308;;null]
    ER 12:49:03:257 JTS-CCPDispatcher-31:[1:60:67:1:0:5:31:INFO] Open order sent.
    ER 12:49:03:257 JTS-CCPDispatcher-31: [1:60:67:1:0:3:6:INFO]Sending order status.
    ER 12:49:03:257 JTS-CCPDispatcher-31: [1:60:67:1:0:3:6: DET][3;6;20;Submitted;0;1;0;1743508218;0;0;1;]
    ER 12:49:03:257 JTS-CCPDispatcher-31: [1:60:67:1:0:3:6:INFO]Order status sent.
    ER 12:49:03:261 JTS-EServerSocket-98: [1:60:67:1:0:0:0:SYS]Client{1} terminated conversation.
    ER 12:49:03:262 JTS-EServerSocket-98: null
    ER 12:49:03:262 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Close call made for client{1} socket connection.
    ER 12:49:03:262 JTS-EServerSocket-98: [1:60:67:1:0:0:0: DET]closePrim called.  Stopping all mkt dataand HMDS requests for client{1}.
    ER 12:49:03:262 JTS-EServerSocket-98: ArEServer: Removing896424280 with id 1
    ER 12:49:03:262 JTS-EServerSocket-98: [1:60:67:1:0:0:0:INFO]Closed API client{1} session.
    ER 12:49:03:262 JTS-EServerSocketNotifier-97: Terminating
    ER 12:49:03:262 JTS-EServerSocket-98: [1:60:67:1:0:0:0:SYS]Ending conversation with client{1} at 127.0.0.1/127.0.0.1
    ER 12:49:03:263 JTS-EWriter2-99: [1:60:67:1:0:0:0:INFO]Close call made for client{1} socket connection.
    ER 12:49:03:263 JTS-EWriter2-99: [1:60:67:1:0:0:0:INFO]Client{1} already closed.
    ER 12:49:03:263 JTS-EWriter2-99: [1:60:67:1:0:0:0:SYS]Writer thread terminated for socket client{1}.
    
     
  6. You're missing something.

    Try getting their samples working and compare your code to their samples.
     
  7. vicirek

    vicirek

    It looks like your program does what it is suppose to do; after order is placed main() terminates and your socket connection is automatically terminated unless there is more code that is not posted due to space limitation.
     
  8. vicirek

    vicirek

    there is some issue with this page so I post it again; it seems like your main() after calling place order terminates; this will drop socket connection and terminate program so it looks this is how it is programmed unless there is more code keeping program running and socket listening to TWS messages and sending your requests. Use orderstatus() to receive messages on the progress of your order you have just sent.
     
  9. tchow

    tchow

    Ok I figured it out.

    Thanks for trying to help, and sorry for not including all the code.

    Turns out I had a variable in my openOrder wrapper method so that when I didn't place an order the openOrder never executed. Thus I thought my issue was related to placing an Order.

    In actuality I had a silly noob mistake where I had a variable in my openOrder which had not been initialized. Any ways, this has been fixed now. Thanks for the suggestions, Appreciate it.
     
  10. tchow,

    I know it has been a couple of years, but do you recall exactly what was going wrong with it? I am having the same issue (with C#) and I feel like I'm missing something small but can't seem to pinpoint it.
     
    #10     Oct 12, 2015