Buy Order Works on 1st Data Feed And Not on 2nd Data Feed
Hi fellow traders,
I have two data feeds and am trying to place buy orders to buy either one of them.
I find that the buy order works on the 1st data feed but doesn't work on the second data feed. To be exact, self.position.size would be equal to zero after I place an order for the second data feed whereas it wouldn't be zero if the order were to be placed for the 1st data feed.
Can someone pls help me out here?
See the code below for reference.
import backtrader as bt import datetime as dt class Test_Strategy (bt.Strategy): params = (('risk', 0), ) def __init__ (self): self.data_risk1 = self.datas self.data_risk2 = self.datas def next (self): print (self.position.size) if self.params.risk == 1: self.buy (data = self.data_risk1, size = 100) elif self.params.risk == 2: self.buy (data = self.data_risk2, size = 100) if __name__ == '__main__': cerebro = bt.Cerebro() data_risk1 = bt.feeds.GenericCSVData (dataname = r"C:\data1.csv", timeframe = bt.TimeFrame.Days, compression = 1, fromdate = dt.datetime (1999,12,31), todate = dt.datetime (2018,12,31), headers = True, nullvalue = 0, dtformat = '%m/%d/%Y', datetime = 0, time = -1, open = 2, high = -1, low = -1, close = 1, volume = 3, openinterest = -1, ) data_risk2 = bt.feeds.GenericCSVData (dataname = r"C:\data2.csv", timeframe = bt.TimeFrame.Days, compression = 1, fromdate = dt.datetime (1999,12,31), todate = dt.datetime (2018,12,31), headers = True, nullvalue = 0, dtformat = '%m/%d/%Y', datetime = 0, time = -1, open = 2, high = -1, low = -1, close = 1, volume = 3, openinterest = -1, ) cerebro.resampledata (data_risk1, timeframe = bt.TimeFrame.Months, compression = 1) cerebro.resampledata (data_risk2, timeframe = bt.TimeFrame.Months, compression = 1) cerebro.addstrategy(Test_Strategy, risk = 2) cerebro.broker.setcash (1000000) results = cerebro.run()
Sample data format of the two imported csv files are as follows
ab_trader last edited by
With all my respect, you may want to be less aggressive in your claims that something doesn't work in
bt. Just think this way -
btwas used by a lot of people for quite a long time, and for sure such simple mechanics as order placing should work well now, otherwise it would be discovered and fixed long time ago.
Now returning to your question:
self.positionreturns position for the first data feed ONLY, in order to get position in any data feed
getpositionbyname(dataname)have to be used, see Docs - Strategy.
@ab_trader , thanks for providing your feedback. I was trying to imply that my code wasn't working and not bt wasn't working. Guess I should have been clearer in my post. Will definitely be more mindful of my wordings in future post.
Back to your solution, it works like a charm.
Problem solved now! Many thanks.
@ab_trader I've up your reputation too!