14.2 Timers

2020-05-02  本文已影响0人  wanggs66

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

-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.
    '''

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

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.

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

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

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

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.

上一篇 下一篇

猜你喜欢

热点阅读