Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. sarah_james
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    S
    • Profile
    • Following 0
    • Followers 0
    • Topics 2
    • Posts 2
    • Best 0
    • Controversial 0
    • Groups 0

    sarah_james

    @sarah_james

    0
    Reputation
    3
    Profile views
    2
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    sarah_james Unfollow Follow

    Latest posts made by sarah_james

    • how to only buy a certain percentage of the account balance and sell the quantity bought

      Hi, I have spend a while looking in the forum but cannot find anything which clearly shows how to only buy a certain percentage and only sell the amount bought from that percentage.

      My account balance is $10,000 when buying I want to buy 5% worth, which will be $500 and when selling I want to sell the amount of shares I bought for that $500. e.g if I Bought 100 shares for $500, I want to then sell that 100 shares when it's time to sell

      posted in General Discussion
      S
      sarah_james
    • RSI and MACD combo

      Hi all, I am trying to backtest RSI and MACD indicator strategies together like below. However When running my test it never takes any trade and I have tried it with 700 symbols so far. I have also tried just with the MACD and RSI separately and same thing? any help will highly appreciated thank you

      import backtrader
      from datetime import datetime
      import pandas as pd
      from services.trader_service import TraderService
      import numpy,pprint
      from matplotlib import warnings
      #Create Strategy
      class MACD_RSI_TestStrategy(backtrader.Strategy):
         params = dict(
             fastperiod=12,  
             slowperiod=26, 
             signalperiod=9,
             rsi_period=14,
             rsi_lookback=5,
             rsi_under=20,
             rsi_over=80
         )
      
         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):
             self.movav= backtrader.talib.MACD(self.datas[0].close, fastperiod=self.params.fastperiod, slowperiod=self.params.slowperiod, signalperiod=self.params.signalperiod)
             self.rsi = backtrader.talib.RSI(self.datas[0].close,period=self.params.rsi_period)
             self.order = None
             self.macdabove = False
             self.dataclose = self.datas[0].close
      
         def notify_order(self, order):
             if order.status in [order.Submitted, order.Accepted]:
                 return 
             if order.status in [order.Completed]:
                 if order.isbuy():
                     self.log('BUY EXECUTED {}'.format(order.executed.price))
                 elif order.issell():
                     self.log('SELL EXECUTED {}'.format(order.executed.price))
      
                 self.bar_executed =len(self)
      
             self.order = None
      
         def next(self):
            
             if self.macdabove == False and self.movav.lines.macd[0] > self.movav.lines.macdsignal[0] and self.rsi.lines[0] < self.params.rsi_under:
                 self.macdabove = True
                 self.log(f'BUY CREATE, {self.dataclose[0]}')
                 self.order = self.buy()
             elif self.macdabove == True and self.position and self.rsi.lines[0] > self.params.rsi_over:
                 self.macdabove = False
                 self.log('SELL CREATE {}'.format(self.dataclose[0]))
                 self.order = self.close()
      
      if __name__ == '__main__':
         trading_pair = 'ETH/USDT'
         chartTime= ['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h']
         date_of_trade="2021-05-03T12:00:00"
         trader = TraderService()
         account_balance=1000
         for  interval in chartTime:
             colums = ['timestamp', 'open','high', 'low', 'close', 'volume']
             klines =  trader.exchange.fetch_ohlcv(trading_pair, timeframe=interval, limit=1500,since=trader.exchange.parse8601(date_of_trade))
             dataFrame = pd.DataFrame(klines, columns=colums)
             dataFrame["timestamp"] = [datetime.fromtimestamp(t/1000) for t in dataFrame["timestamp"]]
      
             data = backtrader.feeds.PandasDirectData(dataname=dataFrame, 
             datetime=dataFrame.columns.get_loc("timestamp")+1, 
                 open=dataFrame.columns.get_loc('open')+1, high=dataFrame.columns.get_loc('high')+1, low=dataFrame.columns.get_loc('low')+1, 
                 close=dataFrame.columns.get_loc('close')+1,volume=dataFrame.columns.get_loc('volume')+1,openinterest=-1)
      
             cerebro = backtrader.Cerebro()
             cerebro.broker.setcash(account_balance)
             cerebro.addsizer(backtrader.sizers.FixedSize, stake=10)
             cerebro.adddata(data)
             cerebro.addstrategy(MACD_RSI_TestStrategy)
             cerebro.broker.setcommission(commission=0.10)
             print(f'timeframe {interval}')
             print(f'Pair {trading_pair}')
             print('Starting Balance: %.2f' % cerebro.broker.getvalue())
             cerebro.run()
      
             print('Final Balance: %.2f' % cerebro.broker.getvalue())
      
      posted in Indicators/Strategies/Analyzers
      S
      sarah_james