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) if self.order: return if not self.position: if self.rsim30<30 and self.rsim60<30: self.log('BUY CREATE, %.2f' % self.dataclose) self.order = self.buy() elif self.rsim30>70 and self.rsim60>70: self.log('SELL CREATE, %.2f' % self.dataclose) 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) 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)
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!
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.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?)
bt.Order.Closeis an order execution type and not an instruction to close a position. This is what is also known as
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
self.sell(and the right size) and a
This will close an open position (no matter whether long/short).
(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
shortpositions simultaneously on the same assets, so it cannot close all existing long and short positions.
self.closewill 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?
Yes you can. Buy/Sell an asset which hedges your asset: options, futures. But if you buy
AAPLshares and also sell
AAPLshares, 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!
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.
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!
It seems that your reply implies that backtrader assumes that assets are denominated in USD
No. It simply assumes nothing. The assumption is yours.
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.
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!
@bernardlin You have to check whether the position is a Long Position or Short position, before trying to close it. The position object has size property which will be +ve for Long position and -Ve for short position. You have to check for this before trying to close a position
What it happening in your code is, the position check is being evaluated and since the system does not know whether you are looking to close a long or short position it is simply executing the condition that is being met in the 'Else' block
Hope it helps
I have something critical to point out.
Backtesting forex pairs trading has a major flaw. It uses a different way to calculate pnl of the backtest because the assets involved rarely have the same quote or base currencies.
The only exception to this is if the assets involved have the same base currency, e.g USDCHF USDJPY. If this pair appear to be cointegrated, then the returns of the backtest would be the same as calculating pnl of, say, GLD GDX.
But if the forex assets involved are of the same quote currency or of completely different currency bases and quotes, then the calculation of the pnl is completely different.
If one proceeds and backtest these cointegrated pairs the same way one do regularly then one would get the wrong result.
I am really keen to know how you went about backtesting cointegrated forex pairs and getting the correct result using Backtrader. I am yet to do that.