Closing Imbalance Script

Is it possible to write a script for individual symbols that gets long the stock at 15:50 if it has imbalance shares over a certain amount?


  • ptunneyptunney Posts: 246

    Yes, absolutely
    With any code your first step is to make sure you have all the steps down in detail, ideally as some kind of pseudo code.
    For example, you have not stated when you plan to exit. I would assume MOC.
    If you plan to run this over a long period of time you would also need to bear in mind that the market closes early on some dates.

    So your pseudo code steps would be..

    1) Qualify all symbols that could possibly meet your criteria at 15:50
    2) Set up any tracking variables you may want to use to keep track of your current status in each symbol. ie set self.status to zero
    3) At 15:50 check the imbalance, if the imbalance meets your requirements and self.status = 0 send a long order and print and set self status to 1
    4) When the long order fills (on_fill is called and self.status = 1), send a MOC order and print and set self.status to 2
    5) If the long order has not filled by x time (in on minute, if self.status =1 and time > x), cancel the order and print and set self.status to 999. We don't want to be getting filled when it is too late to send a MOC order.
    6) When the MOC order fills.. print and set self.status to 3

    When it comes to running the script, you can set the time of the backtest to custom and just run it from 15:49 to 16:20 (Allow plenty of time after the close to fill those MOC orders).

    All you need to do now is write that code using the pieces you need from the front page on the documentation tab.

    The main callbacks you will be using are

    is_symbol_qualified - to choose your symbol universe
    on_start - to set the initial status for each symbol to 0
    on_xxxx_imbalance - for whichever imbalance(s) you will be triggering off at 15:50 - remember to set
    on_minute - to check the order status for any sent orders every minute.
    on_fill - if it is filling the initial long then print and change self.status, if it is filling the MOC print success....
    on_minute - to check every order with self.status of 1 so that if it gets too late we can cancel. (you can use on_trade for a more fine check)

    That's it. Just write the code now.


  • tb435225tb435225 Posts: 7

    Thank you Paul! I did what you said and was successful getting the code to run with entry and exit working!

Sign In or Register to comment.