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
這里將避免在回測階段使用該策略。參見異常章節
-
Conception:
__init__
This is obviously invoked during instantiation:
indicators
will be created here and other needed attribute. Example: - 這里很顯然是在實例化期間調用:這里將創建指標和其他需要的屬性。
-
def __init__(self): self.sma = btind.SimpleMovingAverage(period=15)
-
Birth:
start
- 懷孕:
start
-
The world (
cerebro
) tells the strategy is time to start kicking. A default empty method exists. cerebro
告訴這個策略開始工作了。這是一個存在的默認的方法-
Childhood:
prenext
- 兒童:
prenext
indicators
declared during conception will have put constraints on how long the strategy needs to mature: this is called theminimum period
. Above__init__
created a SimpleMovingAverage with aperiod=15
. -
設計期間公布的指標將戰略成熟的時間之前限制:這被稱為最小周期。在
__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) - 只要系統看到的bar少於15個,prenext就會被調用(默認實現是no-op)
-
Adulthood:
next
- 成年:next
Once the system has seen
15
bars and theSimpleMovingAverage
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 fromprenext
tonext
. The default implementation ofnextstart
is to simply callnext
- 在next執行的時候,已經可以全部讀取到當時的時間幀的所有數據
- 一旦系統達到15條,並且SimpleMovingAverage擁有足夠大的緩沖區來開始產生價值,那么該策略就足夠成熟,可以真正執行了。
有一個nextstart方法,它只被調用一次,用於標記從prenext到next的切換。nextstart的默認實現只是調用next -
Reproduction:
None
- 再生產: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)
- 好吧,策略是不會重現的。但從某種意義上說,它們確實如此,因為如果優化(使用不同的參數),系統將對它們進行多次實例化。
-
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.
- 死亡:stop
- 系統告訴策略,重啟和整理的時間已經到來。存在一個默認的空方法。
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
andnexstart
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 overridennotify_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 - close方法明顯是關閉現有的倉位。
-
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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場價交易和關閉交易指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
has been used) - 僅適用於
StopLimit
指令。一旦止損被觸發,這就是設定隱含的限價指令的價格(已使用價格) -
exectype
(default:None
)Possible values:
-
Order.Market
orNone
. 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
orNone
.。市場訂單將以下一個可用價格執行。在回溯測試中,它將是下一個bar的開盤價-
Order.Limit
. An order which can only be executed at the givenprice
or better Order.Limit
.只能以給定價格或更好價格執行的訂單-
Order.Stop
. An order which is triggered atprice
and executed like anOrder.Market
order Order.Stop
.以價格觸發並執行訂單,感覺像5檔成交-
Order.StopLimit
. An order which is triggered atprice
and executed as an implicit Limit order with price given bypricelimit
- 以價格觸發並作為隱含限價指令執行的指令,價格由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
ordatetime.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
or0
ortimedelta()
: 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 inmatplotlib
coding (the one used bybacktrader
) 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. Thistradeid
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 aLIMIT 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 withlen(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 fordata0
. - 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 beforenext
is called - _orderspending:將在調用next之前通知策略的訂單列表
-
_tradespending
: list of trades which will be notified to the strategy beforenext
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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場和平倉指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
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
orNone
. 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
orNone
.。市場訂單將以下一個可用價格執行。在回溯測試中,它將是下一個bar的開盤價-
Order.Limit
. An order which can only be executed at the givenprice
or better Order.Limit
.只能以給定價格或更好價格執行的訂單-
Order.Stop
. An order which is triggered atprice
and executed like anOrder.Market
order Order.Stop
.以價格觸發並執行訂單,感覺像5檔成交-
Order.StopLimit
. An order which is triggered atprice
and executed as an implicit Limit order with price given bypricelimit
- 以價格觸發並作為隱含限價指令執行的指令,價格由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 atprice
minustrailamount
(ortrailpercent
) and which is updated if the price moves away from the stop - 以價格減去尾價(或尾價百分比)觸發的一種指令,當價格偏離止損點時,該指令更新
-
Order.StopTrailLimit
. An order which is triggered atprice
minustrailamount
(ortrailpercent
) 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
ordatetime.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
or0
ortimedelta()
: 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 inmatplotlib
coding (the one used bybacktrader
) 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. Thistradeid
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 aLIMIT 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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場和平倉指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
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
-> buytarget - pos.size
-
If
target
<pos.size
-> sellpos.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 is100
-
The
value
to be reached is0.05 * 100 = 5
-
5
is passed as thetarget
value toorder_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)
- buy if
-
If
target
<value
- sell if
pos.size >= 0
(Decrease a long position) - buy if
pos.size < 0
(Decrease a short position)
- sell if
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 belowtzdata
) -
bt.timer.SESSION_START
to reference a session start -
bt.timer.SESSION_END
to reference a session end -
offset
which must be adatetime.timedelta
instance
Used to offset the value
when
. It has a meaningful use in combination withSESSION_START
andSESSION_END
, to indicated things like a timer being called15 minutes
after the session start.-
repeat
which must be adatetime.timedelta
instanceIndicates if after a 1st call, further calls will be scheduled within the same session at the scheduled
repeat
deltaOnce 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 invokedIf not specified, the timer will be active on all days
-
weekcarry
(default:False
). IfTrue
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 monthIf 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 returnsTrue
if the date is allowed for timers or else returnsFalse
-
tzdata
which can be eitherNone
(default), apytz
instance or adata 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 thetz
parameter of the data feed instance.Note
If
when
is eitherSESSION_START
orSESSION_END
andtzdata
isNone
, the 1st data feed in the system (akaself.data0
) will be used as the reference to find out the session times. -
cheat
(defaultFalse
) ifTrue
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 tonotify_timer
-
**kwargs
: any extra kwargs will be passed tonotify_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.
------------恢復內容開始------------
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
這里將避免在回測階段使用該策略。參見異常章節
-
Conception:
__init__
This is obviously invoked during instantiation:
indicators
will be created here and other needed attribute. Example: - 這里很顯然是在實例化期間調用:這里將創建指標和其他需要的屬性。
-
def __init__(self): self.sma = btind.SimpleMovingAverage(period=15)
-
Birth:
start
- 懷孕:
start
-
The world (
cerebro
) tells the strategy is time to start kicking. A default empty method exists. cerebro
告訴這個策略開始工作了。這是一個存在的默認的方法-
Childhood:
prenext
- 兒童:
prenext
indicators
declared during conception will have put constraints on how long the strategy needs to mature: this is called theminimum period
. Above__init__
created a SimpleMovingAverage with aperiod=15
. -
設計期間公布的指標將戰略成熟的時間之前限制:這被稱為最小周期。在
__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) - 只要系統看到的bar少於15個,prenext就會被調用(默認實現是no-op)
-
Adulthood:
next
- 成年:next
Once the system has seen
15
bars and theSimpleMovingAverage
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 fromprenext
tonext
. The default implementation ofnextstart
is to simply callnext
- 在next執行的時候,已經可以全部讀取到當時的時間幀的所有數據
- 一旦系統達到15條,並且SimpleMovingAverage擁有足夠大的緩沖區來開始產生價值,那么該策略就足夠成熟,可以真正執行了。
有一個nextstart方法,它只被調用一次,用於標記從prenext到next的切換。nextstart的默認實現只是調用next -
Reproduction:
None
- 再生產: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)
- 好吧,策略是不會重現的。但從某種意義上說,它們確實如此,因為如果優化(使用不同的參數),系統將對它們進行多次實例化。
-
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.
- 死亡:stop
- 系統告訴策略,重啟和整理的時間已經到來。存在一個默認的空方法。
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
andnexstart
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 overridennotify_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 - 現有位置的明顯是關閉,
close
方法 -
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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場價交易和關閉交易指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
has been used) - 僅適用於
StopLimit
指令。一旦止損被觸發,這就是設定隱含的限價指令的價格(已使用價格) -
exectype
(default:None
)Possible values:
-
Order.Market
orNone
. 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
orNone
.。市場訂單將以下一個可用價格執行。在回溯測試中,它將是下一個bar的開盤價-
Order.Limit
. An order which can only be executed at the givenprice
or better Order.Limit
.只能以給定價格或更好價格執行的訂單-
Order.Stop
. An order which is triggered atprice
and executed like anOrder.Market
order Order.Stop
.以價格觸發並執行訂單,感覺像5檔成交-
Order.StopLimit
. An order which is triggered atprice
and executed as an implicit Limit order with price given bypricelimit
- 以價格觸發並作為隱含限價指令執行的指令,價格由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
ordatetime.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
or0
ortimedelta()
: 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 inmatplotlib
coding (the one used bybacktrader
) 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. Thistradeid
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 aLIMIT 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 withlen(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 fordata0
. - 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 beforenext
is called - _orderspending:將在調用next之前通知策略的訂單列表
-
_tradespending
: list of trades which will be notified to the strategy beforenext
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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場和平倉指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
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
orNone
. 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
orNone
.。市場訂單將以下一個可用價格執行。在回溯測試中,它將是下一個bar的開盤價-
Order.Limit
. An order which can only be executed at the givenprice
or better Order.Limit
.只能以給定價格或更好價格執行的訂單-
Order.Stop
. An order which is triggered atprice
and executed like anOrder.Market
order Order.Stop
.以價格觸發並執行訂單,感覺像5檔成交-
Order.StopLimit
. An order which is triggered atprice
and executed as an implicit Limit order with price given bypricelimit
- 以價格觸發並作為隱含限價指令執行的指令,價格由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 atprice
minustrailamount
(ortrailpercent
) and which is updated if the price moves away from the stop - 以價格減去尾價(或尾價百分比)觸發的一種指令,當價格偏離止損點時,該指令更新
-
Order.StopTrailLimit
. An order which is triggered atprice
minustrailamount
(ortrailpercent
) 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
ordatetime.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
or0
ortimedelta()
: 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 inmatplotlib
coding (the one used bybacktrader
) 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. Thistradeid
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 aLIMIT 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
(akaself.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
thesizer
instance retrieved viagetsizer
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 forMarket
andClose
orders (the market determines the price) - 對市場和平倉指令無效(市場決定價格)
-
For
Limit
,Stop
andStopLimit
orders this value determines the trigger point (in the case ofLimit
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 whichprice
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
-> buytarget - pos.size
-
If
target
<pos.size
-> sellpos.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 is100
-
The
value
to be reached is0.05 * 100 = 5
-
5
is passed as thetarget
value toorder_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)
- buy if
-
If
target
<value
- sell if
pos.size >= 0
(Decrease a long position) - buy if
pos.size < 0
(Decrease a short position)
- sell if
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 belowtzdata
) -
bt.timer.SESSION_START
to reference a session start -
bt.timer.SESSION_END
to reference a session end -
offset
which must be adatetime.timedelta
instance
Used to offset the value
when
. It has a meaningful use in combination withSESSION_START
andSESSION_END
, to indicated things like a timer being called15 minutes
after the session start.-
repeat
which must be adatetime.timedelta
instanceIndicates if after a 1st call, further calls will be scheduled within the same session at the scheduled
repeat
deltaOnce 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 invokedIf not specified, the timer will be active on all days
-
weekcarry
(default:False
). IfTrue
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 monthIf 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 returnsTrue
if the date is allowed for timers or else returnsFalse
-
tzdata
which can be eitherNone
(default), apytz
instance or adata 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 thetz
parameter of the data feed instance.Note
If
when
is eitherSESSION_START
orSESSION_END
andtzdata
isNone
, the 1st data feed in the system (akaself.data0
) will be used as the reference to find out the session times. -
cheat
(defaultFalse
) ifTrue
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 tonotify_timer
-
**kwargs
: any extra kwargs will be passed tonotify_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.
------------恢復內容結束------------