IB API Close all Positions

Discussion in 'App Development' started by Mike805, Aug 21, 2012.

  1. Hello,

    I'm sure this has been requested before (and likely posted elsewhere); my question is about getting flat by end of day given a variety of circumstances.

    1. Is anyone willing to share some code (VBA possibly) that will close all positions when run (a starting point for this discussion that I can provide - it won't be pretty however as I'm not a very good programmer)?

    2. Can we start a discussion regarding the risks associated with such code and how to program around those risks:
    - For example: data disconnection and subsequent redundant checks upon reconnect to make sure the account will be flat.
    - S/W crash (not in IB's side) where the program can recover gracefully and guarantee the account is flat.

    I realize that if IB servers are down, there's nothing one can do... my question is aimed at a more general issue of never getting stuck in anything overnight. Whether the solution is programmable, or, something else entirely (broker request, auto-liquidation etc).

  2. Bob111



    i have it some where,but it was for older API version. like 9.4. basically-you request list of your positions,avg.prices, Qty and side. then- get a market data,make sure there is no crazy spreads and stuff like that. and you place an orders. or maybe there is a command now-liquidate all at whatever prices. bots will have a field day over this one.
  3. 2rosy


    request positions

    in callback close the position
  4. in tradelink you would do something like :

    public class MyFlatAtClose : ResponseTemplate
       int shutdownat = 155500;
       bool shutdown = true;
       override void GotTick(Tick k)
           if (shutdown && (k.time>=shutdownat))
                shutdown = false;
                foreach (var p in pt)
                    sendorder(new MarketOrderFlat(p));
       PositionTracker pt = new PositionTracker();
       override void GotPosition(Position p)
       override void GotFill(Trade f) { pt.Adjust(t); }
    reconnections occur automatically unless you disable them.

    for making sure problems in your own code/modules don't impact the shutdown routine, ensure you have exception handling setup so those errors aren't fatal and recover (or recover at least enough to allow shutdown checks to occur).

    for more info google tradelink project or tradelink.org
  5. crmorris


    could you add some sort of email writer to that class? i'd love to know when one of your users is about to run that.
  6. are you sure if the server is down a time order won't get executed?
  7. there's email and assembla.com ticket notification.

    I don't recall syntax offhand for email but pretty sure it's something straightforward like Email.send("from","to","sub","body"), you can insert it anywhere. docs on tradelink.org or one of the other users can probably help you with it.
  8. LOL...

    Maybe we can start with something simple. Take this snippet of code from IB's reference:

    If Not (objTWSControl Is Nothing) Then
    If objTWSControl.m_isConnected Then
    Call objTWSControl.m_TWSControl.reqAccountUpdates(True, "XXXXXXX")
    End If
    End If

    We can set this on some timer interval and wait for the callback to finish, right? So, the waiting part is what confuses me. How do we wait and check to make sure we have something back that is real? If the call fails and nothing returns ... then what?

    This is specific to the Active X API as its the environment I'm working in at the moment. Can I make VBA wait and timeout amd then do something more drastic when a timeout occurs?
  9. Mike, the reqAccountUpdates will send you positions one at a time. The responses from reqAccountUpdates comes via event, so you need to create an event handler for Tws.updatePortfolioEx. Then you can get the symbol and position via "e.contract.symbol, e.position" that your handler function should also contain. From there you can send a counter order for that contract, just invert the position. So it's all events, you dont have to use a timer for anything. It will reliably launch those events, so don't worry. Just make sure you have a check that a position is closed once you send the order, so you don't close it twice because sometimes the same status message can come in twice. There's a bunch of docs for the IB API at : http://www.interactivebrokers.com/php/apiUsersGuide/apiguide.htm

    btw, in VB.Net you create an event handler like this (Debug.AddLine is my own code, not the .Net debugger... just for illustration purposes)

    Private Sub updatePortfolioEx(ByVal sender As Object, ByVal e As AxTWSLib._DTwsEvents_updatePortfolioExEvent) Handles Tws.updatePortfolioEx
                    Debug.AddLine("Symbol = " & e.contract.symbol)
                    Debug.AddLine("Position = " & e.position)
     End Sub
  10. Thanks for this - very useful information.

    I am still having trouble synching on events, is there any difference in the TWS demo versus the real thing? It seems that no matter what I do, the portfolio update either takes a very long time, or, the request updates call doesn't return. Not sure what to do...

    In general, maybe you guys can recommend a course of action as I'm spending too much time on this already?

    I have an existing risk manager Excel spreadsheet that is key to my operation; it basically parses all trade signals from my signal generation system, assigns allocation amounts and then sends orders to TWS for execution.

    What I would like to see are a set of functions incorporated in this sheet that do the following:

    1. Close 50% of the portfolio of either the following:
    --Close 50% of all longs : adding liquidity on BATS.
    --Close 50% of all shorts : adding liquidity on BATS.
    --Close 50% of all longs : taking liquidity on SMART.
    --Close 50% of all shorts : taking liquidity on SMART.

    2. Close 100% of all positions by adding on BATS.

    3. Close 100% of portfolio by sending MOC's for all positions.

    4. Cancel all open orders.

    I am willing to pay for this, or, exchange some of the functionality I've already built up.

    #10     Aug 24, 2012