Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    How to implement a Limit Order Correctly

    Indicators/Strategies/Analyzers
    3
    12
    288
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • C
      chhrissi2909 last edited by

      Hey Guys,

      I am trying to set a Buy Limit Order on the Donchian High and and a Sell oder on the DonchianLow. I don't know why my code doesn't work.

      Here you can see how I calculated the Donchian High and Low:

      entry_price = bt.indicators.Highest(self.data.high[-1], period=30)
      stop_price = bt.indicators.Lowest(self.data.low[-1], period=15)
      

      These are my lines, which should open and close the trades:

      if self.position.size == 0:
         self.buy(exectype=bt.Order.Limit, price=entry_price, size = size)
      else:
         self.close(exectype=bt.Order.Stop, price=stop_price)
      

      So I want to open a Trade with a limit Order, when the price reaches the Donchian High and I want to close it, when the price goes down to the Donchian Low.

      thank you for your help :)
      best regards Christian

      run-out 1 Reply Last reply Reply Quote 1
      • run-out
        run-out @chhrissi2909 last edited by

        @chhrissi2909 said in How to implement a Limit Order Correctly:

        entry_price = bt.indicators.Highest(self.data.high[-1], period=30)

        You are creating an indicator line but off of the data in a single bar. [-1].

        Try creating your indicator lines in init without the square brackets. Use self.

        self.entry_price = bt.indicators.Highest(self.data.high, period=30)
        self.stop_price = bt.indicators.Lowest(self.data.low, period=15)
        

        Then in next you can call the value for that bar like:

        if self.position.size == 0:
           self.buy(exectype=bt.Order.Limit, price=self.entry_price[-1], size = size)
        else:
           self.close(exectype=bt.Order.Stop, price=self.stop_price[-1])
        

        RunBacktest.com

        C 1 Reply Last reply Reply Quote 0
        • C
          chhrissi2909 @run-out last edited by

          Hey @run-out,

          sorry I just tased this line out of my indicator, so in my original strategy I use my DonchianIndicator like this:

          def __init__(self):
              self.MyDonchian = Donchian()
          

          and than I take the values like this:

          entry_price = self.MyDonchian.DonchianHigh[-1]
          stop_price = self.MyDonchian.DonchianLow[-1]
          

          and than I use these values for my entry...

          Even If I just put as a entry value just 250.0, than the system just buys and buys and buys, even if the price is under 250..... And I do not know why..?

          A 1 Reply Last reply Reply Quote 0
          • run-out
            run-out last edited by

            Please include all your code in one snippet between triple back quotes. Thanks.

            RunBacktest.com

            C 2 Replies Last reply Reply Quote 0
            • C
              chhrissi2909 @run-out last edited by

              @run-out okay so that's the Indicator Class:

              import math
              import backtrader as bt
              import numpy as np
              # ---- Hier werden auch alle Zeicheneigenschaften eines Indikators erklärt! ----
              # Quelle:
              #https://www.backtrader.com/docu/inddev/
              
              class Donchian(bt.ind.PeriodN):
                  # Lines erzeugt den Indikator in einem SUbchart, wenn in init aufgerufen
                  lines = ("DonchianHigh","DonchianLow")
              
                  #params macht legt variablen für Indikator fest
                  params = (('DonchianEntryPeriod', 30),('DonchianStopPeriod', 15))
              
                  # plotinfo sagt ob unten in der Box geplottet werden soll oder im Chart
                  plotinfo = dict(subplot=False)  # plot along with data
              
                  #Mit plotlines können den Linien explizite Eigenschafte wie 
                  # Farbe, Struktur usw. zugewiesen werden
                  plotlines = dict(
                      # würde die Linieanart auf gestrichelt ändern.
                      #DonchianHigh=dict(ls='--'),  
                      DonchianHigh=dict(color = "green"),  # use same color as prev line (dcm)
                      DonchianLow=dict(color = "red"),  # use same color as prev line (dch)
                  )
              
              
              
              
                  def __init__(self):
              
                      self.lines.DonchianHigh =  bt.indicators.Highest(self.data.high,
                                                      period=self.p.DonchianEntryPeriod)
                      self.lines.DonchianLow = bt.indicators.Lowest(self.data.low,
                                                      period=self.p.DonchianStopPeriod)
                  
              
              

              and that's the Strategy Class:

              import math
              import backtrader as bt
              from Donchian_Indicator import Donchian
              
              
              
              class DonchianStrategy(bt.Strategy):
              
              
              # in die __init__ müssen die allgemeinen deklarationen
                  def __init__(self):
                      self.MyDonchian = Donchian()
              
              # in die next muss die logik der strategie
                  def next(self):
                      
                      price = self.MyDonchian.DonchianHigh[-1]
                      stop_price = self.MyDonchian.DonchianLow[-1]
                      size = int((self.broker.get_cash()*0.01) / self.data)
              
                      difference = price - self.datas[0].close 
                      if self.position.size == 0:
                          self.buy(exectype=bt.Order.Limit, price=difference, size = size)
                      else:
                      self.close(exectype=bt.Order.Stop, price=stop_price)
              
              
              
              
              C 1 Reply Last reply Reply Quote 0
              • C
                chhrissi2909 @chhrissi2909 last edited by

                @chhrissi2909 shit sorry, I tried something with difference...

                so normally the price = price like this:

                self.buy(exectype=bt.Order.Limit, price=price, size = size)
                
                1 Reply Last reply Reply Quote 0
                • C
                  chhrissi2909 @run-out last edited by

                  Hey @run-out what do you say to my code? Where could be the error?

                  best regards
                  Christian

                  1 Reply Last reply Reply Quote 0
                  • run-out
                    run-out last edited by

                    I'm not 100% sure I understand your goal, but I think you are looking for a bracket order. This will also allow you to sell on the high side with a limit order.

                    self.buy_bracket(
                        data=self.datas[0],
                        size=size,
                        exectype=bt.Order.Limit,
                        plimit=price,
                        stopprice=price_stop,
                        stopexec=bt.Order.Stop,
                        limitprice=price_limit,
                        limitexec=bt.Order.Limit,
                    )
                    

                    RunBacktest.com

                    1 Reply Last reply Reply Quote 1
                    • A
                      ab_trader @chhrissi2909 last edited by

                      @chhrissi2909 said in How to implement a Limit Order Correctly:

                      Even If I just put as a entry value just 250.0, than the system just buys and buys and buys, even if the price is under 250..... And I do not know why..?

                      This is correct behavior of the limit order - buy cheaper than the limit price. Not sure why you are not happy with it. If you want to buy on the breakouts, than use stop order, not limit.

                      • If my answer helped, hit reputation up arrow at lower right corner of the post.
                      • Python Debugging With Pdb
                      • New to python and bt - check this out
                      C 2 Replies Last reply Reply Quote 1
                      • C
                        chhrissi2909 @ab_trader last edited by

                        Hey @ab_trader thank you for your tip.

                        So I want to buy with an limit Order, when the market goes above the DocnhianHigh.

                        If I change the Limit and the Stop Order as you said, than the code again don't buy on the high and sell not the low..

                        it would look like this

                                if self.position.size == 0:
                                    self.buy(exectype=bt.Order.Stop, price=price, size = size)
                                else:
                                    self.close(exectype=bt.Order.Limit, price=stop_price)
                        

                        And the result is this:

                        limit to sell.png

                        1 Reply Last reply Reply Quote 0
                        • C
                          chhrissi2909 @ab_trader last edited by

                          @ab_trader if I take this code, than the strategy works. With this code it trades long, with an pending Order own the Donchian High,:

                                  if self.position.size == 0:
                                      self.buy(exectype=bt.Order.Stop, price=price, size=size)
                                  else:
                                      if self.data[0] < stop_price:
                                          self.sell(size=self.position.size)
                                      # Stop Order like this  with  pending does not work... :
                                      #self.sell(exectype=bt.Order.Stop, price=stop_price, size=self.position.size)
                          

                          but the only problem ist, that it just goes out of the trade, when it closes under the Donchian Low.. And in my Case I want it to close, when it triggers the DonchianLow line..

                          Do you know a solution for closing a trade on a Stop Line like the DonchianLow?

                          best regards Christian

                          1 Reply Last reply Reply Quote 0
                          • A
                            ab_trader last edited by

                            Sell using stop order, not limit.

                            • If my answer helped, hit reputation up arrow at lower right corner of the post.
                            • Python Debugging With Pdb
                            • New to python and bt - check this out
                            1 Reply Last reply Reply Quote 1
                            • 1 / 1
                            • First post
                              Last post
                            Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors