Backtrader Community

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

    Yelloww

    @Yelloww

    1
    Reputation
    526
    Profile views
    11
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    Yelloww Unfollow Follow

    Best posts made by Yelloww

    • Difference between leverage and multi

      I have read through the page https://www.backtrader.com/docu/commission-schemes/commission-schemes.html? but I am not clear what is the difference between multi and leverage. Both seems to be multiplicator to apply to profit and loss calculations.

      Let's say I want to trade a futures contract, margin requirement is 5% of contract value and commission is fixed ratio 0.0001 of contract value. how to define the parameters in broker.setcommission(commission=?, margin=?, mult=20?,leverage=20?)

      Thanks for help!

      posted in General Code/Help
      Y
      Yelloww

    Latest posts made by Yelloww

    • RE: Save cerebro data to file for later plotting it on another computer

      @backtrader

      Sorry to re-open this old thread.

      I tried to dump and then load a cerebro object, then error occured when I plot this pickled cerebro.
      Here is my code

      with open('test.file','wb') as f:
         pickle.dump(cerebro,f,pickle.HIGHEST_PROTOCOL)
      

      Then in another script:

      with open('test.file','rb') as f:
         cere=pickle.load(f) 
      #no problem with loading, but plotting
      
      cere.plot()
      /home/rr/anaconda2/lib/python2.7/site-packages/matplotlib/__init__.py:1350: UserWarning:  This call to matplotlib.use() has no effect
      because the backend has already been chosen;
      matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
      or matplotlib.backends is imported for the first time.
      
        warnings.warn(_use_error_msg)
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/home/rr/anaconda2/lib/python2.7/site-packages/backtrader/cerebro.py", line 987, in plot
          for stratlist in self.runstrats:
      AttributeError: 'Cerebro' object has no attribute 'runstrats'
      
      

      I think its a typical attribute error explained here:http://stefaanlippens.net/python-pickling-and-dealing-with-attributeerror-module-object-has-no-attribute-thing.html

      But still I dont know how to fix it.

      Thanks for help!

      posted in General Code/Help
      Y
      Yelloww
    • Risk management methods? pause trading when a maximum loss is incurred?

      Hi all,

      I am wondering if I can pause trading for like 24 hours when a maximum loss is incurred in a day.
      I could check loss of the day in the next() method and then skip it, but is there a smarter way to do that?
      Thanks for help.

      posted in General Code/Help
      Y
      Yelloww
    • trailing stop order with trailamount=ATR

      I have followed the post Mixing Timeframes in Indicators to resample my minute data to get daily data and then calculate ATR from daily data. self.atr = btindic.ATR(self.datas[1], plot=True)

      Then I would like to implement stoptrail orders whose trailamount equaLs to current ATR value

      def next(self):
        current_atr = self.atr() #I unerstand self.atr() as a LineCoupler which fills the daily atr values with the latest value to make it minute frequency.  
        if buy:
          self.buy(exectype=bt.Order.StopTrail, trailamount=current_atr)
      

      I got error:

      if self.trailamount: TypeError: __nonezero__ should return boll or int, returned LineOwnOperations

      I suppose I should supply trailamount by an explicit numeric value, but how to get this value?

      Many thanks for help!

      posted in General Code/Help
      Y
      Yelloww
    • RE: Problem with creating a custom indicator

      @kazi I think you should use SimpleMovingAverage1(self.data, period=20) or SimpleMovingAverage1(self.datas[0], period=20)

      posted in General Code/Help
      Y
      Yelloww
    • How to implement dualthrust with backtrader

      Dualthrust is quite a simple idea, but I failed to implement it with backtrader.

      My first approach is use built-in indicators to form a dualthrust system.
      I tried backtrader.indicators.Lowest and Highest in an attempt to get the highest/lowest of the previous high/low/close prices. However, these indicator does not let you specify field (high, low, close). And I am not sure it is calculating highest/lowest in a rolling manner.

      2nd approach is to create a customized indicator class. Multiple questions here: data is not in pandas format, I dont even know how to get high/low prices for a specific period. In addition, I have 2 data timeframes, seconds and daily. Indicator only needs to be calculated daily, but I believe the "next" method in the indicator class will calculate it every second, which is inefficient.

      Can anyone tell me how to use built-in indicator to make up a dualthrust indicators? Or give me an example indicator class which just calculate in a daily basis the rolling maximum high price for a rolling window of N?

      Thank you.

      posted in General Code/Help
      Y
      Yelloww
    • RE: Question on trailing stop orders

      I post my own implementation of trail stop orders here. It may not be absolutely correct/optimum. Just for the reference of any one who are interested.

      There are 2 rules:

      1. position can be both long/short
      2. all new long/short orders must be executed successfully.

      '''

      def next(self):
          # need to go long
          if self.curr_buysell[0] > 0 and self.prev_buysell <= 0 and self.position.size <= 0:
              if self.position.size < 0:
                  self.close_short = self.close()  # close existing positions
                  self.close_short.addinfo(ordername="FLATSHORT")
                  self.log('FLATSHORT CREATE, size {}'.format(self.close_short.created.size))
                  self.cancel(self.stop_short)
              self.enter_long = self.buy()
              self.enter_long.addinfo(ordername="LONGENTER")
              self.log(
                  'LONGENTER CREATE, close price {}, size {}'.format(self.data.close[0], self.enter_long.created.size))
      
              self.stop_long = self.sell(exectype=self.p.stoptype, trailpercent=self.p.trailpercent)
              self.stop_long.addinfo(ordername="STOPLONG")
      
          # need to go short
          elif self.curr_buysell[0] < 0 and self.prev_buysell >= 0 and self.position.size >= 0:
              if self.position.size > 0:
                  self.close_long = self.close()  # close existing positions
                  self.close_long.addinfo(ordername="FLATLONG")
                  self.log('FLATLONG CREATE, size {}'.format(self.close_long.created.size))
                  self.cancel(self.stop_long)
              self.enter_short = self.sell()
              self.enter_short.addinfo(ordername="SHORTENTER")
              self.log(
                  'SHORTENTER CREATE, close price {}, size {}'.format(self.data.close[0], self.enter_short.created.size))
      
              self.stop_short = self.buy(exectype=self.p.stoptype, trailpercent=self.p.trailpercent)
              self.stop_short.addinfo(ordername="STOPSHORT")
      
          self.prev_buysell = self.curr_buysell[0]
      

      '''

      posted in General Code/Help
      Y
      Yelloww
    • RE: Percentage Margin for Futures

      broker.get_value() gives fund value. broker.get_cash() gives currently available cash.

      posted in General Code/Help
      Y
      Yelloww
    • Difference between leverage and multi

      I have read through the page https://www.backtrader.com/docu/commission-schemes/commission-schemes.html? but I am not clear what is the difference between multi and leverage. Both seems to be multiplicator to apply to profit and loss calculations.

      Let's say I want to trade a futures contract, margin requirement is 5% of contract value and commission is fixed ratio 0.0001 of contract value. how to define the parameters in broker.setcommission(commission=?, margin=?, mult=20?,leverage=20?)

      Thanks for help!

      posted in General Code/Help
      Y
      Yelloww
    • Question on cheat on open

      Hi,

      I have a longshort strategy. It decides whether to long/short based on today's close price and decide the order size based on tomorrow's open price. Sizer is AllInSizer.

      I tried to mimic the cheat-on-open.py sample https://www.backtrader.com/docu/cerebro/cheat-on-open/cheat-on-open.html but still, my order sizes are decided by previous close, not open price and I got insufficient margin.

      Here is code:

      '''

      def next(self):
          print('{} next, open {} close {}'.format(
              self.data.datetime.date(),
              self.data.open[0], self.data.close[0])
          )
      
          if self.cheating: #look at next_open()
              return
          self.operate()
      
      def next_open(self):
          if not self.cheating: #look at next()
              return
          #in cheating mode
          self.operate()
      
      def operate(self):
          # enter into positions
          if self.buysell[0]>0:
              if self.position.size<0: #close existing short position
                  self.close()
                  self.log('Close short, close price {}, size {}'.format(self.dataclose[0],self.order.created.size))
      
              if self.position.size<=0:# Enter into long.
                  self.order=self.buy()
                  self.log('BUY CREATE, close price {}, size {}'.format(self.dataclose[0], self.order.created.size))
                  
          if self.buysell[0]<0:
              if self.position.size >= 0:
                  self.close()
                  self.log('Close long, close price {}, size {}'.format(self.dataclose[0],self.order.created.size))
              if self.position.size >= 0:  # Enter into short.
                  self.order = self.sell()
                  self.log('SELL CREATE, close price {}, size {}'.format(self.dataclose[0], self.order.created.size))
      

      '''

      Below is part of the main program:

      '''

      cerebro = bt.Cerebro(stdstats= True,cheat_on_open=True)
      
      cerebro.addstrategy(teststrat,fastn = 5, slown=30)
      
      cerebro.adddata(data)
      
      cerebro.broker.setcash(1000000.0)
      
      cerebro.addsizer(bt.sizers.AllInSizer)
      
      cerebro.broker.setcommission(commission=1/10000)
      cerebro.broker.set_slippage_fixed(5)
      cerebro.run()
      

      '''

      Below are some of the output:

      '''
      2010-02-12 next, open 41257.33 close 41702.98
      2010-02-22 next, open 42979.95 close 42654.28
      2010-02-23 next, open 42302.9 close 43031.37
      2010-02-24, BUY CREATE, close price 43099.94, size 23.2018884481
      2010-02-24, Order Margin
      2010-02-24 next, open 42628.57 close 43099.94
      2010-02-25 next, open 43117.08 close 42302.9
      2010-02-26 next, open 42500.02 close 42568.58
      2010-03-01 next, open 43638.31 close 42449.72
      2010-03-02 next, open 42212.0 close 40913.04
      2010-03-03 next, open 41218.68 close 41227.17
      2010-03-04 next, open 41430.93 close 40284.78
      2010-03-05 next, open 40395.15 close 40785.69
      2010-03-08 next, open 41176.23 close 42110.12
      2010-03-09, Close long, close price 41651.66, size 23.2018884481
      2010-03-09, SELL CREATE, close price 41651.66, size -24.0086469543
      2010-03-09 Sell Executed at price 41858.91
      2010-03-09 next, open 41863.91 close 41651.66
      2010-03-10, Close short, close price 41694.11, size -24.0086469543
      2010-03-10, BUY CREATE, close price 41694.11, size 24.0086469543
      2010-03-10 Buy Executed at price 41283.11
      2010-03-10 Buy Executed at price 41283.11
      2010-03-10, OPERATION PROFIT, GROSS 13824.18, NET 13624.57
      2010-03-10 next, open 41278.11 close 41694.11
      2010-03-11 next, open 41745.05 close 40904.55
      2010-03-12 next, open 41108.31 close 40293.27
      2010-03-15 next, open 40293.27 close 38866.96
      2010-03-16, Close long, close price 39580.12, size 24.0086469543
      2010-03-16, SELL CREATE, close price 39580.12, size -24.0086469543
      2010-03-16 Sell Executed at price 38437.47
      2010-03-16 Sell Executed at price 38437.47
      2010-03-16, OPERATION PROFIT, GROSS -68319.97, NET -68511.36
      2010-03-16 next, open 38442.47 close 39580.12
      2010-03-17 next, open 39919.72 close 40547.97
      2010-03-18 next, open 40259.31 close 40174.41
      2010-03-19 next, open 40242.33 close 41091.33
      2010-03-22 next, open 40768.71 close 40760.22
      2010-03-23 next, open 40853.61 close 40004.62
      2010-03-24 next, open 40140.45 close 40327.23
      2010-03-25 next, open 40446.09 close 41897.87
      2010-03-26 next, open 42279.92 close 42203.51
      2010-03-29, Close short, close price 42373.31, size -24.0086469543
      2010-03-29, BUY CREATE, close price 42373.31, size 24.0086469543
      2010-03-29, Order Margin
      2010-03-29 Buy Executed at price 42590.56
      2010-03-29, OPERATION PROFIT, GROSS -99710.07, NET -99904.61
      '''

      My problem is twofold:

      1. according to "2010-02-24, BUY CREATE, close price 43099.94, size 23.2018884481
        2010-02-24, Order Margin
        2010-02-24 next, open 42628.57 close 43099.94" obviously, the program still uses that days' closed price to decide order size, even though I used cheap-on-open option.

      2. After a while the order sizes all became fixed at 24.0086469543, even though AllInSizer is used.
        I guess it's probably related to there are always 2 orders together, one is close the previous long/short, another one is open new short/long. Then size = available cash/price does not give me the right size. But I don't know exact the reason and solution.

      3. lastly, how to round size to an integer without define my own sizer function?

      Many thanks for any help.

      posted in General Code/Help
      Y
      Yelloww
    • Question on trailing stop orders

      Hi,

      in the example here , trail stop order is created as below
      '''

      def next(self):
          if not self.position:
              if self.crup:
                  o = self.buy()
                  self.order = None
                  print('*' * 50)
      
          elif self.order is None:
              if self.p.stoptype == bt.Order.StopTrailLimit:
                  price = self.data.close[0]
                  plimit = self.data.close[0] + self.p.limitoffset
              else:
                  price = None
                  plimit = None
      
              self.order = self.sell(exectype=self.p.stoptype,
                                     price=price,
                                     plimit=plimit,
                                     trailamount=self.p.trailamount,
                                     trailpercent=self.p.trailpercent)
      

      '''

      I have a few doubts.

      1. My understanding of the code: on day 1 new buy order created and 'self.order=None'. The next day, the buy order got executed at open and 'position.size>0', then create a 'StopTrailLimit' order. On day 3, if price reached a certain level, the StopTrailLimit order got executed. What If on day 2 stop price is already reached, there is no way to stop loss because the StopTrailLimit will only be executed on the next bar after creation (which is already day 3)?? What if you want stop loss immediately take effect after position is entered on day 2 at open.

      2. Suppose a StopTrailLimit is never executed and the original position has been closed. If later you want to enter into a new position, I think you have to cancel the existing StopTrailLimit order. Strangely, according to the sample code, if there is pending order (including StopTrailLimit), new buy cannot be created. StopTrailLimit does not die with the original position, but forbids creation of new position??

      I tried to implement stop trail orders on my own. The strategy is long short. Can someone tell me if the implementation is correct? Thank you!

      '''

       def next(self):
          # enter into positions
          if self.buysell>0:
              self.cancel() #cancel existing stop loss orders
              self.buy(exectype=bt.Order.Market) #enter into new position
              self.stop_long = 1 #indicates a new long is just entered, need to put a stop loss sell order
      
          elif self.buysell<0:
              self.cancel()
              self.buy(exectype=bt.Order.Market)
              self.stop_short = 1
      
          #create trailing stop loss orders
          elif self.stop_long == 1 and self.position.size>0:
              self.stop_long = self.sell(exectype=bt.Order.StopTrailLimit,
                                     trailpercent=self.p.trailpercent)
          elif self.stop_short == 1 and self.position.size<0:
              self.stop_short = self.buy(exectype=bt.Order.StopTrailLimit,
                                     trailpercent=self.p.trailpercent)
      

      '''

      posted in General Code/Help
      Y
      Yelloww