Created
June 21, 2024 08:24
-
-
Save ChadThackray/98a80a3d147c5bba18608489c07c3096 to your computer and use it in GitHub Desktop.
Translating a Tradingview strategy to Backtrader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Licensed under the MIT License. See comment below for full licence information. | |
import backtrader as bt | |
from datetime import datetime | |
class SwingTrade(bt.SignalStrategy): | |
params = (("closeThreshold",3),) | |
def __init__(self): | |
self.sma1 = bt.ind.SMA(period = 1400) | |
def next(self): | |
weekday =self.data.datetime.date().isoweekday() | |
if self.data.close[0] < (self.sma1[0]*1.1) and weekday == 1: | |
self.buy() | |
self.params.closeThreshold = 3 | |
print(f"Buy 1 BTC for {self.data.close[0]}") | |
if self.data.close[0] > (self.sma1[0]* self.params.closeThreshold) and self.position.size > 0: | |
self.close(size = 1) | |
self.params.closeThreshold += 1 | |
print(f"Sold 1 BTC for {self.data.close[0]}") | |
class SmaCross(bt.SignalStrategy): | |
def __init__(self): | |
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30) | |
crossover = bt.ind.CrossOver(sma1, sma2) | |
self.signal_add(bt.SIGNAL_LONG, crossover) | |
cerebro = bt.Cerebro() | |
cerebro.addstrategy(SwingTrade) | |
#cerebro.addstrategy(SmaCross) | |
data0 = bt.feeds.GenericCSVData( | |
dataname = "btc.csv", | |
fromdate = datetime(2011,1,1), | |
todate = datetime(2021,8,1), | |
datetime = 0, | |
open = 1, | |
high = 1, | |
close = 1, | |
low = 1, | |
volume = -1, | |
openinterest = -1, | |
dtformat ="%Y-%m-%d") | |
cerebro.adddata(data0) | |
cerebro.broker.setcash(10000) | |
cerebro.addsizer(bt.sizers.SizerFix, stake=1) | |
cerebro.run() | |
cerebro.plot(volume = False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is some data you can use, save it as
btc.csv