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 do I set up correct position close logic?



  • Hi I am trying to backtest my code but now I don't know how I can correctly ask the backtrader to close an existing position for me. I tried looking at the Backtrader blogs but didn't find a page that clarifies how I should do it. Thus I would appreciate immensely if anyone can offer some insights!

    def next(self): # input trade logid in this function
        self.log('Close, %.2f' % self.dataclose[0])
    
        if self.order:
            return
    
        if not self.position:
    
            if self.rsim30<30 and self.rsim60<30:
    
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy()
    
            elif self.rsim30>70 and self.rsim60>70:
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell()
        
        if self.position:
            if self.rsim30>70 and self.rsim60>70:
    
                self.close(exectype=bt.Order.Close)
                self.log('BUY POSITION CLOSED, exectype Close, price %.2f' %
                         self.data.close[0])
            if self.rsim30<30 and self.rsim60<30:
    
                self.close(exectype=bt.Order.Close)
    
                self.log('SELL POSITION CLOSED, exectype Close, price %.2f' %
                         self.data.close[0])
    

    My trade logic is as above, I am not sure if I am opening long/short positions at the current available market prices. can someone just check it for me? Thanks!

    And my position-closing logic don't seem to work the way I want, that is, if RSIm30>70 and RSIm60>70, close my existing long positions at market, if RSIm30<30 and RSIm60<30. close my existing short positions at market. How should I write my codes here? Thanks so much for the help beforehand!!!

    @backtrader I know this should be obvious, but I swear I have looked through the website and other backtrader strategy files and can't find how I can close long positions and short positions separately under different conditions, please help! Thanks!



  • @backtrader @ab_trader I know this should be obvious, but I swear I have looked through the website and other backtrader strategy files and can't find how I can close long positions and short positions separately under different conditions, please help! Thanks!



  • I've used self.close() to close any type of the position with the marker order.



  • @ab_trader So it is self.close(), not self.buy(exectype=bt.Order.Close) right? But what if I have both existing long and short positions, I wanna close only the long position under one circumstance and short under another, how do I ask Backtrader to distinguish between them?

    For example, if I wanna close a long position, and specify in the command that close only a long position, should I use
    self.buy(exectype=bt.Order.Close)
    or
    self.sell(exectype=bt.Order.Close)
    or
    self.close() ??? (but this one seems to close all existing long and short positions, can I specify, for example, asking it to close only long positions, leaving short positions alone for me?)
    Thanks!


  • administrators

    @bernardlin said in How do I set up correct position close logic?:

    self.buy(exectype=bt.Order.Close)

    bt.Order.Close is an order execution type and not an instruction to close a position. This is what is also known as MOC or Market On Close, i.e.: your order will be executed when the market closes. Your broker and/or the target market have to support this. Please see:

    You can obviously counter a long position with self.sell (and the right size) and a short position with self.buy

    self.close()

    This will close an open position (no matter whether long/short).

    @bernardlin said in How do I set up correct position close logic?:

    (but this one seems to close all existing long and short positions, can I specify, for example, asking it to close only long positions, leaving short positions alone for me?)

    You cannot have long and short positions simultaneously on the same assets, so it cannot close all existing long and short positions. self.close will only close what`s open on the given asset you specify, and if none is specified the first data in the system. See its reference in:



  • @backtrader Hi, thanks so much for the clarification, so it means that we cannot hedge against a position on the same asset in Backtrader, right? Is it possible to add this feature in the future?


  • administrators

    Yes you can. Buy/Sell an asset which hedges your asset: options, futures. But if you buy AAPL shares and also sell AAPL shares, both actions will logically counter each other.



  • @backtrader Okay, but I am now only backtesting my trading strategy with the historical OHLC prices of some forex currency pairs, since it was only historical rates in imported csv files, how does backtrader distinguish the asset class? Or could there be a way to set up counter positions of forex currency paris as on many forex trading platforms such as MT4 and Oanda? Thanks for any advice!


  • administrators

    @bernardlin said in How do I set up correct position close logic?:

    how does backtrader distinguish the asset class

    It doesn't. You determine how an asset performs using Commission Schemes. See

    There are some other chapters in the documentation including how to create your own commission schemes.



  • @backtrader
    Thanks, I will look it up.
    A new question just hit me, to further build up on this question. It seems that your reply implies that backtrader assumes that assets are denominated in USD. What if I am trading forex pairs? I guess it works the same way for currency pairs like EURUSD as the price is denominated also in USD. But what if I am trading USDCHF, USDJPY or USDCHN? These pairs are denominated in other currencies other than USD, yet my base currency is USD and I would like my backtrader to reflect that. This seems to pose an issue, do you have any suggestions how I can solve this? Much gratitude for your help!


  • administrators

    @bernardlin said in How do I set up correct position close logic?:

    It seems that your reply implies that backtrader assumes that assets are denominated in USD

    No. It simply assumes nothing. The assumption is yours.

    @bernardlin said in How do I set up correct position close logic?:

    how I can solve this?

    This has been discussed before and the most appropriate option is to define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency.



  • @backtrader
    Hi, would you mind providing me a link on how 'define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency' is done? I searched throughout the community but haven't found the relating thread on this. Thanks a lot!


  • administrators

    @bernardlin said in How do I set up correct position close logic?:

    Hi, would you mind providing me a link on how 'define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency' is done

    "Discussed" is not the same as developed.