I'm trying to access the self.positions
attribute from within the next
method of a strategy. It works as expected with backbroker but throws Attribute Error when run with IBbroker.
Error: 'Lines_LineSeries_LineIterator_DataAccessor_Strateg' object has no attribute 'positions'
Here's my code:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from datetime import datetime, timedelta
import backtrader as bt
tat = "TATASTEEL_STK_NSE"
rel = "RELIANCE_STK_NSE"
itc = "ITC_STK_NSE"
stocks = [tat, rel, itc]
class MyStrategy(bt.Strategy):
def __init__(self):
pass
def next(self):
print(self.getpositionbyname(itc)) #
print(self.getpositionbyname(rel)) # These 3 work well
print(self.getpositionbyname(tat)) #
print(self.positions) # Throws Attribute Error
print(self.positionsbyname) # Throws Attribute Error
if __name__ == '__main__':
cerebro = bt.Cerebro()
store = bt.stores.IBStore(host="192.168.1.3", port=7497, _debug=False)
datas = [store.getdata(dataname=stk, rtbar=True) for stk in stocks]
for data in datas:
cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes)
cerebro.setbroker(store.getbroker())
cerebro.addstrategy(MyStrategy)
cerebro.run()
In debug mode the strategy attributes postitions
and positionsbyname
hold an str
value containing the error message.
The Full Traceback looks something like this:
Although, separately requesting position for each datafeed using self.getpositionbyname()
works seamlessly: