gpt4 book ai didi

python - Backtrader : order created, 我希望订单立即执行(而不是第二天),该怎么做?

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:57 33 4
gpt4 key购买 nike

我对 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())

当我执行 print(self.order) 时,它将订单状态打印为“已提交”,1)我如何知道以什么价格以及何时执行?2)如何确保只有在最后一个订单(卖出)执行后才进入市场(买方)?谢谢!!

最佳答案

尝试在 def init(self): 代码块之后添加此内容

    def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return

# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))

self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))

self.bar_executed = len(self)

elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None

def notify_trade(self, trade):
if not trade.isclosed:
return

self.log('GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))

关于python - Backtrader : order created, 我希望订单立即执行(而不是第二天),该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54457556/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com