1 准备工作和基础知识学习
所需知识:
- Python:基础语法、变量、函数、循环
- REST API和WebSockets:与交易所通信的基础知识
- 加密货币交易所:注册、订单类型、费用
开发环境设置:
- 安装Python(最新稳定版本)
- 安装开发环境(推荐VS Code)
- 创建项目文件夹
安装必要的库:
pip install python-binance
pip install pandas
pip install numpy
pip install ta
2 从交易所获取API密钥
以Binance为例:
- 登录您的Binance账户
- 导航至API管理部分
- 创建新的API密钥
- 重要:取消勾选"启用提款"权限
- 仅保留"启用读取"和"启用现货和杠杆交易"
- 将API密钥和Secret密钥保存在安全位置
API_KEY = '您的API密钥在此'
API_SECRET = '您的API_SECRET在此'
3 编写机器人代码
创建crypto_bot.py文件并添加以下代码:
import pandas as pd
from binance.client import Client
from binance.enums import *
import time
import config
client = Client(config.API_KEY, config.API_SECRET)
TRADE_SYMBOL = 'BTCUSDT'
TRADE_QUANTITY = 0.001
PROFIT_TARGET = 1.0
STOP_LOSS = 2.0
in_position = False
buy_price = 0.0
def get_price(symbol):
try:
ticker = client.get_symbol_ticker(symbol=symbol)
return float(ticker['price'])
except Exception as e:
print(f"获取价格错误: {e}")
return None
def create_order(symbol, side, quantity):
try:
current_price = get_price(symbol)
if not current_price:
return None
if side == SIDE_BUY:
price = round(current_price * 0.995, 2)
elif side == SIDE_SELL:
price = round(current_price * 1.005, 2)
else:
return None
order = client.create_order(
symbol=symbol,
side=side,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=quantity,
price=str(price)
)
print(f"订单已下: {side} {quantity} {symbol} 价格 {price}")
return order
except Exception as e:
print(f"下单错误: {e}")
return None
这是机器人的基本结构。包含交易策略和主循环的完整代码可在完整指南中找到。