├── .gitattributes └── readme.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Backpack API 操作指南 2 | 3 | 本文档提供了使用Backpack交易所API进行各种操作的详细指南。 4 | 5 | ## 初始化API客户端 6 | 7 | ```python 8 | from funding_arbitrage_bot.exchanges.backpack_api import BackpackAPI 9 | 10 | # 初始化API客户端 11 | backpack_api = BackpackAPI( 12 | api_key="您的API密钥", 13 | api_secret="您的API密钥", 14 | base_url="https://api.backpack.exchange", # 主网API地址 15 | ws_url="wss://ws.backpack.exchange", # WebSocket地址 16 | logger=logger # 可选,传入日志对象 17 | ) 18 | 19 | # 启动价格数据流(实时价格更新) 20 | await backpack_api.start_ws_price_stream() 21 | ``` 22 | 23 | ## 价格和资金费率操作 24 | 25 | ### 获取价格 26 | 27 | ```python 28 | # 获取单个交易对价格 29 | price = await backpack_api.get_price("BTC_USDC_PERP") 30 | print(f"比特币价格: {price}") 31 | 32 | # 通过WebSocket获取的最新价格(需要先启动价格数据流) 33 | btc_price = backpack_api.prices.get("BTC_USDC_PERP") 34 | ``` 35 | 36 | ### 获取资金费率 37 | 38 | ```python 39 | # 获取单个交易对的资金费率 40 | funding_rate = await backpack_api.get_funding_rate("BTC_USDC_PERP") 41 | print(f"比特币资金费率: {funding_rate}") 42 | 43 | # 获取所有交易对的资金费率 44 | all_funding_rates = await backpack_api.get_all_funding_rates() 45 | for symbol, rate in all_funding_rates.items(): 46 | print(f"{symbol} 资金费率: {rate}") 47 | ``` 48 | 49 | ## 订单操作 50 | 51 | ### 下单 52 | 53 | ```python 54 | # 市价买入 55 | market_buy_order = await backpack_api.place_order( 56 | symbol="BTC_USDC_PERP", 57 | side="BUY", 58 | quantity=0.001, # 购买0.001个BTC 59 | order_type="MARKET" # 市价单 60 | ) 61 | 62 | # 限价卖出 63 | limit_sell_order = await backpack_api.place_order( 64 | symbol="ETH_USDC_PERP", 65 | side="SELL", 66 | quantity=0.01, # 卖出0.01个ETH 67 | price=2000, # 限价2000美元 68 | order_type="LIMIT" # 限价单 69 | ) 70 | 71 | # 可选参数:post_only(只做挂单) 72 | post_only_order = await backpack_api.place_order( 73 | symbol="SOL_USDC_PERP", 74 | side="BUY", 75 | quantity=1, 76 | price=100, 77 | order_type="LIMIT", 78 | post_only=True # 确保订单只作为maker 79 | ) 80 | 81 | # 可选参数:reduce_only(只减仓不加仓) 82 | reduce_only_order = await backpack_api.place_order( 83 | symbol="BTC_USDC_PERP", 84 | side="SELL", 85 | quantity=0.001, 86 | order_type="MARKET", 87 | reduce_only=True # 确保此订单只会减少现有仓位 88 | ) 89 | ``` 90 | 91 | ### 使用深度数据下单 92 | 93 | ```python 94 | # 使用订单簿深度数据下单,确保更好的成交价格 95 | order_with_depth = await backpack_api.place_order_with_depth( 96 | symbol="BTC_USDC_PERP", 97 | side="BUY", 98 | quantity=0.001, 99 | order_type="LIMIT", 100 | depth_tolerance=0.001 # 价格容忍度,基于最佳卖价 101 | ) 102 | ``` 103 | 104 | ### 查询订单状态 105 | 106 | ```python 107 | # 通过订单ID查询订单状态 108 | order_status = await backpack_api.get_order_status("BTC_USDC_PERP", "order_id_here") 109 | print(f"订单状态: {order_status}") 110 | 111 | # 查询所有未成交订单 112 | open_orders = await backpack_api.get_open_orders() 113 | for order in open_orders: 114 | print(f"订单ID: {order['orderId']}, 交易对: {order['symbol']}, 类型: {order['type']}") 115 | ``` 116 | 117 | ### 取消订单 118 | 119 | ```python 120 | # 取消特定订单 121 | cancel_result = await backpack_api.cancel_order("BTC_USDC_PERP", "order_id_here") 122 | 123 | # 取消特定交易对的所有订单 124 | cancel_all_result = await backpack_api.cancel_all_orders("BTC_USDC_PERP") 125 | 126 | # 取消所有订单 127 | cancel_all_result = await backpack_api.cancel_all_orders() 128 | ``` 129 | 130 | ## 仓位操作 131 | 132 | ### 查询持仓 133 | 134 | ```python 135 | # 查询单个交易对的持仓 136 | btc_position = await backpack_api.get_position("BTC_USDC_PERP") 137 | if btc_position: 138 | print(f"方向: {'多' if btc_position['quantity'] > 0 else '空'}, 数量: {abs(btc_position['quantity'])}") 139 | print(f"入场价: {btc_position['entryPrice']}, 未实现盈亏: {btc_position['unrealizedProfit']}") 140 | 141 | # 查询所有持仓 142 | all_positions = await backpack_api.get_positions() 143 | for position in all_positions: 144 | if float(position['quantity']) != 0: # 只显示有仓位的交易对 145 | print(f"{position['symbol']} - 方向: {'多' if float(position['quantity']) > 0 else '空'}, 数量: {abs(float(position['quantity']))}") 146 | ``` 147 | 148 | ### 平仓 149 | 150 | ```python 151 | # 全部平仓 152 | if float(btc_position['quantity']) > 0: # 如果是多仓 153 | close_result = await backpack_api.place_order( 154 | symbol="BTC_USDC_PERP", 155 | side="SELL", # 卖出平多 156 | quantity=abs(float(btc_position['quantity'])), 157 | order_type="MARKET", 158 | reduce_only=True 159 | ) 160 | else: # 如果是空仓 161 | close_result = await backpack_api.place_order( 162 | symbol="BTC_USDC_PERP", 163 | side="BUY", # 买入平空 164 | quantity=abs(float(btc_position['quantity'])), 165 | order_type="MARKET", 166 | reduce_only=True 167 | ) 168 | 169 | # 部分平仓 170 | partial_close = await backpack_api.place_order( 171 | symbol="BTC_USDC_PERP", 172 | side="SELL" if float(btc_position['quantity']) > 0 else "BUY", 173 | quantity=abs(float(btc_position['quantity'])) / 2, # 平仓一半 174 | order_type="MARKET", 175 | reduce_only=True 176 | ) 177 | ``` 178 | 179 | ## 订单簿(深度)数据 180 | 181 | ```python 182 | # 获取订单簿深度数据 183 | orderbook = await backpack_api.get_orderbook("BTC_USDC_PERP") 184 | 185 | if orderbook: 186 | # 显示最优买价和卖价 187 | best_bid = orderbook["bids"][0] if orderbook["bids"] else None 188 | best_ask = orderbook["asks"][0] if orderbook["asks"] else None 189 | 190 | if best_bid: 191 | print(f"最优买价: {best_bid[0]}, 数量: {best_bid[1]}") 192 | if best_ask: 193 | print(f"最优卖价: {best_ask[0]}, 数量: {best_ask[1]}") 194 | 195 | # 计算买单总量(前5档) 196 | bid_volume = sum(float(bid[1]) for bid in orderbook["bids"][:5]) 197 | # 计算卖单总量(前5档) 198 | ask_volume = sum(float(ask[1]) for ask in orderbook["asks"][:5]) 199 | 200 | print(f"买单总量(前5档): {bid_volume}") 201 | print(f"卖单总量(前5档): {ask_volume}") 202 | ``` 203 | 204 | ## 账户信息 205 | 206 | ```python 207 | # 获取账户余额 208 | balances = await backpack_api.get_balances() 209 | for balance in balances: 210 | print(f"{balance['asset']} 可用余额: {balance['available']}, 冻结余额: {balance['locked']}") 211 | 212 | # 获取账户信息 213 | account_info = await backpack_api.get_account_info() 214 | print(f"账户状态: {account_info['status']}") 215 | print(f"手续费等级: {account_info['commissionTier']}") 216 | ``` 217 | 218 | ## WebSocket订阅 219 | 220 | ```python 221 | # 启动和监听价格流 222 | await backpack_api.start_ws_price_stream() 223 | 224 | # 获取最新价格(从缓存) 225 | btc_price = backpack_api.prices.get("BTC_USDC_PERP", 0) # 默认返回0如果价格不可用 226 | 227 | # 如果需要通过回调处理价格更新 228 | async def price_callback(symbol, price): 229 | print(f"价格更新: {symbol} = {price}") 230 | 231 | # 注册回调 232 | backpack_api.register_price_callback(price_callback) 233 | ``` 234 | 235 | ## 错误处理 236 | 237 | 所有API方法都内置了错误处理机制,但在应用程序中,您仍然应该捕获可能的异常: 238 | 239 | ```python 240 | try: 241 | # 尝试调用API 242 | result = await backpack_api.place_order(...) 243 | 244 | # 检查返回结果是否包含错误信息 245 | if "code" in result and result["code"] != 0: 246 | print(f"操作失败: {result['msg']}") 247 | else: 248 | print("操作成功!") 249 | 250 | except Exception as e: 251 | print(f"发生异常: {e}") 252 | ``` 253 | 254 | ## 实用提示 255 | 256 | 1. **交易对格式**:Backpack使用`BTC_USDC_PERP`这样的格式表示交易对,特别注意永续合约后缀`_PERP`。 257 | 258 | 2. **保持WebSocket连接**:使用`start_ws_price_stream()`方法可以维持WebSocket连接并持续更新价格数据,确保获取最新的市场价格。 259 | 260 | 3. **资金费率周期**:了解Backpack的资金费率结算周期(通常为每8小时一次),规划交易时机。 261 | 262 | 4. **日志级别**:调整日志级别以获取更详细的信息: 263 | ```python 264 | import logging 265 | logging.basicConfig(level=logging.DEBUG) # 设置为DEBUG级别获取详细日志 266 | ``` 267 | 268 | 5. **仓位同步**:定期调用`get_positions()`同步当前仓位信息,确保本地状态与交易所状态一致。 269 | 270 | 6. **WebSocket断线重连**:如果使用WebSocket长时间运行,建议实现断线重连机制: 271 | ```python 272 | while True: 273 | try: 274 | await backpack_api.start_ws_price_stream() 275 | # 保持连接运行 276 | await asyncio.sleep(3600) # 每小时检查一次 277 | except Exception as e: 278 | print(f"WebSocket断开: {e}") 279 | await asyncio.sleep(5) # 等待5秒后重连 280 | ``` 281 | 282 | ## 示例:执行简单的套利策略 283 | 284 | ```python 285 | async def simple_arbitrage_example(): 286 | # 获取价格和资金费率 287 | btc_price = await backpack_api.get_price("BTC_USDC_PERP") 288 | btc_funding_rate = await backpack_api.get_funding_rate("BTC_USDC_PERP") 289 | 290 | # 基于资金费率决定方向 291 | if btc_funding_rate > 0.0001: # 正资金费率超过某个阈值 292 | # 做空,因为可以收取资金费 293 | order = await backpack_api.place_order( 294 | symbol="BTC_USDC_PERP", 295 | side="SELL", # 卖出/做空 296 | quantity=0.001, 297 | order_type="MARKET" 298 | ) 299 | print(f"做空订单已提交: {order}") 300 | elif btc_funding_rate < -0.0001: # 负资金费率超过某个阈值 301 | # 做多,因为可以收取资金费 302 | order = await backpack_api.place_order( 303 | symbol="BTC_USDC_PERP", 304 | side="BUY", # 买入/做多 305 | quantity=0.001, 306 | order_type="MARKET" 307 | ) 308 | print(f"做多订单已提交: {order}") 309 | else: 310 | print("资金费率在阈值范围内,不操作") 311 | ``` 312 | 313 | ## 常见问题排查 314 | 315 | 1. **API密钥权限**:确保API密钥有足够的权限执行相应操作,特别是交易需要的写入权限。 316 | 317 | 2. **订单参数格式**:确保传递正确的参数格式,例如数量和价格应该是字符串或浮点数,而不是整数。 318 | 319 | 3. **价格精度**:不同交易对对价格和数量的精度要求不同,确保遵循Backpack的精度要求。 320 | 321 | 4. **交易量限制**:注意某些交易对可能有最小和最大交易量限制,确保下单数量在允许范围内。 322 | 323 | 5. **API请求限制**:Backpack可能对API请求频率有限制,如果收到限流错误,考虑减少请求频率或实现指数退避机制。 324 | 325 | 6. **订单类型大写**:确保订单类型(如"MARKET"、"LIMIT")和交易方向(如"BUY"、"SELL")使用全大写格式,这是Backpack API的要求。 --------------------------------------------------------------------------------