@run-out thanks! this is already useful, I am going to check the repo
Best posts made by KLearner1
-
RE: Stuck with this ---> for fill in ccxt_order['trades']: TypeError: 'NoneType' object is not iterable
Latest posts made by KLearner1
-
ccxt.base.errors.BadRequest: binance {"code":-1104,"msg":"Not all sent parameters were read; read '9' parameter(s) but was sent '10'."}
Guys I am trying binance testnet, this my code
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt from ccxtbt import CCXTStore from datetime import datetime, timedelta class St(bt.Strategy): params = ( # Standard MACD Parameters ('macd1', 12), ('macd2', 26), ('macdsig', 9), ('atrperiod', 14), # ATR Period (standard) ('atrdist', 3.0), # ATR distance for stop price ('smaperiod', 30), # SMA Period (pretty standard) ('dirperiod', 10), # Lookback period to consider SMA trend direction ) def log(self, txt, dt=None): ''' Logging function for this strategy''' dt = dt or self.datas[0].datetime.datetime(0) print('%s, %s' % (dt.isoformat(), txt)) def notify_data(self, data, status): dn = data._name dt = datetime.utcnow() 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, %.2f' % order.executed.price) elif order.issell(): self.log('SELL EXECUTED, %.2f' % order.executed.price) 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 __init__(self): self.macd = bt.indicators.MACD(self.data, period_me1=self.p.macd1, period_me2=self.p.macd2, period_signal=self.p.macdsig) # Cross of macd.macd and macd.signal self.mcross = bt.indicators.CrossOver(self.macd.macd, self.macd.signal) # To set the stop price self.atr = bt.indicators.ATR(self.data, period=self.p.atrperiod) # Control market trend self.sma = bt.indicators.SMA(self.data, period=self.p.smaperiod) self.smadir = self.sma - self.sma(-self.p.dirperiod) def start(self): self.order = None # sentinel to avoid operrations on pending order def next(self): if self.order: return # pending order execution if not self.position: # not in the market if self.mcross[0] > 0.0 and self.smadir < 0.0: self.order = self.buy() self.log("Buy ordered: $%.2f" % self.data0.close[0]) pdist = self.atr[0] * self.p.atrdist self.pstop = self.data.close[0] - pdist else: # in the market pclose = self.data.close[0] pstop = self.pstop if pclose < pstop: self.close() # stop met - get out else: pdist = self.atr[0] * self.p.atrdist # Update only if greater than self.pstop = max(pstop, pclose - pdist) def main(): cerebro = bt.Cerebro(quicknotify=True) config = {'apiKey': '***********************************', 'secret': '**********************************', 'enableRateLimit': True, 'options': {'newOrderRespType': 'FULL'}, } store = CCXTStore(exchange='binance', 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-loss', 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=50) data = store.getdata(dataname='BTC/USDT', name="BTCUSD", timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, compression=1, config={'enableRateLimit': True}, ohlcv_limit=50, drop_newest=True, buffered=True) cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=1) cerebro.addstrategy(St) cerebro.run() cerebro.plot(style="candlesticks") if __name__ == '__main__': main()
Returns:
2021-03-01 12:48:42.441846 BTCUSD Data Status: DELAYED, Order Status: 3
Traceback (most recent call last):
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\base\exchange.py", line 589, in fetch
response.raise_for_status()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\requests\models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://testnet.binance.vision/api/v3/orderDuring handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/N/PycharmProjects/pythonProject2/time.py", line 144, in <module>
main()
File "C:/Users/N/PycharmProjects/pythonProject2/time.py", line 140, 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 1630, in _runnext
strat._next()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\strategy.py", line 347, in _next
super(Strategy, self)._next()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\lineiterator.py", line 271, in _next
self.next()
File "C:/Users/N/PycharmProjects/pythonProject2/time.py", line 83, in next
self.order = self.buy()
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\backtrader\strategy.py", line 933, in buy
return self.broker.buy(
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxtbt\ccxtbroker.py", line 245, in buy
return self._submit(owner, data, exectype, 'buy', size, price, kwargs)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxtbt\ccxtbroker.py", line 227, in _submit
ret_ord = self.store.create_order(symbol=data.p.dataname, order_type=order_type, side=side,
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxtbt\ccxtstore.py", line 142, in retry_method
return method(self, *args, **kwargs)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxtbt\ccxtstore.py", line 172, in create_order
return self.exchange.create_order(symbol=symbol, type=order_type, side=side,
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\binance.py", line 1718, in create_order
response = getattr(self, method)(self.extend(request, params))
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\base\exchange.py", line 466, in inner
return entry(_self, **inner_kwargs)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\binance.py", line 2545, in request
response = self.fetch2(path, api, method, params, headers, body)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\base\exchange.py", line 487, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\base\exchange.py", line 605, in fetch
self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\binance.py", line 2539, in handle_errors
self.throw_exactly_matched_exception(self.exceptions, error, feedback)
File "C:\Users\N\anaconda3\envs\pythonProject2\lib\site-packages\ccxt\base\exchange.py", line 505, in throw_exactly_matched_exception
raise exactstring
ccxt.base.errors.BadRequest: binance {"code":-1104,"msg":"Not all sent parameters were read; read '9' parameter(s) but was sent '10'."}Dont know how to solve, please help
-
RE: Stuck with this ---> for fill in ccxt_order['trades']: TypeError: 'NoneType' object is not iterable
@run-out thanks! this is already useful, I am going to check the repo
-
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