Backtrader Community

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

    Emin Ozkan

    @Emin Ozkan

    0
    Reputation
    277
    Profile views
    12
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    Emin Ozkan Unfollow Follow

    Latest posts made by Emin Ozkan

    • RE: bt.sizer.PercentSizer behavior

      I totally agree with the stupidity of all in strategies, but I feel like there is a bit more to that here. Looking at the following log:

      Order size: 10233.442891368994
      Order value: 8500.0
      2011-06-29T00:00:00, Order submitted by 1900-01-01 00:00:00 2100-01-01 00:00:00 NZDUSD
      2011-06-30T00:00:00, Order Submitted NZDUSD-market
      2011-06-30T00:00:00, Order Margin NZDUSD
      2011-07-03T00:00:00, Ending Value 10000.0000
      Order size: 10362.315306968352
      Order value: 8499.999999999998
      2011-07-11T00:00:00, Order submitted by 2011-07-04 00:00:00 2017-01-01 00:00:00 NZDUSD
      2011-07-12T00:00:00, Order Submitted NZDUSD-market
      2011-07-12T00:00:00, Order Margin NZDUSD
      Order size: 10333.341437914853
      Order value: 8500.0
      2011-07-12T00:00:00, Order submitted by 2011-07-04 00:00:00 2017-01-01 00:00:00 NZDUSD
      2011-07-13T00:00:00, Order Submitted NZDUSD-market
      2011-07-13T00:00:00, Order Margin NZDUSD
      Order size: 9957.009148734287
      Order value: 8500.0
      2011-08-03T00:00:00, Order submitted by 2011-07-04 00:00:00 2017-01-01 00:00:00 NZDUSD
      2011-08-04T00:00:00, Order Submitted NZDUSD-market
      2011-08-04T00:00:00, Order Accepted NZDUSD-market
      2011-08-04T00:00:00, SELL EXECUTED, Price: 0.8537, Size: 9957.0091,
      

      I am using a percent sizer only at 85%. It seems that my orders are rejected if the order size (not my order value) is bigger than my cash. In other words, the first three orders are rejected because numerical value of my order size is bigger than my cash, the percent sizer starts working as soon as my order size drops below my cash. Very curious indeed.

      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Based my code on Quickstart: would like to self.log the minutes

      This works for me

      def log(self, txt, dt=None, doprint=False):
          ''' Logging function fot this strategy'''
          if self.params.printlog or doprint:
      
              dt = dt or self.datas[0].datetime.datetime(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
      posted in General Code/Help
      E
      Emin Ozkan
    • bt.sizer.PercentSizer behavior

      Hello,
      I am running Cerebro engine with the following parameters:

      'broker_input': {
                  'stdstats': False,
                  'opreturn': False,
                  'cash': 10000,
                  'slippage_perc': 0,
                  'comission': StocksPerc,
                  'commvalue':0,
                  'sizer': bt.sizers.PercentSizer,
                  'percents': 100
              }
          }
      

      The weird thing is that when I run the engine with NZDUSD forex where the price is around 0.6, all of my orders are rejected with margin. However the same data feed makes trades with FixedSizer or with PercentSizer when the percent drops below around 80. PercentSizer also works perfectly fine with a couple other data feeds. My question is that is there some kind of buffer I need to think about when using PercentSizer like comission slippage etc. (even though they are both zero in my cases)?
      Thanks,

      My repo: https://github.com/emindeniz/exterme_bt
      I am running walkforward_test_run.py

      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Stop Order execution price?

      @backtrader ok thanks

      posted in General Code/Help
      E
      Emin Ozkan
    • Stop Order execution price?

      Hello,
      I am sending a stop loss order with the following code

              self.buy(exectype=bt.Order.Stop,
                       price=data.close[0] * (1 + self.params.stop_loss),
                       data=data)
      

      First of all is this the correct way to send a stop loss order? I check the execution price with the following code:

          def notify_order(self, order):
      
              if order.status in [order.Submitted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  self.log('Order Submitted {}-{}'.
                           format(order.params.data._name,
                           self.getOrderType(order)))
                  return
      
              if order.status in [order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  self.log('Order Accepted {}-{}'.
                           format(order.params.data._name,
                           self.getOrderType(order)))
                  return
      
              # Check if an order has been completed
              # Attention: broker could reject order if not enough cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Price: {:.4f}, Cost: {:.4f}, '
                          'Comm:{:.4f}, Ticker:{} OrderType:{}'.format
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm,
                           order.params.data._name,
                           self.getOrderType(order)))
      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: {:.4f}, '
                               'Cost: {:.4f}, Comm:{:.4f},'
                               'Ticker:{}, OrderType:{}'.format
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm,
                                order.params.data._name,
                                self.getOrderType(order)))
      
                  self.bar_executed = len(self)
      

      What I am seeing is that if this is indeed a stop loss order, the execution price is actually the stop loss trigger price, not the actual closing price on the execution bar.
      Let me give an example. Let's say I buy 100 with a stop loss of 90. Then at the few bars down the road the price is 80. I expect the stop loss order to be triggered (It is). But the execution price is still 90 instead of 80.
      Is this normal? It seems unrealistic to me that a stop loss would be executed at the trigger price. What do you think? The documentation says:

      Order.Stop. An order which is triggered at price and executed like an Order.Market order

      Or is it that order.executed.price doesn't matter?

      I also checked the execution price with

      pricein = trade.history[len(trade.history)-1].status.price
      priceout = trade.history[len(trade.history)-1].event.price
      

      priceout is still the stop loss trigger price.

      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Preventing subplots

      Here is another way to plot an independent equity curve based on bokeh. I apologize for shitty code. This way, I don't have to turn off cerebro's built in
      pretty plotting such as buysell observers.

      0_1546364337821_Capture.JPG

      cerebro.run()
      # This assumes that you have added a strategy
      # the value observer 
      plot_observer(cerebro.runstrats[0][0])
      
      from mpl_toolkits.mplot3d import axes3d
      import matplotlib.pyplot as plt
      from matplotlib import cm
      import numpy as np
      from matplotlib.ticker import LinearLocator, FormatStrFormatter
      from matplotlib.dates import num2date
      import seaborn as sns
      from bokeh.io import show
      from bokeh.layouts import column
      from bokeh.models import ColumnDataSource, RangeTool
      from bokeh.plotting import figure, output_file
      
      def plot_observer(strategy,alias='value'):
          for observer in strategy.getobservers():
              linealias = observer.lines._getlinealias(0)
              if linealias ==alias:
                  dates = np.array(strategy.datetime.plot())
                  ydata = np.array(observer.line.plot())
                  dates = num2date(dates)
                  plot_bokeh(dates=dates,values=ydata)
      
          return
      
      def plot_bokeh(dates,values):
      
          output_file("equity.html", title="equity line")
      
          TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
      
          source = ColumnDataSource(data=dict(date=dates, value=values))
      
          p = figure(plot_height=300, plot_width=600, tools=TOOLS,
                     x_axis_type="datetime", x_axis_location="above",
                     background_fill_color="#efefef", x_range=(dates[0], dates[-1]))
      
          p.line('date', 'value', source=source)
          p.yaxis.axis_label = 'value'
      
          select = figure(title="Drag the middle and edges of the selection box to change the range above",
                          plot_height=130, plot_width=600, y_range=p.y_range,
                          x_axis_type="datetime", y_axis_type=None,
                          tools="", toolbar_location=None, background_fill_color="#efefef")
      
          range_rool = RangeTool(x_range=p.x_range)
          range_rool.overlay.fill_color = "navy"
          range_rool.overlay.fill_alpha = 0.2
      
          select.line('date', 'value', source=source)
          select.ygrid.grid_line_color = None
          select.add_tools(range_rool)
          select.toolbar.active_multi = range_rool
      
          show(column(p, select))
      
      
      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Preventing subplots

      @backtrader Thanks actually I got what I need by adding plot=False to datafeed and the indicators. 0_1546349852787_Figure_100.jpeg

      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Preventing subplots

      I am sorry that I wasn't clear. I have attached an image to see what I get currently:
      0_1546348809827_Figure_0.jpeg
      What I want to get is
      0_1546348964707_Figure_1.jpg.
      I think this is called Broker observer? But the relevant part is I want an observer such as Value or Broker in its own independent plot without including datafeed and indicators etc. (rather than a subplot). Is this possible? Thanks,

      posted in General Code/Help
      E
      Emin Ozkan
    • Preventing subplots

      Hello,
      I am interested in having separate plots for equity line and drawdown lines. How does one go about doing this?
      I have set cerebro = bt.Cerebro(stdstats=False) and then added an observer for drawdown like this:
      cerebro.addobserver(bt.observers.DrawDown,plot=True, subplot=False)
      but cerebro.plot() only plots datafeed and the indicators.(i.e. doesn't plot newly added drawdown observer).

      posted in General Code/Help
      E
      Emin Ozkan
    • RE: Memory Error

      Thanks a lot. Simply doing this
      cerebro = bt.Cerebro(stdstats=False,optreturn=True,optdatas=True)
      solved all of my problems. Backtrader is a powerful tool. I was able to complete 800 rounds in 2.5 hours.

      posted in General Code/Help
      E
      Emin Ozkan