Skip to content

Instantly share code, notes, and snippets.

@qharlie
Last active May 15, 2019 15:26
Show Gist options
  • Save qharlie/93630eda214ed9533f8672c3d91c4aea to your computer and use it in GitHub Desktop.
Save qharlie/93630eda214ed9533f8672c3d91c4aea to your computer and use it in GitHub Desktop.
import backtrader as bt
from strategy import BaseStrategy
class SMAStrategy(BaseStrategy):
def __init__(self):
super().__init__()
self.sma_fast = bt.ind.ExponentialMovingAverage(period=10)
self.sma_slow = bt.ind.ExponentialMovingAverage(period=30)
self.crossover = bt.ind.CrossOver(self.sma_fast, self.sma_slow)
self.upday = bt.ind.UpDayBool()
self.stop_loss_percent = 0.01
def next(self):
# print('crossover={},close={},sma_short={},sma_long={}'.format(self.crossover[0], self.data.close[0],self.sma_short.sma[0],self.sma_long.sma[0]))
if self.position.size:
# current_stop_loss is now handled by trailing_stop_loss function
current_stop_loss = self.position.price + (self.position.price * -self.stop_loss_percent)
# if were a downward trend then we should probably sell
# but we're not were just going to hold onto it till we get a profit
if self.crossover[0] < 0 \
and self.data.tick_last > self.position.price:
super().sell('self.crossover[0] < 0 and self.data.tick_last > self.position.price')
if ( current_stop_loss > self.data.tick_last):
super().sell('current_stop_loss > self.data.tick_last')
# If a crossover signal is positive it means we have a crossover event
# We then check that the current price is greather than the 10 period average, if so we buy
elif self.crossover[0] > 0 and \
self.data.close[0] > self.sma_fast[0] and self.upday[0] > 0:
self.trailing_stop_loss_buy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment