dYdX交易机器人tick-size适配问题:限价单价格格式错误求助
解决dYdX交易机器人价格tickSize适配问题
问题根源
错误提示order with price: 0.000162316 must be divisble by tickSize: 1说明你硬编码的tickSize = Decimal('0.000000001')和dYdX平台BTC-USD市场实际要求的tickSize不符,平台当前要求价格必须是1的整数倍(这里的1是平台定义的tick单位,对应实际价格的最小变动单位,必须从平台API获取准确值)。
解决方案
1. 动态获取官方市场参数
不要硬编码tickSize和数量最小变动单位,直接调用dYdX的市场信息接口获取BTC-USD的官方参数,确保完全符合平台规则。
2. 修正价格与数量的量化逻辑
用获取到的官方参数处理价格和数量,确保两者都是对应单位的整数倍,同时避免浮点数精度问题。
修改后的代码片段
# 先获取BTC-USD市场的官方参数 market_info = private_client.public.get_markets(market='BTC-USD') btc_market = market_info['markets']['BTC-USD'] tick_size = Decimal(btc_market['tickSize']) quantum_size = Decimal(btc_market['stepSize']) # stepSize对应数量的最小变动单位 # Calculate the number of coins to buy buy_price = calculate_buy_price(dollar_amount) quantity = risk_amount / buy_price # 量化数量到stepSize的整数倍 quantity = (Decimal(quantity) / quantum_size).quantize(Decimal('1'), rounding=ROUND_DOWN) * quantum_size # 量化价格到tickSize的整数倍 rounded_buy_price = (Decimal(buy_price) / tick_size).quantize(Decimal('1'), rounding=ROUND_DOWN) * tick_size buy_price_str = format(rounded_buy_price, 'f') # 用format避免科学计数法格式 # 下单逻辑 print('Buy signal detected!') print('Buying {} BTC at price {}'.format(quantity, rounded_buy_price)) buy_order = private_client.private.create_order( market='BTC-USD', side=ORDER_SIDE_BUY, position_id=1, limit_fee='0.015', order_type=ORDER_TYPE_LIMIT, price=buy_price_str, size=str(quantity), post_only=True, expiration_epoch_seconds=int(time.time()) + 600 ) print('Buy order placed. Order ID: {}'.format(buy_order['id'])) time.sleep(request_interval) # 卖出逻辑同样适配tickSize response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd') if response.status_code == 200: current_price = response.json()['bitcoin']['usd'] if float(current_price) > sell_threshold: # 卖出价格向上取整,确保更容易成交 rounded_sell_price = (Decimal(current_price) / tick_size).quantize(Decimal('1'), rounding=ROUND_UP) * tick_size print('Sell signal detected!') print('Selling all BTC at price {}'.format(rounded_sell_price)) sell_order = private_client.private.create_order( market='BTC-USD', side=ORDER_SIDE_SELL, position_id=1, limit_fee='0.015', order_type=ORDER_TYPE_LIMIT, price=format(rounded_sell_price, 'f'), size='all' ) print('Sell order placed. Order ID: {}'.format(sell_order['id']))
关键说明
- 动态参数获取:通过
get_markets接口拿到的tickSize和stepSize是平台官方定义的,彻底避免硬编码带来的适配错误。 - 字符串格式化:用
format(decimal_value, 'f')转换Decimal为字符串,防止出现平台不接受的科学计数法格式。 - 取整策略:买入时向下取整符合限价逻辑,卖出时向上取整能提高成交概率,可根据需求调整
rounding参数。
内容的提问来源于stack exchange,提问作者Gareth Cares
相关产品推荐
相关产品推荐

