14.2 Timers

Timers 有一下选项可以用于控制相关操作:

  • Timer based in absolute time input or with regards to session start/end times

  • Timezone specification for the time specification, be it directly or via pytz compatible objects or via data feed session end times

  • Starting offset with regards to the specified time

  • Repetitions intervals

  • Weekdays filter (with carry over option)

  • Monthdays filter (with carry over option)

-Custom callback filter

Usage pasttern

Both in Cerebro and Strategy subclasses the timer callback will be received in the following method.

def notify_timer(self, timer, when, *args, **kwargs):
    '''Receives a timer notification where ``timer`` is the timer which was
    returned by ``add_timer``, and ``when`` is the calling time. ``args``
    and ``kwargs`` are any additional arguments passed to ``add_timer``

    The actual ``when`` time can be later, but the system may have not be
    able to call the timer before. This value is the timer value and not the
    system time.
    '''
  • Adding timers - Via Strategy
  • Adding timers - Via Cerebro

Done with the same method and just the addition of the parameter strats. If set to True the timer will not only be notified to the cerebro, it will also be notified to all strategies running in the system. strats 设定为True 则Timer作用于这个回测系统,不只是cerebro

def add_timer(self, when,
              offset=datetime.timedelta(), repeat=datetime.timedelta(),
              weekdays=[], weekcarry=False,
              monthdays=[], monthcarry=True,
              allow=None,
              tzdata=None, cheat=False, strats=False,
              *args, **kwargs):
    '''

Parameters to add_timer

  • when: can be

  • datetime.time instance (see below tzdata)

  • bt.timer.SESSION_START to reference a session start

  • bt.timer.SESSION_END to reference a session end

  • offset which must be a datetime.timedelta instance

Used to offset the value when. It has a meaningful use in combination with SESSION_START and SESSION_END, to indicated things like a timer being called 15 minutes after the session start.

  • repeat which must be a datetime.timedelta instance
    Indicates if after a 1st call, further calls will be scheduled within the same session at the scheduled repeat delta

Once the timer goes over the end of the session it is reset to the original value for when

  • weekdays: a sorted iterable with integers indicating on which days (iso codes, Monday is 1, Sunday is 7) the timers can be actually invoked
    If not specified, the timer will be active on all days

  • weekcarry (default: False). If True and the weekday was not seen (ex: trading holiday), the timer will be executed on the next day (even if in a new week)

  • monthdays: a sorted iterable with integers indicating on which days of the month a timer has to be executed. For example always on day 15 of the month

If not specified, the timer will be active on all days

  • monthcarry (default: True). If the day was not seen (weekend, trading holiday), the timer will be executed on the next available day.

  • allow (default: None). A callback which receives a datetime.date` instance and returns True if the date is allowed for timers or else returns False

  • tzdata which can be either None (default), a pytz instance or a data feed instance.

None: when is interpreted at face value (which translates to handling it as if it where UTC even if it’s not)

  • pytz instance: when will be interpreted as being specified in the local time specified by the timezone instance.

  • data feed instance: when will be interpreted as being specified in the local time specified by the tz parameter of the data feed instance.
    [Note] If when is either SESSION_START or SESSION_END and tzdata is
    None, the 1st data feed in the system (aka self.data0) will be
    used as the reference to find out the session times.

  • strats (default: False) call also the notify_timer of strategies

  • cheat (default False) if True the timer will be called before the broker has a chance to evaluate the orders. This opens the chance to issue orders based on opening price for example right before the session starts

  • *args: any extra args will be passed to notify_timer

  • **kwargs: any extra kwargs will be passed to notify_timer

Example for allow=callable

allow=callable where the callable accepts datetime.date instance. Notice this is not a datetime.datetime instance, because the allow callable is only meant to decide if a given day is suitable for timers or not.

To implement something like the rule laid out above:

class FutOpExp(object):
    def __init__(self):
        self.fridays = 0
        self.curmonth = -1

    def __call__(self, d):
        _, _, isowkday = d.isocalendar()

        if d.month != self.curmonth:
            self.curmonth = d.month
            self.fridays = 0

        # Mon=1 ... Sun=7
        if isowkday == 5 and   self.curmonth in [3, 6, 9, 12]:
            self.fridays += 1

            if self.friday == 3:  # 3rd Friday
                return True  # timer allowed

        return False  # timer disallowed

And one would pass allow=FutOpeExp() to the creation of the timer

This would allow a timer to kick in on the 3rd Friday of those months and may be close positions before the futures expire.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354