使用CCXT与Bybit时如何修复retCode:170003错误?
问题描述
用Python+CCXT开发Bybit交易机器人,计划用50 USDT市价买入BTC/USDT,同时设置0.33%止损和0.45%止盈,但运行时报错:
"Market order failed with error: bybit {"retCode":170003,"retMsg":"An unknown parameter was sent.","result":{},"retExtInfo":{},"time":1698675395747}"
用户代码如下:
# Define your Bybit API credentials api_key = '<Here is my api key>' api_secret = '<Here is my screct api key>' # Initialize the Bybit exchange exchange = ccxt.bybit({ 'apiKey': api_key, 'secret': api_secret, 'enableRateLimit': True, }) # Set the option to allow market buy orders without price exchange.options["createMarketBuyOrderRequiresPrice"] = False # Define trading parameters symbol = 'BTC/USDT' cost_in_usdt = 50 # The cost of the buy order in USDT entry_price = None # Market order, so entry price is not specified stop_loss_percent = 0.0033 # 0.33% stop loss as a float (0.33% = 0.0033) take_profit = 0.0045 # 0.45% take profit as a float (0.45% = 0.0045) # Get the current market price ticker = exchange.fetch_ticker(symbol) market_price = ticker['last'] # Calculate the quantity of BTC to buy quantity = cost_in_usdt / market_price # Place a market order to buy BTC/USDT try: market_order = exchange.create_order( symbol, 'market', 'buy', quantity ) print(f"Market order to buy {quantity} BTC placed at market price.") # Update the entry price based on the market order response entry_price = market_order['price'] # Calculate stop loss and take profit prices stop_loss_price = entry_price * (1 - stop_loss_percent) take_profit_price = entry_price * (1 + take_profit) # Place a stop market sell order (stop loss) stop_loss_order = exchange.create_order( symbol, 'limit', 'sell', quantity, stop_loss_price, {'stopPrice': stop_loss_price} ) # Place a take profit market sell order take_profit_order = exchange.create_order( symbol, 'market', 'sell', quantity ) print(f"Stop loss order placed at {stop_loss_price}.") print(f"Take profit order placed at {take_profit_price}.") except Exception as e: print(f"Market order failed with error: {str(e)}")
修复方案
核心问题分析
报错170003是因为传入了Bybit不识别的参数,根源在于:
- 未明确指定交易类型(现货/合约),Bybit默认是合约模式,现货交易参数不匹配
- 止损/止盈订单类型错误,用普通限价单+
stopPrice不符合平台规则 - 手动计算的数量/价格可能不符合平台精度要求
修复后的完整代码
# Define your Bybit API credentials api_key = '<Here is my api key>' api_secret = '<Here is my screct api key>' # Initialize the Bybit exchange,明确指定现货交易类型 exchange = ccxt.bybit({ 'apiKey': api_key, 'secret': api_secret, 'enableRateLimit': True, 'options': { 'defaultType': 'spot' } }) # Define trading parameters symbol = 'BTC/USDT' cost_in_usdt = 50 # 买入金额(USDT) stop_loss_percent = 0.0033 # 0.33%止损 take_profit_percent = 0.0045 # 0.45%止盈 try: # 直接用专用方法市价买入,自动处理数量精度 market_order = exchange.create_market_buy_order(symbol, cost_in_usdt) print(f"市价买入成交:{market_order}") # 获取实际成交均价和数量 entry_price = float(market_order['average']) quantity = float(market_order['amount']) # 计算止损/止盈价格 stop_loss_price = entry_price * (1 - stop_loss_percent) take_profit_price = entry_price * (1 + take_profit_percent) # 处理价格精度,匹配平台要求 stop_loss_price = exchange.price_to_precision(symbol, stop_loss_price) take_profit_price = exchange.price_to_precision(symbol, take_profit_price) # 挂市价止损单 stop_loss_order = exchange.create_order( symbol, 'stop_market', 'sell', quantity, None, # 市价止损无需指定成交价格 {'stopPrice': stop_loss_price} ) print(f"止损单已挂:{stop_loss_order}") # 挂市价止盈单 take_profit_order = exchange.create_order( symbol, 'take_profit_market', 'sell', quantity, None, {'takeProfitPrice': take_profit_price} ) print(f"止盈单已挂:{take_profit_order}") except Exception as e: print(f"订单执行失败:{str(e)}")
关键修复点说明
- 指定交易类型:初始化时添加
'defaultType': 'spot',避免默认合约模式导致的参数不兼容 - 使用专用市价买入方法:
create_market_buy_order直接传入USDT金额,自动处理数量精度,无需手动计算 - 止损/止盈订单类型匹配:用
stop_market和take_profit_market类型,对应参数stopPrice和takeProfitPrice,符合Bybit规则 - 精度处理:通过
price_to_precision确保价格符合平台小数位数要求,避免参数格式错误
内容的提问来源于stack exchange,提问作者Backersbtc
相关产品推荐
相关产品推荐

