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



  • 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



  • @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])
    


  • 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..?



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



  • @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)
    
    
    
    


  • @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)
    


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

    best regards
    Christian



  • 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,
    )
    


  • @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.



  • 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



  • @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



  • Sell using stop order, not limit.


Log in to reply
 

});