For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Order Execution



  • Hello,
    I developed a risk structure which takes the executed market price and runs some conditions and returns a stop loss price level. However when i reference the order in my program and run the strategy, the executed prices seem to be shifted down to the subsequent buy order, i.e first executed price is 0 and then the next buy order has the previous executed price when it is run from next method . Any input on this situation is much appreciated.
    Result:

    Executed Price: 1.20389 # executed price of previous order
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY Order Accepted
    2018-03-14, Status 2: Ref: 28, Size: 136135.89, Price: NA
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_SL Order Accepted
    2018-03-14, Status 2: Ref: 29, Size: -136135.89, Price: 1.19039
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_TP Order Accepted
    2018-03-14, Status 2: Ref: 30, Size: -136135.89, Price: 1.25029
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY Order Completed
    2018-03-14, Status 4: Ref: 28, Size: 136135.89, Price: 1.23838
    --------------------------------------------------------------------------------
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_SL Order Completed
    2018-05-06, Status 4: Ref: 29, Size: -136135.89, Price: 1.18979
    --------------------------------------------------------------------------------
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_TP Order Cancelled
    2018-05-06, Status 5: Ref: 30, Size: -136135.89, Price: 1.25029
    --------------------------------------------------------------------------------
    --------------------------------  NOTIFY TRADE  --------------------------------
    2018-05-06 00:00:00, Close Price: **1.23838**, Profit, Gross -6614.84, Net -6633.63
    --------------------------------------------------------------------------------
    Executed Price: **1.23838** #executed price of previous order
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY Order Accepted
    2018-06-03, Status 2: Ref: 31, Size: 121797.28, Price: NA
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_SL Order Accepted
    2018-06-03, Status 2: Ref: 32, Size: -121797.28, Price: 1.22438
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_TP Order Accepted
    2018-06-03, Status 2: Ref: 33, Size: -121797.28, Price: 1.18002
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY Order Completed
    2018-06-03, Status 4: Ref: 31, Size: 121797.28, Price: 1.17227
    --------------------------------------------------------------------------------
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_SL Order Completed
    2018-06-04, Status 4: Ref: 32, Size: -121797.28, Price: 1.16528
    --------------------------------------------------------------------------------
    --------------------------------  NOTIFY ORDER  --------------------------------
    BUY_TP Order Cancelled
    2018-06-04, Status 5: Ref: 33, Size: -121797.28, Price: 1.18002
    

    Here is the code where i referenced the executed prices:

    if order.status == order.Completed:
    			print('-' * 32, ' NOTIFY ORDER ', '-' * 32)
    			print('{} Order Completed'.format(order.info['name']))
    			print('{}, Status {}: Ref: {}, Size: {}, Price: {}'.format(
    				date,
    				order.status,
    				order.ref,
    				round(order.size, 2),
    				round(order.executed.price, 5)
    			))
    			print('-' * 80)
    			
    			self.buy_price = round(self.buy_ord.executed.price,5)
    
    

    Code for my orders:

    if self.trade_sig > 0:
    				self.buy_ord = self.buy(size=units, exectype=bt.Order.Market, transmit=False)
    				self.buy_ord.addinfo(name='BUY')
    				buy_sl = self.sell(price=long_sl, size=self.buy_ord.size, exectype=bt.Order.Stop, transmit=False, parent=self.buy_ord)
    				buy_sl.addinfo(name='BUY_SL')
    				buy_tp = self.sell(price=long_tp, size=self.buy_ord.size, exectype=bt.Order.Limit, transmit=True, parent=self.buy_ord)
    				buy_tp.addinfo(name='BUY_TP')
    				print('Executed Price: {}'.format(round(self.buy_price,5)))
    

  • administrators

    The problem:

    • Unknown

    Potential diagnostic:

    • None

    Why?

    • Because you place out of context code pieces which may or may have nothing to do with the situation you experience, and may even not be the code you are executing.

    Advice:

    • Write a very short script in which you simply issue a buy order when next is 1st called. No condition needed
      • You can override nextstart which is called exactly once, when next would be called for the 1st time.
    • Check the execution price when the order is completed in notify_order and print it out

    Total size of code to check that works:

    • Around 15 lines

    Result:

    • The execution price will be printed out.


  • Hello @backtrader
    My apologies if you thought that the code I posted was somehow irrelevant. However, I did follow your advice and reproduce my error in a short script.

    Goal: Use the market order executed prices to determine a stop loss price

    Issue: When referring the executed prices in the next method, the returned price is 0 for the first order and then the correct prices are produced. I am guessing due to the flow of execution for backtrader.

    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 and buy price/commission
            self.order = None
            self.buyprice = 0
    
        def notify_order(self, order):
            if order.status in [order.Submitted, order.Accepted]:
                return
                # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                
    
            # 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.buyprice = order.executed.price
                    print('-----'*10)
                    self.log('Notified Executed price: {}'.format(round(self.buyprice,5)))
                    print('*****'*10)
    
            self.order = None
    
        def next(self):
    
    
            # Check if an order is pending ... if yes, we cannot send a 2nd one
            if self.order:
                return
    
            # Check if we are in the market
            if not self.position:
    
                self.order = self.buy()
                self.log('BUY executed, {}'.format(round(self.buyprice,5)))
    
    
            else:
    
                # Already in the market ... we might sell
                    # SELL, SELL, SELL!!! (with all possible default parameters)
    
                    # Keep track of the created order to avoid a 2nd order
                    self.order = self.sell()
    
    

    This Produces the Following:

    ###RESULT
    Starting Portfolio Value: 100000.00
    2015-12-01, BUY executed, 0    #should be 1.06155
    --------------------------------------------------
    2015-12-02, Notified Executed price: 1.06155
    **************************************************
    2015-12-03, BUY executed, 1.06155
    --------------------------------------------------
    2015-12-06, Notified Executed price: 1.08765
    **************************************************
    2015-12-07, BUY executed, 1.08765
    --------------------------------------------------
    2015-12-08, Notified Executed price: 1.08927
    **************************************************
    

    If you could provide some direction as to how can I accomplish the goal of retrieving the correct executed prices in the next method so that I can perform some math operations and send in a stop loss order, will be greatly appreciated.



  • In the very first next() you issue the buy order, but your buy price unknown since no order processing happened. It will be known only in the following next(). So you can calculate stop price only in the following next().



  • Good point @ab_trader , but I have a similar problem, are you saying that I will have to send in a buy order in next() and then do the calculations and send in a Stop loss order in the notify_order() or is there a better way of achieving this without having to break up the code and having all the orders in one method?



  • @emilie-leblanc TS tried to get the order price before he even issued that order. I don't think you have the same problem.

    If issuing order during notify_order() works for you, than why not to use it?


Log in to reply
 

});