我对backtrader比较陌生,我不太了解它是如何工作的。我的代码非常简单,如下所示:
class TestStrategy(bt.Strategy):
params = (
('maperiod', 60),
)
def log(self, txt, dt=None):
''' Logging function for this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
self.data_cpa = self.datas[0].high
self.data_cpb = self.datas[0].low
self.order = None
self.buyprice = None
self.buycomm = None
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod)
def next(self):
# Simply log the closing price of the series from the reference
self.log('Close, %.8f' % self.dataclose[0])
if self.dataclose[0] >= self.sma[0]:
# BUY, BUY, BUY!!! (with all possible default parameters)
self.log('BUY CREATE, %.8f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy()
else:
if self.dataclose[0] <= self.sma[0]:
# SELL, SELL, SELL!!! (with all possible default parameters)
self.log('SELL CREATE, %.8f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell()
print(self.order)
if __name__ == '__main__':
# Create a cerebro entity
cerebro = bt.Cerebro()
# Add a strategy
cerebro.addstrategy(TestStrategy)
# retrieve the csv file
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, './datas/zrxeth_sample.txt')
# Create a Data Feed
data = bt.feeds.GenericCSVData(
dataname = datapath,
fromdate=datetime.datetime(2018, 9, 28),
todate=datetime.datetime(2018, 12, 3),
nullvalue=0.0,
dtformat=('%Y-%m-%d %H:%M:%S'),
datetime=0,
high=1,
low=2,
open=3,
close=4,
volume=5,
openinterest=-1
)
# Add the Data Feed to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(100.0)
# Print out the starting conditions
print('Starting Portfolio Value: %.8f' % cerebro.broker.getvalue())
# Run over everything
cerebro.run()
# Print out the final result
print('Final Portfolio Value: %.8f' % cerebro.broker.getvalue())
当我打印的时候(自我命令)它将订单状态打印为“已提交”, 1) 我怎么知道它是在什么价格和什么时候被执行的? 2) 我怎样才能确保它只在最后一个订单(卖出)执行之后才进入市场(买方)?谢谢!!在
尝试在definit(self):代码块之后添加此代码
相关问题 更多 >
编程相关推荐