Stuck with this ---> for fill in ccxt_order['trades']: TypeError: 'NoneType' object is not iterable
-
I little help with my code guys, I am a begginer:
from future import (absolute_import, division, print_function,
unicode_literals)
import backtrader as bt
from ccxtbt import CCXTStore
from datetime import datetime, timedeltaclass St(bt.Strategy):
params = (
('maperiod', 15),
)def log(self, txt, dt=None): ''' Logging function fot this strategy''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None # Add a MovingAverageSimple indicator self.sma = bt.indicators.SimpleMovingAverage( self.datas[0], period=self.params.maperiod) # Indicators for the plotting show bt.indicators.ExponentialMovingAverage(self.datas[0], period=25) bt.indicators.WeightedMovingAverage(self.datas[0], period=25, subplot=True) bt.indicators.StochasticSlow(self.datas[0]) bt.indicators.MACDHisto(self.datas[0]) rsi = bt.indicators.RSI(self.datas[0]) bt.indicators.SmoothedMovingAverage(rsi, period=10) bt.indicators.ATR(self.datas[0], plot=False) def notify_data(self, data, status, *args, **kwargs): dn = data._name dt = datetime.now() msg = 'Data Status: {}, Order Status: {}'.format(data._getstatusname(status), status) print(dt, dn, msg) if data._getstatusname(status) == 'LIVE': self.live_data = True else: self.live_data = False def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return # Check if an order has been completed # Attention: broker could reject order if not enough cash if order.status in [order.Completed]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.buyprice = order.executed.price self.buycomm = order.executed.comm else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def next(self): # Simply log the closing price of the series from the reference self.log('Close, %.2f' % self.dataclose[0]) if self.live_data: # Check if an order is pending ... if yes, we cannot send a 2nd one if self.order: return # Check if we are in the market if not self.position: # Not yet ... we MIGHT BUY if ... if self.dataclose[0] > self.sma[0]: # BUY, BUY, BUY!!! (with all possible default parameters) self.log('BUY CREATE, %.2f' % self.dataclose[0]) # Keep track of the created order to avoid a 2nd order self.order = self.buy() else: if self.dataclose[0] < self.sma[0]: # SELL, SELL, SELL!!! (with all possible default parameters) self.log('SELL CREATE, %.2f' % self.dataclose[0]) # Keep track of the created order to avoid a 2nd order self.order = self.sell()
def main():
cerebro = bt.Cerebro(quicknotify=True)
config = {'apiKey': '',
'secret': '******',
'enableRateLimit': True,
}store = CCXTStore(exchange='bitmex', currency='BTC', config=config, retries=5, debug=False, sandbox=True) broker_mapping = { 'order_types': { bt.Order.Market: 'market', bt.Order.Limit: 'limit', bt.Order.Stop: 'stop', # stop-loss for kraken, stop for bitmex bt.Order.StopLimit: 'stop limit' }, 'mappings': { 'closed_order': { 'key': 'status', 'value': 'closed' }, 'canceled_order': { 'key': 'result', 'value': 1} } } broker = store.getbroker(broker_mapping=broker_mapping) cerebro.setbroker(broker) hist_start_date = datetime.utcnow() - timedelta(minutes=40) data = store.getdata(dataname='BTC/USD', name="BTCUSD", timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, compression=1, ohlcv_limit=999, drop_newest=True) cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=1) cerebro.addstrategy(St) cerebro.run() cerebro.plot(style="candlesticks")
if name == 'main':
main()As a result this:
2021-02-19 14:02:25.862573 BTCUSD Data Status: DELAYED, Order Status: 3
2021-02-19, Close, 51793.00
2021-02-19, Close, 51797.00
2021-02-19, Close, 51797.00
2021-02-19, Close, 51836.50
2021-02-19, Close, 51836.50
2021-02-19, Close, 51836.50
2021-02-19 14:02:28.115552 BTCUSD Data Status: LIVE, Order Status: 4
2021-02-19, Close, 51836.50
2021-02-19, BUY CREATE, 51836.50and then
Traceback (most recent call last):
File "C:\Users\N\PycharmProjects\pythonProject2\bitmex_sandbox.py", line 166, in <module>
main()
File "C:\Users\N\PycharmProjects\pythonProject2\bitmex_sandbox.py", line 162, in main
cerebro.run()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\cerebro.py", line 1298, in runstrategies
self._runnext(runstrats)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\cerebro.py", line 1623, in _runnext
self._brokernotify()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\cerebro.py", line 1360, in _brokernotify
self._broker.next()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxtbt\ccxtbroker.py", line 199, in next
for fill in ccxt_order['trades']:
TypeError: 'NoneType' object is not iterableThank you for the help
-
Nobody? Really?
-
@klearner1 said in Stuck with this ---> for fill in ccxt_order['trades']: TypeError: 'NoneType' object is not iterable:
from ccxtbt import CCXTStore
I don't know the answer for you. I'm guessing others don't either. Perhaps you could check in the repo? https://github.com/Dave-Vallance/bt-ccxt-store/issues
-
@run-out thanks! this is already useful, I am going to check the repo