Backtrader Community

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

    t3chap

    @t3chap

    3
    Reputation
    99
    Profile views
    8
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    t3chap Unfollow Follow

    Best posts made by t3chap

    • RE: How to extract historical account value from backtrader or its results

      @run-out said in How to extract historical account value from backtrader or its results:

      Dictionary

      dictionary = results[0].analyzers.getbyname("cash_market").get_analysis()
      df = pd.DataFrame(dictionary).T
      df.columns = ["Date", "Cash", "Value"]
      

      It works, thank you so much.

      I guess the system double_unders can't be reached from outside of the object

      posted in Indicators/Strategies/Analyzers
      T
      t3chap

    Latest posts made by t3chap

    • RE: Cannot fetch IB future/stock data

      @jin-lin Did you ever figure this out? I have the same problem, I'm wondering if something changed with IBTWS that breaks the IbPy package or something like that.

      posted in Indicators/Strategies/Analyzers
      T
      t3chap
    • reducing cash in the account seemingly not working

      I have a trading bot using Oanda that I'm trying to get working. Oanda for the pair that I'm considering using 50x leverage, and I want to reduce this to 5. The easiest way that I've though of is to reduce the cash available to the system to the actual trading results achievable on oanda will be simulated by backtrader. Essentially I want to remove cash from the broker and add it to the fund, making a backup account that is used to adjust the size of the actual account I'm using for trading calculations.

      As the first step to implementing this, I use the following code:

          def nextstart(self):
              des_leverage = 5
              act_leverage = 50
              starting_cash = self.broker.get_cash()
              use_cash = starting_cash * des_leverage / act_leverage
              adjustment = use_cash - starting_cash
              self.broker.add_cash(adjustment)
              current_cash = self.broker.get_cash()
              print('starting cash:$ {}' . format(starting_cash))
              print('desired cash due to leverage:$ {}' . format(use_cash))
              print('adjustment: $ {}' . format(adjustment))
              print('current cash: $ {}' . format(current_cash))
      

      The results are below. I haven't implemented the adding the subtracted money to the fund, but it doesn't look like my add_cash is working. Any ideas?

      starting cash:$ 1000.0
      desired cash due to leverage:$ 100.0
      adjustment: $ -900.0
      current cash: $ 1000.0
      

      Thanks.

      posted in General Code/Help
      T
      t3chap
    • Exiting trades due to margin closeout

      Am I correct in assuming that backtrader doesn't exit trades when a margin call would have happened? I have a system I'm testing in forex which can be highly leveraged but I want to use a lesser amount. I've set the leverage to 4 (from 50 that is available at many forex outlets) but I'm not able to see that any trades have been exited for a margin exceedance if the market goes against the trade and the account value falls below the required amount for leverage.

      It appears that new trades are rejected due to margin if there is insufficient money in the trading account, but I don't see where existing trades are exited due to margin.

      I haven't seen this explicitly stated in the documentation yet but I might have missed it.

      Thanks.

      posted in General Discussion
      T
      t3chap
    • RE: How to extract historical account value from backtrader or its results

      @run-out said in How to extract historical account value from backtrader or its results:

      Dictionary

      dictionary = results[0].analyzers.getbyname("cash_market").get_analysis()
      df = pd.DataFrame(dictionary).T
      df.columns = ["Date", "Cash", "Value"]
      

      It works, thank you so much.

      I guess the system double_unders can't be reached from outside of the object

      posted in Indicators/Strategies/Analyzers
      T
      t3chap
    • How to extract historical account value from backtrader or its results

      I know this should be fairly easy to do but I'm stumped. I want to get the account value by bar from a cerebro instance so I can do analysis on a spreadsheet.

      For some reason I can't seem to figure out how to make this happen. I have this observer:

      class AcctValue(bt.Observer):
          alias = ('Value',)
          lines = ('value',)
       
          plotinfo = {"plot": True, "subplot": True}
       
          def next(self):
              self.lines.value[0] = self._owner.broker.getvalue()    # Get today's account value (cash + stocks)
       
      

      which I call with this code block:

      # Create an instance of cerebro
      cerebro = bt.Cerebro()
      # Input a starting broker account value
      cerebro.broker.setcash(startcash)
      
      
      # Add our strategy
      cerebro.addstrategy(Boll)
      
      
       
      comminfo = forexSpreadCommisionScheme(spread = spread, leverage = leverage)
      comminfo.show_spread_leverage()
      cerebro.broker.addcommissioninfo(comminfo)
       
      # Add the data to Cerebro
      cerebro.adddata(data)
       
      # Add a sizer
      
      cerebro.addsizer(ForexSizer,risk_per_trade=.0025,ATR_mult=6)
      
      #cerebro.addobserver(OrderObserver) 
      cerebro.addobserver(AcctValue)
      cerebro.addobservermulti(bt.observers.BuySell, markersize=4.0)    # Plots up/down arrows
      
      
      # Add the analyzers we are interested in
      #cerebro.addanalyzer(bt.analyzers.GrossLeverage, _name="gl")
      cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
      cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
      cerebro.addanalyzer(bt.analyzers.Returns, _name="ret")
      cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='mysharpe')
      cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='ann')
      cerebro.addanalyzer(bt.analyzers.DrawDown, _name='dd')   
      cerebro.addanalyzer(bt.analyzers.Transactions, _name = 'transactions')
      #cerebro.addanalyzer(AcctStats)
      
      # Run over everything
      strategies = cerebro.run()
      
      firstStrat = strategies[0]
      result=strategies[0]
      
       
      #Get final portfolio Value
      portvalue = cerebro.broker.getvalue()
      pnl = portvalue - startcash
       
      #Print out the final result
      print('Final Portfolio Value: ${}'.format(round(portvalue,2)))
      print('P/L: ${}'.format(round(pnl,2)))
      printSharpe(firstStrat.analyzers.mysharpe.get_analysis())
      printTradeAnalysis(firstStrat.analyzers.ta.get_analysis())
      printSQN(firstStrat.analyzers.sqn.get_analysis())
      printAnnualReturns(result.analyzers.ann.get_analysis())
      printReturns(result.analyzers.ret.get_analysis())
      printDD(result.analyzers.dd.get_analysis())
      

      using

      b= cerebro.Observer.AccountValue()
      b
      

      doesn't work.
      When I look at the vars(result) I see:
      <main.AcctValue at 0x7f931b97a610>
      but I don't know how to access this.

      Can anyone help me?

      posted in Indicators/Strategies/Analyzers
      T
      t3chap
    • How to build a sizer that can use some measure of volatility, like ATR, and the multiplier for the future to determine position sizing?

      The following is my attempt to make a custom position sizer based on ATR and the multiplier for the given future. I'm sure this is relatively easy but I seem to have hit a wall.

      I seem to have a position size of 0 for every trade.
      What am I getting wrong?

      Thanks.

      class comm_sizer(bt.Sizer):
          def __init__(self, atr):
              #self.atr_parameter= atr_parameter
              atr= self.atr
              risk_per_trade=5000
              atr_risk_per_trade=5
              
              sizing = math.floor((risk_per_trade/(mult*atr_risk_per_trade*atr)))
              
         # position = self.broker.getposition(data)
          
          def _getsizing(self,comminfo,cash,data,isbuy):
              
              return sizing
      
      posted in General Code/Help
      T
      t3chap
    • How to check for open orders by symbol, or how to cancel all orders for a given symbol/stock?

      I have a system where I enter a long position and simultaneously enter a protective stop. I have a separate exit that sometimes occurs. When this occurs, I'd like to be able to cancel the protective stop. I currently use more than one instrument, (currently looking at a basket of 5 stocks), so I'd like to either find a way to determine which orders are still open by symbol or cancel all open orders by symbol.
      After looking through the documentation I believe this should be possible but I can't seem to get it to work.
      Does anyone have any ideas?

      Thanks.

      posted in General Code/Help
      T
      t3chap