@backtrader said in self.buy(size=1.5) does not work:
Blog - Cheat On Open
ok, thanks for your reply , but still I still don't solve my problem. Here is my code below.
import backtrader as bt
import pandas as pd
from backtrader.indicators import CrossOver
from backtrader.indicators import CrossDown
from backtrader.order import Order
pd.set_option('expand_frame_repr',False)
pd.set_option('display.max_rows',10)
def resample(rule_type='15T'):
df = pd.read_hdf('/Users/Lins/Python/QuantTrade/BTDemo/program/BTCUSDT_1min_data.h5')
df['datetime'] = df['open_time']
df = df.resample(rule=rule_type,on='open_time',base=0,label='left',closed='left').agg({
'open':'first',
'close':'last',
'volume':'sum',
'high':'max',
'low':'min',
})
df['datetime'] = df.index
df = df[df['volume'] > 0]
return df
class ThreeDaysBreakoutIndicator(bt.Indicator):
lines=('up','down',)
def __init__(self):
self.addminperiod(4)
self.plotinfo.plotmaster = self.data
def next(self):
self.up[0] = max(max(self.data.open.get(ago=-1,size=3)), max(self.data.close.get(ago=-1,size=3)))
self.down[0] = min(min(self.data.open.get(ago=-1,size=3)),min(self.data.close.get(ago=-1,size=3)))
class ThreeDaysBreakoutStrategy(bt.Strategy):
def log(self,txt,dt=None):
""" Loging function for this Strategy"""
dt = dt or self.datas[0].datetime.date(0)
print("%s, %s" % (dt.isoformat(), txt))
def __init__(self):
self.up_down = ThreeDaysBreakoutIndicator(self.data)
self.buy_signal = CrossOver(self.data.close,self.up_down.up)
self.sell_signal = CrossDown(self.data.close,self.up_down.down)
def next(self):
# buy_price = self.data.close[0] * (1+0.002)
# sell_price = self.data.close[0] *(1-0.002)
# cash = self.broker.get_cash()
# size = cash/buy_price
# size = 1
# print("cash = %f , will buy price = %f size = %f" %(cash,buy_price,size))
if not self.position and self.buy_signal == 1:
self.order = self.buy()
if self.getposition().size > 0 and self.sell_signal == 1:
self.order = self.sell()
def notify_order(self,order):
if order.status in [order.Completed]:
if order.isbuy():
self.log("Buy executed = %f, volume = %f , position = %f" % (order.executed.price, order.executed.size,self.getposition().size))
elif order.issell():
self.log("Sell executed = %f, volume = %f, position = %f" % (order.executed.price, order.executed.size,self.getposition().size))
if __name__ == "__main__":
cerebro = bt.Cerebro(cheat_on_open=True)
cerebro.broker.set_cash(100000)
df = resample(rule_type='1D')
df = df[df.index > pd.to_datetime('20180601')]
data = bt.feeds.PandasData(dataname=df)
cerebro.broker.setcommission(commission=0.002)
# cerebro.broker.set_slippage_perc(perc=0.005)
# cerebro.broker.set_slippage_perc()
cerebro.adddata(data)
cerebro.addobserver(bt.observers.TimeReturn)
cerebro.addstrategy(ThreeDaysBreakoutStrategy)
# cerebro.addwriter(bt.WriterFile,csv=True,out='ThreeDaysBreakoutStrategy.csv')
print("The initial Cash = %.2f" %cerebro.broker.get_cash())
cerebro.run()
print("The final Cash = %.2f" % cerebro.broker.get_cash())
cerebro.plot(style='candle')
# here is the log for executing the code
"""
The initial Cash = 100000.00
2018-06-19, Buy executed = 6711.390000, volume = 1.000000 , position = 1.000000
2018-06-23, Sell executed = 6045.920000, volume = -1.000000, position = 0.000000
2018-07-01, Buy executed = 6391.080000, volume = 1.000000 , position = 1.000000
2018-07-11, Sell executed = 6296.910000, volume = -1.000000, position = 0.000000
2018-07-17, Buy executed = 6723.330000, volume = 1.000000 , position = 1.000000
2018-08-01, Sell executed = 7735.670000, volume = -1.000000, position = 0.000000
2018-08-17, Buy executed = 6316.000000, volume = 1.000000 , position = 1.000000
2018-08-21, Sell executed = 6251.000000, volume = -1.000000, position = 0.000000
2018-08-24, Buy executed = 6525.000000, volume = 1.000000 , position = 1.000000
2018-09-06, Sell executed = 6399.040000, volume = -1.000000, position = 0.000000
The final Cash = 99930.95
"""
You can see from the log that even if I have $10000, and the executed price = 6711.390000, my strategy only buy 1 BTC , how can I buy 1.49 ( 10000/6711.39 = 1.49BTC) . Thanks and best regards.