Trade
exchange.Buy()
以限价单方式买入。
语法
python
order_id = exchange.Buy(price, amount)参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| price | float | 是 | 买入价格 |
| amount | float | 是 | 买入数量 |
返回值
str: 订单ID,用于后续查询和取消订单
示例
基础用法
python
# 以50000价格买入0.1个BTC
order_id = exchange.Buy(50000, 0.1)
Log("买单已提交,订单ID:", order_id)市价买入(以对手价)
python
def market_buy(amount):
"""模拟市价买入"""
depth = exchange.GetDepth()
price = depth['Asks'][0][0] # 取卖一价
order_id = exchange.Buy(price, amount)
Log(f"市价买入: 价格 {price}, 数量 {amount}, 订单ID {order_id}")
return order_id
order_id = market_buy(0.1)按百分比买入
python
def buy_by_percentage(percentage=50):
"""使用指定百分比的可用余额买入"""
account = exchange.GetAccount()
ticker = exchange.GetTicker()
# 计算可用资金
available = account['Balance'] * (percentage / 100)
# 计算买入数量
price = ticker['Last']
amount = available / price
# 调整精度
amount = round(amount, 6) # 假设6位精度
if amount > 0:
order_id = exchange.Buy(price, amount)
Log(f"买入{percentage}%仓位: {amount} @ {price}, 订单ID: {order_id}")
return order_id
else:
Log("可用余额不足")
return None
# 使用50%的余额买入
buy_by_percentage(50)分批买入
python
def grid_buy(start_price, end_price, num_orders, total_amount):
"""网格买入"""
price_step = (start_price - end_price) / (num_orders - 1)
amount_per_order = total_amount / num_orders
order_ids = []
for i in range(num_orders):
price = start_price - (i * price_step)
order_id = exchange.Buy(price, amount_per_order)
order_ids.append(order_id)
Log(f"挂单{i+1}: 价格 {price:.2f}, 数量 {amount_per_order:.6f}")
return order_ids
# 在49000-48000之间挂5个买单,总共买入0.5个BTC
orders = grid_buy(49000, 48000, 5, 0.5)
Log(f"已挂{len(orders)}个买单")追踪止损买入
python
def trailing_buy(target_amount, trail_percent=1):
"""追踪买入:价格下跌时追踪,反弹时买入"""
lowest_price = None
while True:
ticker = exchange.GetTicker()
current_price = ticker['Last']
# 更新最低价
if lowest_price is None or current_price < lowest_price:
lowest_price = current_price
Log(f"更新最低价: {lowest_price:.2f}")
# 计算反弹幅度
rebound = ((current_price - lowest_price) / lowest_price) * 100
# 反弹超过指定百分比时买入
if rebound >= trail_percent:
order_id = exchange.Buy(current_price, target_amount)
Log(f"触发买入: 价格 {current_price:.2f}, 反弹 {rebound:.2f}%")
return order_id
Sleep(1000) # 1秒检查一次
# 追踪买入,反弹1%时触发
trailing_buy(0.1, trail_percent=1)智能买入(带验证)
python
def smart_buy(price, amount):
"""智能买入:自动验证并调整参数"""
# 1. 获取精度信息
precisions = exchange.GetCurrenciesPrecision()
currency = exchange.GetCurrency()
symbol = currency.replace("_", "")
precision = precisions.get(symbol)
if precision:
# 调整价格和数量精度
price = round(price, precision["price_precision"])
amount = round(amount, precision["amount_precision"])
# 验证最小数量
if amount < precision["min_qty"]:
Log(f"数量太小: {amount} < {precision['min_qty']}")
return None
# 验证最小交易额
notional = price * amount
if notional < precision["min_notional"]:
Log(f"交易额太小: {notional} < {precision['min_notional']}")
return None
# 2. 检查余额
account = exchange.GetAccount()
required = price * amount
if account['Balance'] < required:
Log(f"余额不足: 需要 {required:.2f}, 可用 {account['Balance']:.2f}")
return None
# 3. 执行买入
try:
order_id = exchange.Buy(price, amount)
Log(f"买入成功: {amount} @ {price}, 订单ID: {order_id}")
return order_id
except Exception as e:
Log(f"买入失败: {str(e)}")
return None
# 使用
smart_buy(50000, 0.1)等待成交
python
def buy_and_wait(price, amount, timeout=60000):
"""买入并等待成交"""
order_id = exchange.Buy(price, amount)
Log(f"订单已提交: {order_id}")
start_time = _D() # 记录开始时间
while True:
order = exchange.GetOrder(order_id)
if order is None:
Log("订单不存在")
return None
if order['Status'] == 'closed':
Log(f"订单已完全成交: {order['DealAmount']}")
return order
# 检查超时
elapsed = _D() - start_time
if elapsed > timeout:
Log("等待超时,取消订单")
exchange.CancelOrder(order_id)
return None
Sleep(1000) # 1秒检查一次
# 买入并等待60秒
buy_and_wait(50000, 0.1, timeout=60000)注意事项
- 限价单:Buy() 是限价单,不保证立即成交
- 精度要求:价格和数量必须符合交易所精度要求
- 余额检查:下单前确保余额充足
- 订单管理:保存 order_id 用于后续查询和取消
python
# 推荐做法
try:
order_id = exchange.Buy(50000, 0.1)
if order_id:
Log("下单成功:", order_id)
# 保存订单ID供后续使用
except Exception as e:
Log("下单失败:", str(e))相关方法
- Sell - 卖出下单
- CancelOrder - 取消订单
- GetOrder - 查询订单
- GetOrders - 获取未完成订单
- GetAccount - 获取账户信息