Navigation

    Backtrader Community

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

    derek2017

    @derek2017

    4
    Reputation
    433
    Profile views
    12
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    derek2017 Unfollow Follow

    Best posts made by derek2017

    • RE: Can observer output text/characters in lines?

      @backtrader

      Many thanks for the advice, I solved the problem using the method you provided!

      
      # https://www.backtrader.com/docu/observers-and-statistics/observers-and-statistics.html
      class OrderObserver(bt.observer.Observer):
      
          lines = ('ref0', 'createdPrice0', 'createdSize0', 'executedPrice0', 'executedValue0', 'Comm0',
                   'ref1', 'createdPrice1', 'createdSize1', 'executedPrice1', 'executedValue1', 'Comm1',)
      
          plotinfo = dict(plot=False, subplot=False, plotlinelabels=False)
      
          def next(self):
      
              results = []
              for order in self._owner._orderspending:
                  # if order.data is not self.data:
                  #     continue
                  if order.status in [bt.Order.Completed]:
                      results.append([
                          order.ref,
                          order.created.price,
                          order.created.size,
                          order.executed.price,
                          order.executed.value,
                          order.executed.comm
                          ])
      
              if len(results) > 0:  # orders are available
                  self.lines.ref0[0] = results[0][0]
                  self.lines.createdPrice0[0] = results[0][1]
                  self.lines.createdSize0[0] = results[0][2]
                  self.lines.executedPrice0[0] = results[0][3]
                  self.lines.executedValue0[0] = results[0][4]
                  self.lines.Comm0[0] = results[0][5]
                  self.lines.ref1[0] = results[1][0]
                  self.lines.createdPrice1[0] = results[1][1]
                  self.lines.createdSize1[0] = results[1][2]
                  self.lines.executedPrice1[0] = results[1][3]
                  self.lines.executedValue1[0] = results[1][4]
                  self.lines.Comm1[0] = results[1][5]
      
      
      posted in General Code/Help
      D
      derek2017
    • RE: Can observer output text/characters in lines?

      @ab_trader

      I use this for a pair trading strategy, so i output the order content for both stocks.

      OrderObserver	len	ref0	createdPrice0	createdSize0	executedPrice0	executedValue0	Comm0	ref1	createdPrice1	createdSize1	executedPrice1	executedValue1	Comm1
      OrderObserver	128												
      OrderObserver	129												
      OrderObserver	130												
      OrderObserver	131	1	85.770005	-58	85.610001	-4965.380058	0	2	76.419999	65	76.809998	4992.64987	0
      OrderObserver	132												
      OrderObserver	133												
      OrderObserver	134												
      OrderObserver	17												
      
      
      posted in General Code/Help
      D
      derek2017
    • Margin Order - why it's triggered?

      Hi,

      If multiple orders are placed on the same day and the orders are mix of buy and sell (not short, just sell part of existing stocks), will the sell orders get rejected due to margin ?

      I suppose reducing the position should not trigger any margin requirements, however during backtesting, I have seen my orders got rejected due to margin.

      In below case, Order Ref 22 got rejected due to margin, which is to reduce position from 1860 to 1643.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE BUY: CH600827, Close: 15.520001, Oref: 20
      2017-02-14, CREATE BUY: CH601628, Close: 26.570008, Oref: 21
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 22
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, Order Margin, Ref: 20, Name: CH600827
      2017-02-15, Order Margin, Ref: 21, Name: CH601628
      2017-02-15, Order Margin, Ref: 22, Name: CH000630
      

      I manually skip the buy orders on 2017-2-14 (everything else remain the same), leaving only rebalance orders, now the sell order got accepted.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 20
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, SELL EXECUTED, Ref: 20, Name: CH000630, Price: 3.49, Cost: 720.44, Size: -217.00, Comm 1.51
      

      It seems the order of Order matters.
      I made changes to the code and issue rebalance orders prior to buy orders. Strangely now the sell order got executed.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 20
      2017-02-14, CREATE BUY: CH600827, Close: 15.520001, Oref: 21
      2017-02-14, CREATE BUY: CH601628, Close: 26.570008, Oref: 22
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, Order Margin, Ref: 21, Name: CH600827
      2017-02-15, Order Margin, Ref: 22, Name: CH601628
      2017-02-15, SELL EXECUTED, Ref: 20, Name: CH000630, Price: 3.49, Cost: 720.44, Size: -217.00, Comm 1.51
      
      

      Could you please advise if this is expected behavior of backtrader? how the margin works internally? Thanks.

      posted in General Code/Help
      D
      derek2017

    Latest posts made by derek2017

    • Margin Order - why it's triggered?

      Hi,

      If multiple orders are placed on the same day and the orders are mix of buy and sell (not short, just sell part of existing stocks), will the sell orders get rejected due to margin ?

      I suppose reducing the position should not trigger any margin requirements, however during backtesting, I have seen my orders got rejected due to margin.

      In below case, Order Ref 22 got rejected due to margin, which is to reduce position from 1860 to 1643.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE BUY: CH600827, Close: 15.520001, Oref: 20
      2017-02-14, CREATE BUY: CH601628, Close: 26.570008, Oref: 21
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 22
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, Order Margin, Ref: 20, Name: CH600827
      2017-02-15, Order Margin, Ref: 21, Name: CH601628
      2017-02-15, Order Margin, Ref: 22, Name: CH000630
      

      I manually skip the buy orders on 2017-2-14 (everything else remain the same), leaving only rebalance orders, now the sell order got accepted.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 20
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, SELL EXECUTED, Ref: 20, Name: CH000630, Price: 3.49, Cost: 720.44, Size: -217.00, Comm 1.51
      

      It seems the order of Order matters.
      I made changes to the code and issue rebalance orders prior to buy orders. Strangely now the sell order got executed.

      2017-02-14, CREATE BUY REBALANCE: CH600028, Close: 5.840000, Old Position: 1316 New Position 1516 Oref: 19
      2017-02-14, CREATE SELL REBALANCE: CH000630, Close: 3.560000, Old Position: 1860 New Position 1643 Oref: 20
      2017-02-14, CREATE BUY: CH600827, Close: 15.520001, Oref: 21
      2017-02-14, CREATE BUY: CH601628, Close: 26.570008, Oref: 22
      2017-02-15, Order Margin, Ref: 19, Name: CH600028
      2017-02-15, Order Margin, Ref: 21, Name: CH600827
      2017-02-15, Order Margin, Ref: 22, Name: CH601628
      2017-02-15, SELL EXECUTED, Ref: 20, Name: CH000630, Price: 3.49, Cost: 720.44, Size: -217.00, Comm 1.51
      
      

      Could you please advise if this is expected behavior of backtrader? how the margin works internally? Thanks.

      posted in General Code/Help
      D
      derek2017
    • RE: How to automate the running of backtrader?

      @Maxim Korobov

      Many thanks for the suggestion, i will take a look!

      posted in General Discussion
      D
      derek2017
    • RE: GenericCSVData Data Issue - dates off by one day in Excel

      @backtrader

      Thanks for the reply!

      252,orcl-2014,252,2014-12-31 23:59:59.999989,45.45,45.56,44.97,44.97,13269200.0,0.0,TestStrategy,252,735598.9999999999,Broker,252,100000.0,100000.0,BuySell,252,,,Trades,252,,,DrawDown,252,0.0,0.0,TimeReturn,252,0.0
      

      Actually the output in question is generated by Writer cerebro.addwriter(bt.WriterFile, csv=True).

      So my question is how can I get a date-only print out when using writer?
      Thanks!

      posted in General Code/Help
      D
      derek2017
    • GenericCSVData Data Issue - dates off by one day in Excel

      Hi,

      I have a strange issue using GenericCSVData.

      As you can see, in orc-2014.txt, the dates start from 2014-1-1 till 2014-12-31.

      orcl-2014.txt

      2014-12-22,45.57,46.05,45.41,45.65,21264400,45.53
      2014-12-23,45.53,46.50,45.46,46.01,14042400,45.89
      2014-12-24,46.36,46.71,46.15,46.23,10238200,46.10
      2014-12-26,46.19,46.50,46.07,46.10,6893500,45.98
      2014-12-29,46.02,46.09,45.60,45.61,9701400,45.49
      2014-12-30,45.55,45.66,45.29,45.34,9968400,45.22
      2014-12-31,45.45,45.56,44.97,44.97,13269200,44.85
      

      Below is taken from the tutorial:

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      import datetime  # For datetime objects
      import os.path  # To manage paths
      import sys  # To find out the script name (in argv[0])
      
      # Import the backtrader platform
      import backtrader as bt
      
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              dt = dt or self.datas[0].datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
              # To keep track of pending orders
              self.order = None
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
      
              # Check if an order has been completed
              # Attention: broker could reject order if not enougth cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log('BUY EXECUTED, %.2f' % order.executed.price)
                  elif order.issell():
                      self.log('SELL EXECUTED, %.2f' % order.executed.price)
      
                  self.bar_executed = len(self)
      
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
      
              # Write down: no pending order
              self.order = None
      
          def next(self):
              # Simply log the closing price of the series from the reference
              # self.log('Close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
      
      if __name__ == '__main__':
          # Create a cerebro entity
          cerebro = bt.Cerebro()
      
          # Add a strategy
          cerebro.addstrategy(TestStrategy)
          cerebro.addobserver(bt.observers.DrawDown)
          cerebro.addobserver(bt.observers.TimeReturn)
      
          # Datas are in a subfolder of the samples. Need to find where the script is
          # because it could have been called from anywhere
          data = bt.feeds.GenericCSVData(
              dataname='datas/orcl-2014.txt',
              nullvalue=0.0,
              dtformat=('%Y-%m-%d'),
              datetime=0,
              time=-1,
              high=2,
              low=3,
              open=1,
              close=4,
              volume=5,
              openinterest=-1)
      
          # Add the Data Feed to Cerebro
          cerebro.adddata(data)
      
          # Set our desired cash start
          cerebro.broker.setcash(100000.0)
          cerebro.addwriter(bt.WriterFile, csv=True)
      
          # Print out the starting conditions
          print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
          # Run over everything
          cerebro.run()
      
          # Print out the final result
          print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      

      Output shown in terminal:

      249,orcl-2014,249,2014-12-26 23:59:59.999989,46.19,46.5,46.07,46.1,6893500.0,0.0,TestStrategy,249,735593.9999999999,Broker,249,100000.0,100000.0,BuySell,249,,,Trades,249,,,DrawDown,249,0.0,0.0,TimeReturn,249,0.0
      2014-12-29, Close, 45.61
      250,orcl-2014,250,2014-12-29 23:59:59.999989,46.02,46.09,45.6,45.61,9701400.0,0.0,TestStrategy,250,735596.9999999999,Broker,250,100000.0,100000.0,BuySell,250,,,Trades,250,,,DrawDown,250,0.0,0.0,TimeReturn,250,0.0
      2014-12-30, Close, 45.34
      251,orcl-2014,251,2014-12-30 23:59:59.999989,45.55,45.66,45.29,45.34,9968400.0,0.0,TestStrategy,251,735597.9999999999,Broker,251,100000.0,100000.0,BuySell,251,,,Trades,251,,,DrawDown,251,0.0,0.0,TimeReturn,251,0.0
      2014-12-31, Close, 44.97
      252,orcl-2014,252,2014-12-31 23:59:59.999989,45.45,45.56,44.97,44.97,13269200.0,0.0,TestStrategy,252,735598.9999999999,Broker,252,100000.0,100000.0,BuySell,252,,,Trades,252,,,DrawDown,252,0.0,0.0,TimeReturn,252,0.0
      

      output show in excel

      249	orcl-2014	249	2014-12-27	46.19	46.5	46.07	46.1	6893500	0	TestStrategy	249	735594	Broker	249	100000	100000
      250	orcl-2014	250	2014-12-30	46.02	46.09	45.6	45.61	9701400	0	TestStrategy	250	735597	Broker	250	100000	100000
      251	orcl-2014	251	2014-12-31	45.55	45.66	45.29	45.34	9968400	0	TestStrategy	251	735598	Broker	251	100000	100000
      252	orcl-2014	252	2015-1-1	 45.45	45.56	44.97	44.97	13269200	0	TestStrategy	252	735599	Broker	252	100000	100000
      

      The issue is when i open the results in Excel, date for the last row is showing as 2015-1-1(it should be 2014-12-31 as shown in the source). Actually all the dates are off by one day.

      I guess this is because the date 2014-12-31 was changed to 2014-12-31 23:59:59.999989 , and Excel automatically convert it to 2015-1-1.

      So why the time 23:59:59.999989 was added? Is it possible to add 00:00:00 instead?

      Thanks.

      posted in General Code/Help
      D
      derek2017
    • RE: How to automate the running of backtrader?

      @backtrader

      Many thanks for the prompt reply! I see what you mean, i will try this out.

      posted in General Discussion
      D
      derek2017
    • How to automate the running of backtrader?

      Hello @backtrader ,

      I'd like to automate the running of backtrader in below scenario, may i know if you have any suggestions on how to achieve this?

      Suppose i have a csv file which looks like this, basically the csv file has three stock paris.

      Stock0	Stock1
      IBM	AAPl
      IBM	FB
      IBM	GOOG
      
      1. Read the csv file which contains the list of stock pairs,
      2. Take the first pair (IBM and AAPL), and feed the codes(IBM, AAPL) into my strategy,
      3. My strategy loads data for IBM and AAPL, runs and finish,
      4. Take the second pair(IBM and FB), and feed the codes(IBM, FB) into my strategy,
      5. My strategy loads data for IBM and FB, runs and finish
        ....
        Till all the stock pairs are used to run my strategy.

      Currently i am just running several files which has same strategy but different data. However it would be great if this can be achieved because the list of pairs could be very large.

      My confusion is how best to construct this loop on top of backtrader.
      This article is helpful, but doesn't address this case.

      Thank!

      posted in General Discussion
      D
      derek2017
    • RE: Can observer output text/characters in lines?

      @ab_trader

      I use this for a pair trading strategy, so i output the order content for both stocks.

      OrderObserver	len	ref0	createdPrice0	createdSize0	executedPrice0	executedValue0	Comm0	ref1	createdPrice1	createdSize1	executedPrice1	executedValue1	Comm1
      OrderObserver	128												
      OrderObserver	129												
      OrderObserver	130												
      OrderObserver	131	1	85.770005	-58	85.610001	-4965.380058	0	2	76.419999	65	76.809998	4992.64987	0
      OrderObserver	132												
      OrderObserver	133												
      OrderObserver	134												
      OrderObserver	17												
      
      
      posted in General Code/Help
      D
      derek2017
    • RE: Can observer output text/characters in lines?

      @backtrader

      Many thanks for the advice, I solved the problem using the method you provided!

      
      # https://www.backtrader.com/docu/observers-and-statistics/observers-and-statistics.html
      class OrderObserver(bt.observer.Observer):
      
          lines = ('ref0', 'createdPrice0', 'createdSize0', 'executedPrice0', 'executedValue0', 'Comm0',
                   'ref1', 'createdPrice1', 'createdSize1', 'executedPrice1', 'executedValue1', 'Comm1',)
      
          plotinfo = dict(plot=False, subplot=False, plotlinelabels=False)
      
          def next(self):
      
              results = []
              for order in self._owner._orderspending:
                  # if order.data is not self.data:
                  #     continue
                  if order.status in [bt.Order.Completed]:
                      results.append([
                          order.ref,
                          order.created.price,
                          order.created.size,
                          order.executed.price,
                          order.executed.value,
                          order.executed.comm
                          ])
      
              if len(results) > 0:  # orders are available
                  self.lines.ref0[0] = results[0][0]
                  self.lines.createdPrice0[0] = results[0][1]
                  self.lines.createdSize0[0] = results[0][2]
                  self.lines.executedPrice0[0] = results[0][3]
                  self.lines.executedValue0[0] = results[0][4]
                  self.lines.Comm0[0] = results[0][5]
                  self.lines.ref1[0] = results[1][0]
                  self.lines.createdPrice1[0] = results[1][1]
                  self.lines.createdSize1[0] = results[1][2]
                  self.lines.executedPrice1[0] = results[1][3]
                  self.lines.executedValue1[0] = results[1][4]
                  self.lines.Comm1[0] = results[1][5]
      
      
      posted in General Code/Help
      D
      derek2017
    • RE: Can observer output text/characters in lines?

      @backtrader Thanks for the prompt reply!

      I am not trying to plot text label in chart, actually I want to add an additional column to the csv file produced by adding cerebro.addwriter(bt.WriterFile, csv=True) to my strategy.

      I noticed all the pricing data / observers / indicators are included in the csv file automatically, which is quite helpful to understand what's going on behind the hood and is useful to verify the backtesting results.

      But I find it a difficult to output orders/trade details. I understand i can write out orders/traders using notify_order and notify_trade functions, however the output text from these function are not aligned with other columns.

      To give an example, Below is the output(partial results) from the writer, from line 130 to line 131 are the text I'd like to add to a new column so that they don't take a new line.

      Current results:

      130	U74271810	130	2016-7-8 0:00	84.979996	85.899994	84.770005	85.770005	6827348	6827348	U92826C83	130	2016-7-8 0:00
      BACKTRADER - ORDER: OrderId: 1 Stock: stock1 Action: SELL CreatePrice: 85.77 CreateSize:-58 ExecutePrice: 85.61 Cost: -4965.38 Comm: 0.00                          												
      BACKTRADER - ORDER: OrderId: 2 Stock: stock2 Action: BUY CreatePrice: 76.42 CreateSize:65 ExecutePrice: 76.81 Cost: 4992.65 Comm: 0.00                          												
      131	U74271810	131	2016-7-11 0:00	85.610001	85.949997	84.910004	85.75	6156824	6156824	U92826C83	131	2016-7-11 0:00
      132	U74271810	132	2016-7-12 0:00	85.490006	85.940003	85.190003	85.75	6649848	6649848	U92826C83	132	2016-7-12 0:00
      133	U74271810	133	2016-7-13 0:00	85.809998	86.149994	85.410004	85.89	7572149	7572149	U92826C83	133	2016-7-13 0:00
      
      

      intended results

      130	U74271810	130	2016-7-8 0:00	84.979996	85.899994	84.770005	85.770005	6827348	6827348	U92826C83	130	2016-7-8 0:00	BACKTRADER - ORDER: OrderId: 1 Stock: stock1 Action: SELL CreatePrice: 85.77 CreateSize:-58 ExecutePrice: 85.61 Cost: -4965.38 Comm: 0.00                          	BACKTRADER - ORDER: OrderId: 2 Stock: stock2 Action: BUY CreatePrice: 76.42 CreateSize:65 ExecutePrice: 76.81 Cost: 4992.65 Comm: 0.00                          												
      131	U74271810	131	2016-7-11 0:00	85.610001	85.949997	84.910004	85.75	6156824	6156824	U92826C83	131	2016-7-11 0:00	76.809998	77.192002
      
      

      Below is the observer I used to output the "Backtrader..." line.

      class OrderObserver(bt.observer.Observer):
          lines = ('created', 'expired',)
      
          plotinfo = dict(plot=False, subplot=False, plotlinelabels=False)
      
          plotlines = dict(
              created=dict(marker='*', markersize=8.0, color='lime', fillstyle='full'),
              expired=dict(marker='s', markersize=8.0, color='red', fillstyle='full')
          )
      
          def next(self):
              results = []
              for order in self._owner._orderspending:
                  # if order.data is not self.data:
                  #     continue
                  if order.status in [bt.Order.Completed]:
                      content = '''BACKTRADER - ORDER: OrderId: %s Stock: %s Action: %s CreatePrice: %.2f CreateSize:%s ExecutePrice: %.2f Cost: %.2f Comm: %.2f
                                ''' % (  order.ref,
                                         order.info['addinfo']['stock'],
                                         order.info['addinfo']['buysell'],
                                         order.created.price,
                                         order.created.size,
                                         order.executed.price,
                                         order.executed.value,
                                         order.executed.comm
                            )
                      content = content.replace('\n', '')
                      results.append(content)
                      print(content)
      
      
      posted in General Code/Help
      D
      derek2017
    • Can observer output text/characters in lines?

      Hello,

      Thanks again for creating this wonderful tool. I have a question regarding observer.

      Below code taken from https://www.backtrader.com/docu/observers-and-statistics/observers-and-statistics.html.

      For example, instead of settingself.lines.created[0] to order.created.price, is it possible to set self.lines.created[0] with some text? Reason being I want to create some descriptions in the output, i.e Bought xx stock at xx price for xx amount and output this in the writer alone with other information.

      When i tried to set it to text, i got below errors:

      Traceback (most recent call last):
        File "strategy\pair-trading-dev.py", line 299, in <module>
          cerebro.run()
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\cerebro.py", line 873, in run
          runstrat = self.runstrategies(iterstrat)
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\cerebro.py", line 1005, in runstrategies
          self._runonce(runstrats)
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\cerebro.py", line 1380, in _runonce
          strat._oncepost(dt0)
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\strategy.py", line 274, in _oncepost
          self._next_observers(minperstatus, once=True)
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\strategy.py", line 326, in _next_observers
          observer.prenext()
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\observer.py", line 59, in prenext
          self.next()
        File "strategy\pair-trading-dev.py", line 74, in next
          self.lines.created[0] = 'd'
        File "C:\Users\u8010137\Envs\quant\lib\site-packages\backtrader\linebuffer.py", line 222, in __setitem__
          self.array[self.idx + ago] = value
      TypeError: a float is required
      
      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      import math
      
      import backtrader as bt
      
      
      class OrderObserver(bt.observer.Observer):
          lines = ('created', 'expired',)
      
          plotinfo = dict(plot=True, subplot=True, plotlinelabels=True)
      
          plotlines = dict(
              created=dict(marker='*', markersize=8.0, color='lime', fillstyle='full'),
              expired=dict(marker='s', markersize=8.0, color='red', fillstyle='full')
          )
      
          def next(self):
              for order in self._owner._orderspending:
                  if order.data is not self.data:
                      continue
      
                  if not order.isbuy():
                      continue
      
                  # Only interested in "buy" orders, because the sell orders
                  # in the strategy are Market orders and will be immediately
                  # executed
      
                  if order.status in [bt.Order.Accepted, bt.Order.Submitted]:
                      self.lines.created[0] = order.created.price
      
                  elif order.status in [bt.Order.Expired]:
                      self.lines.expired[0] = order.created.price
      
      posted in General Code/Help
      D
      derek2017