Tick Bars

David_BelvedereDavid_Belvedere Posts: 19
edited January 2017 in Request New Features

Hi all,

I just wanted to share some code I've created. CQ comes with minute bars which are great, but some strategies require tick bars (i.e. bars created after a certain amount of ticks, instead of a certain amount of time).

It essentially logs a tick at every 'on_trade', then when the number of ticks ('self.tick_bar_size') have been reached, a tick bar is created based on all the log ticks. 'on_tick_bar' is then called.

I've posted the code, as well as a bit of a sample on how to work with it. Let me know what you think - feedback, comments, etc. welcome!

# called at the beginning of each instance  
def on_start(self, md, order, service, account):
    ##### ON_TICK VARIABLES
    self.tick_count = 0
    self.tick_bar_open = None
    self.tick_bar_close = None
    self.tick_bar_high = None
    self.tick_bar_low = None
    self.tick_bar_size = 4500
    self.tick_bars = []
    self.close = []

# called when time and sales message is received
def on_trade(self, event, md, order, service, account):
    self.tick_count = self.tick_count+1

    if self.tick_count == 1:
        self.tick_bar_open = md.L1.last
        self.tick_bar_high = md.L1.last
        self.tick_bar_low = md.L1.last


    if md.L1.last > self.tick_bar_high or self.tick_bar_high is None:
        self.tick_bar_high = md.L1.last
    if md.L1.last < self.low_in_trade or self.tick_bar_low is None:
        self.tick_bar_low = md.L1.last

    if self.tick_count == self.tick_bar_size:
        self.tick_bar_close = md.L1.last
        self.tick_bars.append([self.tick_bar_close,self.tick_bar_open,self.tick_bar_high,self.tick_bar_low])
        self.tick_count = 0
        self.tick_bar_open = None
        self.tick_bar_close = None
        self.tick_bar_high = None
        self.tick_bar_low = None
        self.on_tick_bar(event, md, order, service, account)

# called whenever a new tick bar is formed
def on_tick_bar(self, event, md, order, service, account):

        #print "In on_tick_bar"
        self.close = [self.tick_bars[x][0] for x in range(len(self.tick_bars))]
        self.close = np.asarray(self.close)

Comments

Sign In or Register to comment.