快速入门
本指南演示了如何使用 Hummingbot API 添加交易所凭据、查看您的投资组合以及下市价单。
先决条件¶
- Hummingbot API 已安装并运行(参见 安装指南)
- 交易所 API 密钥(例如,Binance)
- Python 3.7+ 已安装
hummingbot-api-client
(可选)
设置 Python 客户端(可选)¶
如果您想为以下示例使用 Python 客户端:
-
创建一个新的 Python 文件(例如,
hummingbot_api_demo.py
): -
添加以下代码以初始化客户端:
-
要运行以下任何示例,请使用:
列出可用交易所¶
获取所有可用的交易所连接器列表。请注意,现货和永续市场是不同的连接器(例如,hyperliquid
用于现货,hyperliquid_perpetual
用于永续合约)。
import asyncio
from hummingbot_api_client import HummingbotAPIClient
# Create client instance
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
async def list_exchanges():
await client.init()
try:
connectors = await client.connectors.list_connectors()
print("\U0001F4CB Available exchanges/connectors:")
for connector in connectors:
print(f" - {connector}")
return connectors
finally:
await client.close()
def main():
connectors = asyncio.run(list_exchanges())
return connectors
if __name__ == "__main__":
main()
响应:
获取连接器配置¶
在添加凭据之前,检查您的连接器需要哪些配置字段:
import asyncio
from hummingbot_api_client import HummingbotAPIClient
# Create client instance
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
async def get_connector_config():
await client.init()
try:
# Get required config fields for hyperliquid
config_fields = await client.connectors.get_config_map("hyperliquid")
print("\U0001F4CB Required configuration fields for hyperliquid:")
for field in config_fields:
print(f" - {field}")
return config_fields
finally:
await client.close()
# Run the async function
config_fields = asyncio.run(get_connector_config())
响应:
添加交易所凭据¶
将您的交易所凭据添加到 API 中。默认情况下,仅创建 master_account
。您可以根据需要添加多个不同名称的账户。
对于 Hyperliquid:
hyperliquid_api_secret
:您的 Hyperliquid 公共地址或金库地址hyperliquid_api_key
:您的 API 私钥use_vault
:如果使用金库地址,请设置为true
,如果是普通账户则设置为false
import asyncio
from hummingbot_api_client import HummingbotAPIClient
# Create client instance
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
async def add_hyperliquid_credentials():
await client.init()
try:
data = {
"hyperliquid_api_key": "0x1234....abcde", # Your public/vault address
"hyperliquid_api_secret": "your-api-private-key",
"use_vault": False # True if using vault address
}
# Add credentials for hyperliquid to the 'master_account'
result = await client.accounts.add_credential("master_account", "hyperliquid", data)
print("\U0001F511 Added hyperliquid credentials:")
print(result)
return result
finally:
await client.close()
# Run the async function
asyncio.run(add_hyperliquid_credentials())
响应:
查看您的投资组合¶
检查所有已连接交易所中的投资组合余额:
import asyncio
from hummingbot_api_client import HummingbotAPIClient
# Create client instance
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
async def view_portfolio():
await client.init()
try:
# Get portfolio state
portfolio = await client.portfolio.get_state()
print(f"\n\U0001F4CA Portfolio Summary")
for account_name, exchanges in portfolio.items():
print(f"\n{account_name}:")
for exchange, balances in exchanges.items():
print(f" {exchange}:")
for balance in balances:
print(f" {balance['token']}:")
print(f" Units: {balance['units']}")
print(f" Price: ${balance['price']:.2f}")
print(f" Value: ${balance['value']:.2f}")
print(f" Available: {balance['available_units']}")
finally:
await client.close()
# Run the async function
asyncio.run(view_portfolio())
响应:
获取交易规则¶
下订单之前,请获取您预期交易对的交易规则,以了解订单大小限制和价格增量:
import asyncio
from hummingbot_api_client import HummingbotAPIClient
async def get_trading_rules():
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
await client.init()
try:
# Get trading rules for HYPE-USDC
rules = await client.connectors.get_trading_rules(
connector_name="hyperliquid",
trading_pairs=["HYPE-USDC"]
)
hype_rules = rules["HYPE-USDC"]
print("\U0001F4CF Trading Rules for HYPE-USDC:")
print(f" Min Order Size: {hype_rules['min_order_size']}")
print(f" Max Order Size: {hype_rules['max_order_size']}")
print(f" Min Price Increment: {hype_rules['min_price_increment']}")
print(f" Min Base Amount Increment: {hype_rules['min_base_amount_increment']}")
print(f" Supports Limit Orders: {hype_rules['supports_limit_orders']}")
print(f" Supports Market Orders: {hype_rules['supports_market_orders']}")
return rules
finally:
await client.close()
# Run the async function
if __name__ == "__main__":
asyncio.run(get_trading_rules())
响应:
{
"HYPE-USDC": {
"min_order_size": 0,
"max_order_size": 1e+56,
"min_price_increment": 0.0001,
"min_base_amount_increment": 0.01,
"min_quote_amount_increment": 1e-56,
"min_notional_size": 0,
"min_order_value": 0,
"max_price_significant_digits": 1e+56,
"supports_limit_orders": true,
"supports_market_orders": true,
"buy_order_collateral_token": "USDC",
"sell_order_collateral_token": "USDC"
}
}
下限价单¶
执行 HYPE 的限价卖单:
curl -u admin:admin -X 'POST' \
'http://localhost:8000/trading/orders' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"account_name": "master_account",
"connector_name": "hyperliquid",
"trading_pair": "HYPE-USDC",
"trade_type": "SELL",
"amount": 1,
"order_type": "LIMIT",
"price": 47.1,
"position_action": "OPEN"
}'
import asyncio
from hummingbot_api_client import HummingbotAPIClient
# Create client instance
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
async def place_limit_order():
await client.init()
try:
# Place a limit sell order
order = await client.trading.place_order(
account_name="master_account",
connector_name="hyperliquid",
trading_pair="HYPE-USDC",
trade_type="SELL",
amount=1,
order_type="LIMIT",
price=47.1,
position_action="OPEN"
)
print(f"\n✅ Order Placed Successfully!")
print(f" Order ID: {order['order_id']}")
print(f" Status: {order['status']}")
print(f" Connector: {order['connector_name']}")
print(f" Trading Pair: {order['trading_pair']}")
print(f" Type: {order['order_type']} {order['trade_type']}")
print(f" Amount: {order['amount']} HYPE")
print(f" Price: ${order['price']}")
return order
finally:
await client.close()
# Run the async function
asyncio.run(place_limit_order())
地理位置限制错误
如果您收到如下错误:
这可能表示您在该交易所交易时受到地理位置限制。请查看您的 API 日志以获取更多详细信息:完整示例¶
这是一个执行所有三个操作的完整示例:
echo "🔑 Adding Exchange Account..."
curl -X POST "http://localhost:8000/accounts/add-account" \
-u "admin:admin" \
-H "Content-Type: application/json" \
-d '{"account_name": "master_account"}'
# Step 2: Add credentials for hyperliquid
curl -X POST "http://localhost:8000/accounts/add-credential/master_account/hyperliquid" \
-u "admin:admin" \
-H "Content-Type: application/json" \
-d '{
"hyperliquid_api_key": "0x1234...abcd",
"hyperliquid_api_secret": "your-arbitrum-private-key",
"use_vault": false
}'
# Wait for account sync
sleep 2
# Step 3: View portfolio
echo -e "\n\U0001F4CA Fetching Portfolio..."
curl -X POST "http://localhost:8000/portfolio/state" \
-u "admin:admin" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d '{}'
# Step 4: Get trading rules for HYPE-USDC
echo -e "\n\U0001F4CF Getting Trading Rules..."
curl -X GET "http://localhost:8000/connectors/hyperliquid/trading-rules?trading_pairs=HYPE-USDC" \
-u "admin:admin" \
-H "accept: application/json"
# Step 5: Place limit order
echo -e "\n\U0001F4B1 Placing Limit Order..."
curl -X POST "http://localhost:8000/trading/orders" \
-u "admin:admin" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"account_name": "master_account",
"connector_name": "hyperliquid",
"trading_pair": "HYPE-USDC",
"trade_type": "SELL",
"amount": 1,
"order_type": "LIMIT",
"price": 47.1,
"position_action": "OPEN"
}'
将此代码保存到 hummingbot_api_demo.py
:
import asyncio
from hummingbot_api_client import HummingbotAPIClient
async def main():
# Initialize client
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="admin",
password="admin"
)
await client.init()
try:
# Step 1: Add exchange account
print("🔑 Adding Exchange Account...")
try:
account = await client.accounts.add_account(
account_name="master_account"
)
print(f"✓ Account '{account['account_name']}' added successfully!")
except Exception as e:
if "Account already exists" in str(e):
print("ℹ️ Account already exists, continuing...")
else:
raise
# Step 2: Add credentials for hyperliquid
print("\n🔑 Adding Hyperliquid Credentials...")
credentials = {
"hyperliquid_api_key": "0x1234...abcd",
"hyperliquid_api_secret": "your-arbitrum-private-key",
"use_vault": False
}
cred_result = await client.accounts.add_credential(
account_name="master_account",
connector_name="hyperliquid",
credentials=credentials
)
print(f"✓ Credentials added: {cred_result}")
# Wait for account sync
await asyncio.sleep(2)
# Step 3: View portfolio
print("\n📊 Fetching Portfolio...")
portfolio = await client.portfolio.get_state()
print("Portfolio State:")
for account, exchanges in portfolio.items():
for exchange, balances in exchanges.items():
for balance in balances:
print(f" {account}/{exchange}: {balance['units']:.2f} {balance['token']} (${balance['value']:.2f})")
# Step 4: Get trading rules
print("\n📏 Getting Trading Rules for HYPE-USDC...")
rules = await client.connectors.get_trading_rules(
connector_name="hyperliquid",
trading_pairs=["HYPE-USDC"]
)
hype_rules = rules["HYPE-USDC"]
print(f" Min Order Size: {hype_rules['min_order_size']}")
print(f" Min Price Increment: {hype_rules['min_price_increment']}")
# Step 5: Place limit order
print("\n💱 Placing Limit Order...")
order = await client.trading.place_order(
account_name="master_account",
connector_name="hyperliquid",
trading_pair="HYPE-USDC",
trade_type="SELL",
amount=1,
order_type="LIMIT",
price=47.1,
position_action="OPEN"
)
print(f"✓ Order {order['order_id']} submitted")
print(f" Status: {order['status']}")
print(f" Type: {order['order_type']} {order['trade_type']}")
print(f" Amount: {order['amount']} HYPE @ ${order['price']}")
except Exception as e:
print(f"❌ Error: {e}")
finally:
await client.close()
# Run the complete example
if __name__ == "__main__":
asyncio.run(main())
运行脚本:
下一步¶
现在您已完成快速入门,请探索更多高级功能:
API 运行时,请访问 API 文档以获取完整的 API 参考。