Backtrader中文笔记之Live Data Oanda
原文地址:https://www.backtrader.com/docu/live/oanda/oanda/
Oanda
The integration with Oanda supports both:
与Oanda的集成同时支持:
-
Live Data feeding
- 实时的数据源
-
Live Trading
- 实时交易
Requirements
要求
-
oandapy
Install it with:
pip install git+https://github.com/oanda/oandapy.git
-
pytz
(optional and not really recommended) - pytz(可选,不推荐)
-
Given the worlwide and 24x7 nature of Forex, the choice is work in
UTC
time. You may still work with your desired output timezone if wished. - 鉴于外汇的全球范围和24x7的性质,选择在UTC时间工作。如果愿意,您仍然可以使用您想要的输出时区。
Sample Code
案例代码
The sources contain a full sample under:
下面这个来源包含完整代码:
samples/oandatest/oandatest.py
Oanda - the store
The store is the keystone of the live data feed/trade support, providing a layer of adaptation between the Oanda API and the needs of a data feed and a broker proxy.
该仓库是实时数据feed/交易支持的基石,在Oanda API和数据源和券商代理之间提供了一层适应。
-
Provides access to getting a broker instance with the method:
- 提供了获取券商实例的方法
-
OandaStore.getbroker(*args, **kwargs)
-
Provides access to getter data feed instances
- 提供了获取数据源实例的方法
-
OandaStore.getedata(\*args, **kwargs)
In this case many of the
**kwargs
are common to data feeds likedataname
,fromdate
,todate
,sessionstart
,sessionend
,timeframe
,compression
The data may provide other params. Check the reference below.
Mandatory parameters
强制参数
In order to successfully connect to Oanda, the following parameters are mandatory:
为了成功连接到Oanda,以下参数是必须的:
-
token
(default:None
): API access token -
account
(default:None
): account id
This are provided by Oanda
这是有Oanda提供的
Whether to connect to the practice server or to the real server, use:
无论连接的是联系服务区还是正常服务器,使用:
practice
(default:False
): use the test environmentpractice
(default:False
):使用测设环境
The account has to be periodically checked to get the cash and value. The periodicity can be controlled with:
必须定期检查账户以获得现金和价值。周期性可通过以下方式控制:
account_tmout
(default:10.0
): refresh period for account value/cash refresh- 帐户输出(默认值:10.0):帐户值刷新周期/现金刷新
Oanda feeds
Instantiating the data:
实例化数据:
-
Pass the symbol according to the Oanda guidelines
- 根据Oanda指南传入标识
-
- EUR/USDD following the guidelines from Oanda has to be specified as as
EUR_USD
. Instantiate it as:
- EUR/USDD following the guidelines from Oanda has to be specified as as
-
data = oandastore.getdata(dataname='EUR_USD', ...)
Time management
时间管理
Unless a tz
parameter (a pytz-compatible object) is passed to the data feed, all time output is in UTC
format as expressed above.
除非向数据提要传递了一个tz参数(一个与pytz兼容的对象),否则所有时间输出都是上述UTC格式。
Backfilling
backtrader makes no special request to Oanda. For small timeframes the backfilling returned by Oanda on the practice servers has been 500
bars long
backtrader对Oanda没有特殊要求。对于较小的时间范围,Oanda在练习服务器上返回的回填长度为500bar
OandaBroker - Trading Live
Using the broker
使用券商
To use the OandaBroker, the standard broker simulation instance created by cerebro has to be replaced.
要使用OandaBroker,必须替换cerebro创建的标准券商模拟实例。
Using the Store model (preferred):
使用仓库里面的model(首选)
import backtrader as bt cerebro = bt.Cerebro() oandastore = bt.stores.OandaStore() cerebro.broker = oandastore.getbroker() # or cerebro.setbroker(...)
Broker - Initial Positions
The broker supports a single parameter:
-
use_positions
(default:True
): When connecting to the broker provider use the existing positions to kickstart the broker.Set to
False
during instantiation to disregard any existing position
Opperations
There is no change with regards to the standar usage. Just use the methods available in the strategy (see the Strategy
reference for a full explanation)
-
buy
-
sell
-
close
-
cancel
Order Execution Types
Oanda supports almost all of the order execution types needed by backtrader with the exception of Close.
As such the order execution types are limited to:
-
Order.Market
-
Order.Limit
-
Order.Stop
-
Order.StopLimit
(using Stop and upperBound / lowerBound prices) -
Order.StopTrail
-
Bracket orders are supported by using the
takeprofit
andstoploss
order members and creating internally simulated orders.
Order Validity
The same validity notion available during backtesting (with valid
to buy
and sell
) is available and with the same meaning. As such, the valid
parameter is translated as follows for Oanda Orders for the following values:
-
None
translates to Good Til CancelledBecause no validity has been specified it is understood that the order must be valid until cancelled
-
datetime/date
translates to Good Til Date -
timedelta(x)
translates to Good Til Date (heretimedelta(x) != timedelta()
)This is interpreted as a signal to have an order be valid from
now
+timedelta(x)
-
timedelta() or 0
translates to SessionA value has been passed (instead of
None
) but is Null and is interpreted as an order valid for the current day (session)
Notifications
The standard Order
status will be notified to a strategy over the method notify_order
(if overridden)
-
Submitted
- the order has been sent to TWS -
Accepted
- the order has been placed -
Rejected
- Use for real rejections and when no other status is known during order creation -
Partial
- a partial execution has taken place -
Completed
- the order has been fully executed -
Canceled
(orCancelled
) -
Expired
- when an order is cancelled due to expiry
Reference
OandaStore
class backtrader.stores.OandaStore()
Singleton class wrapping to control the connections to Oanda.
Params:
-
token
(default:None
): API access token -
account
(default:None
): account id -
practice
(default:False
): use the test environment -
account_tmout
(default:10.0
): refresh period for account value/cash refresh
OandaBroker
class backtrader.brokers.OandaBroker(**kwargs)
Broker implementation for Oanda.
This class maps the orders/positions from Oanda to the internal API of backtrader
.
Params:
-
use_positions
(default:True
): When connecting to the broker provider use the existing positions to kickstart the broker.Set to
False
during instantiation to disregard any existing position
OandaData
class backtrader.feeds.OandaData(**kwargs)
Oanda Data Feed.
Params:
-
qcheck
(default:0.5
)Time in seconds to wake up if no data is received to give a chance to resample/replay packets properly and pass notifications up the chain
-
historical
(default:False
)If set to
True
the data feed will stop after doing the first download of data.The standard data feed parameters
fromdate
andtodate
will be used as reference.The data feed will make multiple requests if the requested duration is larger than the one allowed by IB given the timeframe/compression chosen for the data.
-
backfill_start
(default:True
)Perform backfilling at the start. The maximum possible historical data will be fetched in a single request.
-
backfill
(default:True
)Perform backfilling after a disconnection/reconnection cycle. The gap duration will be used to download the smallest possible amount of data
-
backfill_from
(default:None
)An additional data source can be passed to do an initial layer of backfilling. Once the data source is depleted and if requested, backfilling from IB will take place. This is ideally meant to backfill from already stored sources like a file on disk, but not limited to.
-
bidask
(default:True
)If
True
, then the historical/backfilling requests will request bid/ask prices from the serverIf
False
, then midpoint will be requested -
useask
(default:False
)If
True
the ask part of the bidask prices will be used instead of the default use of bid -
includeFirst
(default:True
)Influence the delivery of the 1st bar of a historical/backfilling request by setting the parameter directly to the Oanda API calls
-
reconnect
(default:True
)Reconnect when network connection is down
-
reconnections
(default:-1
)Number of times to attempt reconnections:
-1
means forever -
reconntimeout
(default:5.0
)Time in seconds to wait in between reconnection attemps
This data feed supports only this mapping of timeframe
and compression
, which comply with the definitions in the OANDA API Developer’s Guid:
(TimeFrame.Seconds, 5): 'S5', (TimeFrame.Seconds, 10): 'S10', (TimeFrame.Seconds, 15): 'S15', (TimeFrame.Seconds, 30): 'S30', (TimeFrame.Minutes, 1): 'M1', (TimeFrame.Minutes, 2): 'M3', (TimeFrame.Minutes, 3): 'M3', (TimeFrame.Minutes, 4): 'M4', (TimeFrame.Minutes, 5): 'M5', (TimeFrame.Minutes, 10): 'M10', (TimeFrame.Minutes, 15): 'M15', (TimeFrame.Minutes, 30): 'M30', (TimeFrame.Minutes, 60): 'H1', (TimeFrame.Minutes, 120): 'H2', (TimeFrame.Minutes, 180): 'H3', (TimeFrame.Minutes, 240): 'H4', (TimeFrame.Minutes, 360): 'H6', (TimeFrame.Minutes, 480): 'H8', (TimeFrame.Days, 1): 'D', (TimeFrame.Weeks, 1): 'W', (TimeFrame.Months, 1): 'M',
Any other combination will be rejected