Skip to content

Instantly share code, notes, and snippets.

@qharlie
Created May 15, 2019 14:19
Show Gist options
  • Save qharlie/911db49f719bc9355f5e169b3133e683 to your computer and use it in GitHub Desktop.
Save qharlie/911db49f719bc9355f5e169b3133e683 to your computer and use it in GitHub Desktop.
import backtrader as bt
import coloredlogs, logging
logger = logging.getLogger(__name__)
coloredlogs.install(fmt='%(name)s - %(levelname)s %(message)s', level='DEBUG')
class BaseStrategy(bt.Strategy):
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.date(0)
logger.info('%s, %s' % (dt.isoformat(), txt))
def trailing_stop_loss_buy(self, trailamount=0.1):
# self.buy()
self.order = self.buy(exectype=bt.Order.StopTrail, trailamount=trailamount)
return self.order
def __init__(self):
self.dataclose = self.datas[0].close
self.order = None
self.buyprice = None
self.buycomm = None
self.sell_message = ''
def sell(self,msg='',**kwargs):
self.sell_message = msg
super().sell(**kwargs)
self.order = None
def notify_order(self, order):
dt = '{}:{}'.format(self.datas[0].datetime.date(0), self.datas[0].datetime.time(0))
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
logger.debug(' {}, Buying {} at Price: {}, Cost: {}, Comm: {}'.format(dt,self.data._name, order.executed.price,order.executed.value,order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
logger.error(' {}, Selling {} at Price: {}, Cost: {}, Comm: {} - {} '.format(dt,self.data._name, order.executed.price,order.executed.value,order.executed.comm,self.sell_message))
# 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')
# Write down: no pending order
self.order = None
def notify_trade(self, trade):
dt = '{}:{}'.format(self.datas[0].datetime.date(0), self.datas[0].datetime.time(0))
if not trade.isclosed:
return
if (trade.pnlcomm < 0):
logger.error(
'{},{},{} - {}'.format(dt, self.data._name, trade.pnlcomm,self.sell_message))
else:
logger.debug(
'{},{},{} - {}'.format(dt, self.data._name, trade.pnlcomm,self.sell_message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment