• Backtrader中文笔记之 Strategy


    Strategy

    A Cerebro instance is the pumping heart and controlling brain of backtrader. A Strategy is the same for the platform user.

    Cerebro实例是backtrader的跳动心脏和控制的大脑。对于平台用户,策略是相同的

    The Strategy’s expressed lifecycle in methods

    策略的生命周期用方法表示

    Note

    A strategy can be interrupted during birth by raising a StrategySkipError exception from the module backtrader.errors

    在一个策略的生成过程中,可以通过从backtrader.errors模块中抛出一个StrategySkipError异常来中断策略

    This will avoid going through the strategy during a backtesting. See the section Exceptions

    这里将避免在回测阶段使用该策略。参见异常章节

    1. Conception: __init__

      This is obviously invoked during instantiation: indicators will be created here and other needed attribute. Example:

    2. 这里很显然是在实例化期间调用:这里将创建指标和其他需要的属性。
    3. def __init__(self):
          self.sma = btind.SimpleMovingAverage(period=15)
      
    4. Birth: start

    5. 怀孕:start

      The world (cerebro) tells the strategy is time to start kicking. A default empty method exists.

    6. cerebro告诉这个策略开始工作了。这是一个存在的默认的方法
    7. Childhood: prenext

    8. 儿童:prenext

      indicators declared during conception will have put constraints on how long the strategy needs to mature: this is called the minimum period. Above __init__ created a SimpleMovingAverage with a period=15.

    9. 设计期间公布的指标将限制战略成熟的时间:这被称为最小周期。在__init__创造了一个SimpleMovingAverage,period=15。

      As long as the system has seen less than 15 bars, prenext will be called (the default implementation is a no-op)

    10. 只要系统看到的bar少于15个,prenext就会被调用(默认实现是no-op)
    11. Adulthood: next

    12. 成人:next

      Once the system has seen 15 bars and the SimpleMovingAverage has a buffer large enough to start producing values, the strategy is mature enough to really execute.

      There is a nextstart method which is called exactly once, to mark the switch from prenext to next. The default implementation of nextstart is to simply call next

    13. 一旦系统达到15条,并且SimpleMovingAverage拥有足够大的缓冲区来开始产生价值,那么该策略就足够成熟,可以真正执行了。

      有一个nextstart方法,它只被调用一次,用于标记从prenext到next的切换。nextstart的默认实现只是调用next
    14. Reproduction: None

    15. 再生产:None

      Ok, strategies do not really reproduce. But in a sense they do, because the system will instantiate them several times if optimizing (with different parameters)

    16. 好吧,策略是不会重现的。但从某种意义上说,它们确实如此,因为如果优化(使用不同的参数),系统将对它们进行多次实例化。
    17. Death: stop

      The system tells the strategy the time to come to a reset and put things in order has come. A default empty method exists.

    18. 死亡:stop
    19. 系统告诉策略,重启和整理的时间已经到来。存在一个默认的空方法。

    In most cases and for regular usage patterns this will look like:

    在大多数情况下,对于常规的使用模式,这看起来像:

    class MyStrategy(bt.Strategy):
    
        def __init__(self):
            self.sma = btind.SimpleMovingAverage(period=15)
    
        def next(self):
            if self.sma > self.data.close:
                # Do something
                pass
    
            elif self.sma < self.data.close:
                # Do something else
                pass
    

    In this snippet:

    在这个代码片段:

    • During __init__ an attribute is assigned an indicator

    • 在__init__期间,属性被分配一个指示符
    • The default empty start method is not overriden

    • 默认的空start方法没有被覆盖
    • prenext and nexstart are not overriden

    • prenext和nexstart没有被覆盖
    • In next the value of the indicator is compared against the closing price to do something

    • 接下来,将指标的值与收盘价进行比较,以完成某项操作
    • The default empty stop method is not overriden

    • 默认的空stop方法没有被覆盖

    Strategies, like a trader in the real world, will get notified when events take place. Actually once per next cycle in the backtesting process. The strategy will:

    策略就像现实世界中的交易者一样,在事件发生时得到通知。实际上是在回测过程的下一个循环中。战略将:

    • be notified through notify_order(order) of any status change in an order

    • 通过notify_order(order)通知订单中的任何状态更改
    • be notified through notify_trade(trade) of any opening/updating/closing trade

    • 通过notify_trade(trade)通知任何开始/更新/结束的交易
    • be notified through notify_cashvalue(cash, value) of the current cash and portfolio in the broker

    • 通过notify_cashvalue(现金,价值)通知经纪人的当前现金和投资组合
    • be notified through notify_fund(cash, value, fundvalue, shares) of the current cash and portfolio in the broker and tradking of fundvalue and shares

    • 通过notify_fund(现金、价值、基金价值、股份)通知经纪人的当前现金和投资组合以及基金价值和股份的交易
    • Events (implementation specific) via notify_store(msg, *args, **kwargs)

    • 事件(具体实现)通过notify_store(msg, *args, **kwargs)

      See Cerebro for an explanation on the store notifications. These will delivered to the strategy even if they have also been delivered to a cerebro instance (with an overriden notify_store method or via a callback)

    • 有关商店通知的解释,请参阅大脑。即使它们也已被传递到cerebro实例(使用重写的notify_store方法或通过回调)也会传递到策略中

    And Strategies also like traders have the chance to operate in the market during the next method to try to achieve profit with

    而策略也像交易者一样,有机会在市场中操作下一个方法,试图获得利润

    • the buy method to go long or reduce/close a short position

    • 做多或减/平空头的买入方法
    • the sell method to go short or reduce/close a long position

    • 卖空或减少/平仓多头的卖出方法
    • the close method to obviously close an existing position

    • 明显是关闭现有位置的关闭方法
    • the cancel method to cancel a not yet executed order

    • cancel方法取消尚未执行的订单

     

    How to Buy/Sell/Close

    The Buy and Sell methods generate orders. When invoked they return an Order (or subclass) instance that can be used as a reference. This order has a unique ref identifier that can be used for comparison

    Buy和Sell方法生成订单。当被调用时,它们返回一个可以用作引用的Order(或子类)实例。此订单具有可用于比较的唯一ref标识符

    Note

    Subclasses of Order for speficic broker implementations may carry additional unique identifiers provided by the broker.

    特定代理实现的Order子类可以携带代理提供的其他唯一标识符。

    To create the order use the following parameters:

     要创建订单,请使用以下参数:

    • data (default: None)

      For which data the order has to be created. If None then the first data in the system, self.datas[0] or self.data0 (aka self.data) will be used

    • 必须为其选择创建订单的数据。如果没有,那么系统中的第一个数据,self.datas[0] or self.data0(又名self.data)将被使用
    • size (default: None)

      Size to use (positive) of units of data to use for the order.

      If None the sizer instance retrieved via getsizer will be used to determine the size.

    • 为订单使用的数据单位的大小(正)。

      如果没有,那么通过getsizer获取的sizer实例将用于确定大小。
    • price (default: None)

      Price to use (live brokers may place restrictions on the actual format if it does not comply to minimum tick size requirements)

    • 使用价格(如果实际格式不符合最小刻度大小要求,实时经纪人可能会对实际格式进行限制)
    • None is valid for Market and Close orders (the market determines the price)

    • 对市场和平仓指令无效(市场决定价格)
    • For Limit, Stop and StopLimit orders this value determines the trigger point (in the case of Limit the trigger is obviously at which price the order should be matched)

    • 对于Limit, Stop和StopLimit指令,这个值决定了触发点(在Limit的情况下,触发点显然是该指令应该匹配的价格)。
    • plimit (default: None)

      Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for which price has been used)

    • 仅适用于StopLimit指令。这是触发止损后设置隐含限价单的价格(已使用价格)
    • exectype (default: None)

      Possible values:

      • Order.Market or None. A market order will be executed with the next available price. In backtesting it will be the opening price of the next bar

      • Order.Market or None.。市场订单将以下一个可用价格执行。在回溯测试中,它将是下一个bar的开盘价
      • Order.Limit. An order which can only be executed at the given price or better

      • Order.Limit.只能以给定价格或更好价格执行的订单
      • Order.Stop. An order which is triggered at price and executed like an Order.Market order

      • Order.Stop.以价格触发并执行订单,感觉像5档成交
      • Order.StopLimit. An order which is triggered at price and executed as an implicit Limit order with price given by pricelimit

      • 以价格触发并作为隐含限价指令执行的指令,价格由pricelimit给出
    • valid (default: None)

      Possible values:

      • None: this generates an order that will not expire (aka Good til cancel) and remain in the market until matched or canceled. In reality brokers tend to impose a temporal limit, but this is usually so far away in time to consider it as not expiring

      • 这将生成一个不会过期的订单(也就是在取消之前的好订单),并且在匹配或取消之前保持在市场中。在现实中,经纪人往往会设定一个时间限制,但这通常是如此遥远,以至于认为它不会到期
      • datetime.datetime or datetime.date instance: the date will be used to generate an order valid until the given datetime (aka good til date)

      • datetime.datetime或datetime.date实例:该日期将用于生成在给定日期之前有效的订单(也称为良好日期)
      • Order.DAY or 0 or timedelta(): a day valid until the End of the Session (aka day order) will be generated

      • Order.DAY或0或timedelta():生成会话结束前的有效日期(又名日顺序)
      • numeric value: This is assumed to be a value corresponding to a datetime in matplotlib coding (the one used by backtrader) and will used to generate an order valid until that time (good til date)

      • 数值:假设该值对应matplotlib编码中的日期时间(backtrader使用的日期),并将用于生成在该日期之前有效的订单(最佳日期)
    • tradeid (default: 0)

      This is an internal value applied by backtrader to keep track of overlapping trades on the same asset. This tradeid is sent back to the strategy when notifying changes to the status of the orders.

    • 这是backtrader应用的一个内部值,用于跟踪同一资产上的重叠交易。当通知订单状态的更改时,这个tradeid被发送回策略。
    • **kwargs: additional broker implementations may support extra parameters. backtrader will pass the kwargs down to the created order objects

    • **kwargs:其他代理实现可能支持额外的参数。backtrader将把kwarg传递到创建的order对象
    • Example: if the 4 order execution types directly supported by backtrader are not enough, in the case of for example Interactive Brokers the following could be passed as kwargs:

    • 示例:如果backtrader直接支持的4种订单执行类型还不够,在交互式代理的情况下,可以将以下内容作为kwargs传递:
    • orderType='LIT', lmtPrice=10.0, auxPrice=9.8
      

      This would override the settings created by backtrader and generate a LIMIT IF TOUCHED order with a touched price of 9.8 and a limit price of 10.0.

      这将覆盖backtrader创建的设置,并生成一个触及价格为9.8、限价为10.0的限价单。

    Information Bits:

    • A Strategy has a length which is always equal to that of the main data (datas[0]) and can of course be gotten with len(self)

    • 策略的长度总是等于主数据的长度(datas[0]),当然可以通过len(self)得到

      next can be called without changes in length if data is being replayed or a live feed is being passed and new ticks for the same point in time (length) are arriving

      如果正在replayed数据或传递实时提要,并且同一时间点(长度)的新刻度到达,则可以在不改变长度的情况下调用next

    Member Attributes:

    成员属性

    • env: the cerebro entity in which this Strategy lives

    • env:策略居住在的cerebro实例
    • datas: array of data feeds which have been passed to cerebro

    • datas:传递给cerebro的数据输入数组
      • data/data0 is an alias for datas[0]

      • data/data0是datas[0]的别名
      • dataX is an alias for datas[X]

      • dataX是datas[X]的别名

      data feeds can also be accessed by name (see the reference) if one has been assigned to it

    • 如果已经分配了一个数据源,也可以按名称访问数据源(请参阅参考资料)
    • dnames: an alternative to reach the data feeds by name (either with [name] or with .name notation)

    • dnames:按名称(使用[name]或.name符号)访问数据提要的另一种方法
    • For example if resampling a data like this:

    • 例如,如果重新采样数据像这样:
    • ...
      data0 = bt.feeds.YahooFinanceData(datname='YHOO', fromdate=..., name='days')
      cerebro.adddata(data0)
      cerebro.resampledata(data0, timeframe=bt.TimeFrame.Weeks, name='weeks')
      ...
      

      Later in the strategy one can create indicators on each like this:

    • 然后在这个策略里,你可以在每一个上面创建这样的指标:    
    ...
    smadays = bt.ind.SMA(self.dnames.days, period=30)  # or self.dnames['days']
    smaweeks = bt.ind.SMA(self.dnames.weeks, period=10)  # or self.dnames['weeks']
    ...
    
    • broker: reference to the broker associated to this strategy (received from cerebro)

    • broker:对与此策略关联的代理的引用(来自cerebro)
    • stats: list/named tuple-like sequence holding the Observers created by cerebro for this strategy

    • stats:包含cerebro为该策略创建的观察者的列表/类元命名序列
    • analyzers: list/named tuple-like sequence holding the Analyzers created by cerebro for this strategy

    • analyzers:包含cerebro为该策略创建的分析器的列表/命名类元序列
    • position: actually a property which gives the current position for data0.

    • position:实际上是一个为data0提供当前位置的属性。
    • Methods to retrieve all possitions are available (see the reference)

    • 检索所有职位的方法可用(请参阅参考资料)

    Member Attributes (meant for statistics/observers/analyzers):

    用于统计/观察者/分析者

    • _orderspending: list of orders which will be notified to the strategy before next is called

    • _orderspending:将在调用next之前通知策略的订单列表
    • _tradespending: list of trades which will be notified to the strategy before next is called

    • _tradespending:在调用next之前将被通知给策略的交易列表
    • _orders: list of order which have been already notified. An order can be several times in the list with different statuses and different execution bits. The list is menat to keep the history.

    • _orders:已被通知的订单列表。一个顺序可以在列表中多次出现,具有不同的状态和不同的执行位。这个名单是用来保存历史的。
    • _trades: list of order which have been already notified. A trade can be several times in the list just like an order.

    • _trades:已经被通知的订单列表。一个交易可以在列表中多次出现,就像一个订单。

    Note

    Bear in mind that prenext, nextstart and next can be called several times for the same point in time (ticks updating prices for the daily bar, when a daily timeframe is in use)

    请记住,prenext、nextstart和next可以在同一时间点被多次调用(当使用每日时间框架时,为每日条更新价格)

    Reference: Strategy

    class backtrader.Strategy(*args, **kwargs)

    Base class to be subclassed for user defined strategies.

    为用户定义的策略生成子类的基类。

    next()

    This method will be called for all remaining data points when the minimum period for all datas/indicators have been meet.

    当满足所有数据/指标的最小周期时,将对所有剩余数据点调用此方法。

    nextstart()

    This method will be called once, exactly when the minimum period for all datas/indicators have been meet. The default behavior is to call next

    当满足所有数据/指示器的最小周期时,该方法将被调用一次。默认行为是调用next

    prenext()

    This method will be called before the minimum period of all datas/indicators have been meet for the strategy to start executing

    该方法将在策略开始执行的所有数据/指示器满足最小周期之前调用

    start()

    Called right before the backtesting is about to be started.

    在backtesting即将开始之前调用。

    stop()

    Called right before the backtesting is about to be stopped

    在backtesting即将停止之前调用

    notify_order(order)

    Receives an order whenever there has been a change in one

    当一个命令发生变化时接收一个命令

    notify_trade(trade)

    Receives a trade whenever there has been a change in one

    一旦交易发生变化,就接收交易

    notify_cashvalue(cash, value)

    Receives the current fund value, value status of the strategy’s broker

    接收当前基金价值,该策略的经纪人的价值状态

    notify_fund(cash, value, fundvalue, shares)

    Receives the current cash, value, fundvalue and fund shares

    接收当前现金、价值、基金价值和基金份额

    notify_store(msg, *args, **kwargs)

    Receives a notification from a store provider

    接收来自商店提供者的通知

    buy(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)

    Create a buy (long) order and send it to the broker

    创建一个买入(多头)订单并将其发送给经纪人

    • data (default: None)

      For which data the order has to be created. If None then the first data in the system, self.datas[0] or self.data0 (aka self.data) will be used

    • 必须为其选择创建订单的数据。如果没有,那么系统中的第一个数据,self.datas[0] or self.data0(又名self.data)将被使用
    • size (default: None)

      Size to use (positive) of units of data to use for the order.

      If None the sizer instance retrieved via getsizer will be used to determine the size.

    • 为订单使用的数据单位的大小(正)。

      如果没有,那么通过getsizer获取的sizer实例将用于确定大小。
    • price (default: None)

      Price to use (live brokers may place restrictions on the actual format if it does not comply to minimum tick size requirements)

    • 使用价格(如果实际格式不符合最小刻度大小要求,实时经纪人可能会对实际格式进行限制)
    • None is valid for Market and Close orders (the market determines the price)

    • 对市场和平仓指令无效(市场决定价格)
    • For Limit, Stop and StopLimit orders this value determines the trigger point (in the case of Limit the trigger is obviously at which price the order should be matched)

    • 对于Limit, Stop和StopLimit指令,这个值决定了触发点(在Limit的情况下,触发点显然是该指令应该匹配的价格)
    • plimit (default: None)

      Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for which price has been used)

    • 仅适用于StopLimit指令。这是触发止损后设置隐含限价单的价格(已使用价格)
    • trailamount (default: None)

      If the order type is StopTrail or StopTrailLimit, this is an absolute amount which determines the distance to the price (below for a Sell order and above for a buy order) to keep the trailing stop

    • 如果订单类型是止损或止损限制,这是一个绝对数量,它决定了与价格的距离(低于卖出订单,高于买入订单),以保持跟踪止损
    • trailpercent (default: None)

      If the order type is StopTrail or StopTrailLimit, this is a percentage amount which determines the distance to the price (below for a Sell order and above for a buy order) to keep the trailing stop (if trailamount is also specified it will be used)

    • 如果订单类型是StopTrail或stoptrailamount,这是一个百分比金额,它决定了与价格的距离(低于卖出订单,高于买入订单),以保持尾随止损(如果还指定了trailamount,则将使用它)
    • exectype (default: None)

      Possible values:

      • Order.Market or None. A market order will be executed with the next available price. In backtesting it will be the opening price of the next bar

      • Order.Market or None.。市场订单将以下一个可用价格执行。在回溯测试中,它将是下一个bar的开盘价
      • Order.Limit. An order which can only be executed at the given price or better

      • Order.Limit.只能以给定价格或更好价格执行的订单
      • Order.Stop. An order which is triggered at price and executed like an Order.Market order

      • Order.Stop.以价格触发并执行订单,感觉像5档成交
      • Order.StopLimit. An order which is triggered at price and executed as an implicit Limit order with price given by pricelimit

      • 以价格触发并作为隐含限价指令执行的指令,价格由pricelimit给出
      • Order.Close. An order which can only be executed with the closing price of the session (usually during a closing auction)

      • 只有在收盘价的情况下才能执行的指令(通常在收盘拍卖期间)
      • Order.StopTrail. An order which is triggered at price minus trailamount (or trailpercent) and which is updated if the price moves away from the stop

      • 以价格减去尾价(或尾价百分比)触发的一种指令,当价格偏离止损点时,该指令更新
      • Order.StopTrailLimit. An order which is triggered at price minus trailamount (or trailpercent) and which is updated if the price moves away from the stop

      • 以价格减去尾价(或尾价百分比)触发的一种指令,当价格偏离止损点时,该指令更新
    • valid (default: None)

      Possible values:

      • None: this generates an order that will not expire (aka Good till cancel) and remain in the market until matched or canceled. In reality brokers tend to impose a temporal limit, but this is usually so far away in time to consider it as not expiring

      • 这将生成一个不会过期的订单(也就是在取消之前的好订单),并且在匹配或取消之前保持在市场中。在现实中,经纪人往往会设定一个时间限制,但这通常是如此遥远,以至于认为它不会到期
      • datetime.datetime or datetime.date instance: the date will be used to generate an order valid until the given datetime (aka good till date)

      • datetime.datetime或datetime.date实例:该日期将用于生成在给定日期之前有效的订单(也称为良好日期)
      • Order.DAY or 0 or timedelta(): a day valid until the End of the Session (aka day order) will be generated

      • Order.DAY或0或timedelta():生成会话结束前的有效日期(又名日顺序)
      • numeric value: This is assumed to be a value corresponding to a datetime in matplotlib coding (the one used by backtrader) and will used to generate an order valid until that time (good till date)

      • 数值:假设该值对应matplotlib编码中的日期时间(backtrader使用的日期),并将用于生成在该日期之前有效的订单(最佳日期)
    • tradeid (default: 0)

      This is an internal value applied by backtrader to keep track of overlapping trades on the same asset. This tradeid is sent back to the strategy when notifying changes to the status of the orders.

    • 这是backtrader应用的一个内部值,用于跟踪同一资产上的重叠交易。当通知订单状态的更改时,这个tradeid被发送回策略。
    • oco (default: None)

      Another order instance. This order will become part of an OCO (Order Cancel Others) group. The execution of one of the orders, immediately cancels all others in the same group

    • 另一个订单实例。此订单将成为OCO(order Cancel Others)组的一部分。执行其中一个命令后,立即取消同一组中的所有其他命令
    • parent (default: None)

      Controls the relationship of a group of orders, for example a buy which is bracketed by a high-side limit sell and a low side stop sell. The high/low side orders remain inactive until the parent order has been either executed (they become active) or is canceled/expires (the children are also canceled) bracket orders have the same size

    • 控制一组订单之间的关系,例如:由高边限价卖出和低端止损卖出包围的买入。高/低端订单保持不活动状态,直到父订单被执行(它们变为活动状态)或被取消/过期(子订单也被取消)方括号订单的大小相同
    • transmit (default: True)

      Indicates if the order has to be transmitted, ie: not only placed in the broker but also issued. This is meant for example to control bracket orders, in which one disables the transmission for the parent and 1st set of children and activates it for the last children, which triggers the full placement of all bracket orders.

    • 指示是否必须传输订单,即:不仅要放置在代理中,还要发出订单。例如,这意味着控制方括号订单,其中禁用父节点和第一组子节点的传输,并激活最后一组子节点的传输,这将触发所有方括号订单的完整放置。
    • **kwargs: additional broker implementations may support extra parameters. backtrader will pass the kwargs down to the created order objects

    • **kwargs:其他代理实现可能支持额外的参数。backtrader将把kwarg传递到创建的order对象
    • Example: if the 4 order execution types directly supported by backtrader are not enough, in the case of for example Interactive Brokers the following could be passed as kwargs:

    • 示例:如果backtrader直接支持的4种订单执行类型还不够,在交互式代理的情况下,可以将以下内容作为kwargs传递:
    • orderType='LIT', lmtPrice=10.0, auxPrice=9.8
      

      This would override the settings created by backtrader and generate a LIMIT IF TOUCHED order with a touched price of 9.8 and a limit price of 10.0.

    • 这将覆盖backtrader创建的设置,并生成一个触及价格为9.8、限价为10.0的限价单。
    • Returns

      • the submitted order
      • 提交订单

    sell(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)

    To create a selll (short) order and send it to the broker

    创建一个短单并将其发送给经纪人

    See the documentation for buy for an explanation of the parameters

    有关参数的解释,请参阅buy的文档

    Returns: the submitted order

    返回:提交的订单

    close(data=None, size=None, **kwargs)

    Counters a long/short position closing it

    平仓的多头/空头头寸

    See the documentation for buy for an explanation of the parameters

    有关参数的解释,请参阅buy的文档

    Note

    • size: automatically calculated from the existing position if not provided (default: None) by the caller
    • size:如果没有由调用者提供(默认为None),则根据现有位置自动计算

    Returns: the submitted order

    cancel(order)

    Cancels the order in the broker

    取消经纪人的订单

    buy_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs={}, stopprice=None, stopexec=3, stopargs={}, limitprice=None, limitexec=2, limitargs={}, **kwargs)

    Create a bracket order group (low side - buy order - high side). The default behavior is as follows:

    创建一个支架订单组(低边-买单-高边)。默认行为如下:

    • Issue a buy order with execution Limit

    • 发出有执行限制的购买指令
    • Issue a low side bracket sell order with execution Stop

    • 发出带有执行停止的低端支架卖出指令
    • Issue a high side bracket sell order with execution Limit.

    • 发出具有执行限制的高端卖出指令。

    See below for the different parameters

    请参阅下面的不同参数

    • data (default: None)

      For which data the order has to be created. If None then the first data in the system, self.datas[0] or self.data0 (aka self.data) will be used

    • 必须为其选择创建订单的数据。如果没有,那么系统中的第一个数据,self.datas[0] or self.data0(又名self.data)将被使用
    • size (default: None)

      Size to use (positive) of units of data to use for the order.

      If None the sizer instance retrieved via getsizer will be used to determine the size.

    • 为订单使用的数据单位的大小(正)。

      如果没有,那么通过getsizer获取的sizer实例将用于确定大小。
    • Note

      The same size is applied to all 3 orders of the bracket

      相同的大小适用于括号的所有3个订单

    • price (default: None)

      Price to use (live brokers may place restrictions on the actual format if it does not comply to minimum tick size requirements)

    • 使用价格(如果实际格式不符合最小刻度大小要求,实时经纪人可能会对实际格式进行限制)
    • None is valid for Market and Close orders (the market determines the price)

    • 对市场和平仓指令无效(市场决定价格)
    • For Limit, Stop and StopLimit orders this value determines the trigger point (in the case of Limit the trigger is obviously at which price the order should be matched)

    • 对于Limit, Stop和StopLimit指令,这个值决定了触发点(在Limit的情况下,触发点显然是该指令应该匹配的价格)
    • plimit (default: None)

      Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for which price has been used)

    • 仅适用于StopLimit指令。这是触发止损后设置隐含限价单的价格(已使用价格)

    • trailamount (default: None)

      If the order type is StopTrail or StopTrailLimit, this is an absolute amount which determines the distance to the price (below for a Sell order and above for a buy order) to keep the trailing stop

    • 如果订单类型是止损或止损限制,这是一个绝对数量,它决定了与价格的距离(低于卖出订单,高于买入订单),以保持跟踪止损
    • trailpercent (default: None)

      If the order type is StopTrail or StopTrailLimit, this is a percentage amount which determines the distance to the price (below for a Sell order and above for a buy order) to keep the trailing stop (if trailamount is also specified it will be used)

    • 如果订单类型是StopTrail或stoptrailamount,这是一个百分比金额,它决定了与价格的距离(低于卖出订单,高于买入订单),以保持尾随止损(如果还指定了trailamount,则将使用它)
    • exectype (default: bt.Order.Limit)

      Possible values: (see the documentation for the method buy

    • valid (default: None)

      Possible values: (see the documentation for the method buy

    • tradeid (default: 0)

      Possible values: (see the documentation for the method buy

    • oargs (default: {})

      Specific keyword arguments (in a dict) to pass to the main side order. Arguments from the default **kwargs will be applied on top of this.

    • 要传递给主端顺序的特定关键字参数(字典中)。来自默认**kwarg的参数将应用于此之上。
    • **kwargs: additional broker implementations may support extra parameters. backtrader will pass the kwargs down to the created order objects

    • **kwargs:其他代理实现可能支持额外的参数。backtrader将把kwarg传递到创建的order对象
    • Possible values: (see the documentation for the method buy

      Note

      This kwargs will be applied to the 3 orders of a bracket. See below for specific keyword arguments for the low and high side orders

      这个kwargs将应用于一个括号的3阶。见下面的具体关键字参数的低和高边的订单

    • stopprice (default: None)

      Specific price for the low side stop order

    • 为低侧停止订单的具体价格
    • stopexec (default: bt.Order.Stop)

      Specific execution type for the low side order

    • 低端订单的特定执行类型
    • stopargs (default: {})

      Specific keyword arguments (in a dict) to pass to the low side order. Arguments from the default **kwargs will be applied on top of this.

    • 特定的关键字参数(在字典中)传递到低端顺序。来自默认**kwarg的参数将应用于此之上。
    • limitprice (default: None)

      Specific price for the high side stop order

    • 具体价格为高价侧止损订单
    • stopexec (default: bt.Order.Limit)

      Specific execution type for the high side order

    • 高端订单的特定执行类型
    • limitargs (default: {})

      Specific keyword arguments (in a dict) to pass to the high side order. Arguments from the default **kwargs will be applied on top of this.

    • 特定的关键字参数(在字典中)传递给高端顺序。来自默认**kwarg的参数将应用于此之上。

    High/Low Side orders can be suppressed by using:

    可以使用以下方法抑制高/低侧阶数:

    • limitexec=None to suppress the high side

    • stopexec=None to suppress the low side

    • Returns

      • A list containing the 3 orders [order, stop side, limit side]

      • 包含3个指令的列表[指令,停止边,限制边]
      • If high/low orders have been suppressed the return value will still contain 3 orders, but those suppressed will have a value of None

      • 如果高/低阶被抑制,返回值将仍然包含3个阶,但是那些被抑制的将有一个值为None

    sell_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs={}, stopprice=None, stopexec=3, stopargs={}, limitprice=None, limitexec=2, limitargs={}, **kwargs)

    Create a bracket order group (low side - buy order - high side). The default behavior is as follows:

    创建一个支架订单组(低边-买边-高边)。默认行为如下:

    • Issue a sell order with execution Limit

    • Issue a high side bracket buy order with execution Stop

    • Issue a low side bracket buy order with execution Limit.

    See bracket_buy for the meaning of the parameters

    High/Low Side orders can be suppressed by using:

    • stopexec=None to suppress the high side

    • limitexec=None to suppress the low side

    • Returns

      • A list containing the 3 orders [order, stop side, limit side]

      • If high/low orders have been suppressed the return value will still contain 3 orders, but those suppressed will have a value of None

    order_target_size(data=None, target=0, **kwargs)

    Place an order to rebalance a position to have final size of target

    下单重新平衡仓位以确定目标的最终大小

    The current position size is taken into account as the start point to achieve target

    以当前的位置大小作为实现目标的起点

    • If target > pos.size -> buy target - pos.size

    • If target < pos.size -> sell pos.size - target

    It returns either:

    它返回:

    • The generated order
    • 生成的订单

    or

    • None if no order has been issued (target == position.size)
    • 如果没有发出订单,则为None (target == position.size)

    order_target_value(data=None, target=0.0, price=None, **kwargs)

    Place an order to rebalance a position to have final value of target

    下单再平衡有目标的最终值

    The current value is taken into account as the start point to achieve target

    以当前值作为实现目标的起点

    • If no target then close postion on data

    • If target > value then buy on data

    • If target < value then sell on data

    It returns either:

    • The generated order

    or

    • None if no order has been issued

    order_target_percent(data=None, target=0.0, **kwargs)

    Place an order to rebalance a position to have final value of target percentage of current portfolio value

    target is expressed in decimal: 0.05 -> 5%

    It uses order_target_value to execute the order.

    Example

    • target=0.05 and portfolio value is 100

    • The value to be reached is 0.05 * 100 = 5

    • 5 is passed as the target value to order_target_value

    The current value is taken into account as the start point to achieve target

    The position.size is used to determine if a position is long / short

    • If target > value

      • buy if pos.size >= 0 (Increase a long position)
      • sell if pos.size < 0 (Increase a short position)
    • If target < value

      • sell if pos.size >= 0 (Decrease a long position)
      • buy if pos.size < 0 (Decrease a short position)

    It returns either:

    • The generated order

    or

    • None if no order has been issued (target == position.size)

    getsizer()

    Returns the sizer which is in used if automatic statke calculation is used

    Also available as sizer

    如果使用自动数据计算,返回正在使用的分级机

    setsizer(sizer)

    Replace the default (fixed stake) sizer

    替换默认的(固定赌注)分级机

    getsizing(data=None, isbuy=True)

    Return the stake calculated by the sizer instance for the current situation

    返回由sizer实例为当前情况计算的赌注

    getposition(data=None, broker=None)

    Returns the current position for a given data in a given broker.

    返回给定代理中给定数据的当前位置。

    If both are None, the main data and the default broker will be used

    如果两者都为None,则将使用主数据和缺省代理

    A property position is also available

    getpositionbyname(name=None, broker=None)

    Returns the current position for a given name in a given broker.

    If both are None, the main data and the default broker will be used

    A property positionbyname is also available

    getpositionsbyname(broker=None)

    Returns the current by name positions directly from the broker

    If the given broker is None, the default broker will be used

    A property positionsbyname is also available

    getdatanames()

    Returns a list of the existing data names

    getdatabyname(name)

    Returns a given data by name using the environment (cerebro)

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

    Note

    Can be called during __init__ or start

    Schedules a timer to invoke either a specified callback or the notify_timer of one or more strategies.

    • Parameters

      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.

      • 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

    Return Value:

    • The created timer

    notify_timer(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 no the system time.

  • 相关阅读:
    Python对JSON的操作 day3
    Python 文件操作 day2
    Python 字符串常用方法 day2
    Python字典 day2
    Python基础学习(day1)
    Excel图表转成图片
    hadoop —— MapReduce:统计访问所有独立IP个数 、 统计网站子目录访问次数 、 统计每个IP访问的子目录数
    Java -D命令对应的代码中获取-D后面的参数 和 多个参数时-D命令的使用
    hadoop —— teragen & terasort
    C# 计时器 以“天时分秒毫秒”形式动态增加显示
  • 原文地址:https://www.cnblogs.com/sidianok/p/13528058.html
Copyright © 2020-2023  润新知