Find if an open position is a losing position
Is there a way to find if an open position is losing, when inside the Strategy next () method?
by losing I mean its PnL<0
After much thinking, there is no direct method. It is possible, but if doesn't feel natural and will for sure be modeled in a better way.
- Get the position for the data of your choice
- Get the commission info object which applies to that data
- Calculate the current profit and loss
def next(self): pos = self.getposition(self.data) # for the default data (aka self.data0 and aka self.datas) comminfo = self.broker.getcommissioninfo(self.data) pnl = comminfo.profitandloss(pos.size, pos.price, self.data.close)
Eventually, I saved the open price in a file and read it in next() method, easy...
You could create a dictionary in strategy.init. In notify_order: order.completed, insert an item with either the symbol or order.ref as the key, and either the order object (to later retrieve size and price), or order.executed.price as the value.