fix bug to make process correct
This commit is contained in:
parent
d1079d338d
commit
b1c3af6489
Binary file not shown.
17
config.py
17
config.py
|
|
@ -1,10 +1,13 @@
|
||||||
# OKX API 配置
|
# OKX API 配置
|
||||||
# 请将以下信息替换为你的实际API密钥
|
# 请将以下信息替换为你的实际API密钥
|
||||||
|
|
||||||
# API密钥配置
|
# API密钥配置
|
||||||
API_KEY = "your_api_key_here"
|
# API_KEY = "7286d434-225b-401f-b3af-fd595e15d23f"
|
||||||
SECRET_KEY = "your_secret_key_here"
|
# SECRET_KEY = "80B95C5757F9208F70282A85C9DDBC86"
|
||||||
PASSPHRASE = "your_passphrase_here"
|
# PASSPHRASE = "Bengbu_2001"
|
||||||
|
# 模拟盘API密钥配置
|
||||||
|
API_KEY = "f309e789-3497-4ed3-896f-d18bdc4d9817"
|
||||||
|
SECRET_KEY = "9152809391B110E2E647FDE12A37E96D"
|
||||||
|
PASSPHRASE = "Bengbu@2001"
|
||||||
|
|
||||||
# 交易配置
|
# 交易配置
|
||||||
TRADING_CONFIG = {
|
TRADING_CONFIG = {
|
||||||
|
|
@ -21,12 +24,12 @@ TRADING_CONFIG = {
|
||||||
|
|
||||||
# 网格交易参数
|
# 网格交易参数
|
||||||
"grid_levels": 5, # 网格数量
|
"grid_levels": 5, # 网格数量
|
||||||
"grid_range": 0.02, # 网格范围(2%)
|
"grid_range": 0.005, # 网格范围(0.5%)
|
||||||
|
|
||||||
# 风险控制
|
# 风险控制
|
||||||
"max_position": 0.01, # 最大持仓量(BTC)
|
"max_position": 0.01, # 最大持仓量(BTC)
|
||||||
"stop_loss_pct": 0.05, # 止损百分比(5%)
|
"stop_loss_pct": 0.005, # 止损百分比(0.5%)
|
||||||
"take_profit_pct": 0.10, # 止盈百分比(10%)
|
"take_profit_pct": 0.01, # 止盈百分比(1%)
|
||||||
}
|
}
|
||||||
|
|
||||||
# 时间间隔配置
|
# 时间间隔配置
|
||||||
|
|
|
||||||
146
play.py
146
play.py
|
|
@ -1,7 +1,7 @@
|
||||||
import okx.api.account as Account
|
import okx.Account as Account
|
||||||
import okx.api.trade as Trade
|
import okx.Trade as Trade
|
||||||
import okx.api.market as Market
|
import okx.MarketData as Market
|
||||||
import okx.api.public as Public
|
import okx.PublicData as Public
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import time
|
import time
|
||||||
|
|
@ -24,23 +24,23 @@ class BitcoinQuantTrader:
|
||||||
self.passphrase = passphrase
|
self.passphrase = passphrase
|
||||||
|
|
||||||
# 初始化API客户端
|
# 初始化API客户端
|
||||||
flag = "0" if sandbox else "1" # 0:沙盒环境 1:实盘环境
|
flag = "1" if sandbox else "0" # 0:实盘环境 1:沙盒环境
|
||||||
|
|
||||||
self.account_api = Account.Account(
|
self.account_api = Account.AccountAPI(
|
||||||
api_key, secret_key, passphrase,
|
api_key=api_key, api_secret_key=secret_key, passphrase=passphrase,
|
||||||
flag=flag, debug=False
|
flag=flag
|
||||||
)
|
)
|
||||||
self.trade_api = Trade.Trade(
|
self.trade_api = Trade.TradeAPI(
|
||||||
api_key, secret_key, passphrase,
|
api_key=api_key, api_secret_key=secret_key, passphrase=passphrase,
|
||||||
flag=flag, debug=False
|
flag=flag
|
||||||
)
|
)
|
||||||
self.market_api = Market.Market(
|
self.market_api = Market.MarketAPI(
|
||||||
api_key, secret_key, passphrase,
|
api_key=api_key, api_secret_key=secret_key, passphrase=passphrase,
|
||||||
flag=flag, debug=False
|
flag=flag
|
||||||
)
|
)
|
||||||
self.public_api = Public.Public(
|
self.public_api = Public.PublicAPI(
|
||||||
api_key, secret_key, passphrase,
|
api_key=api_key, api_secret_key=secret_key, passphrase=passphrase,
|
||||||
flag=flag, debug=False
|
flag=flag
|
||||||
)
|
)
|
||||||
|
|
||||||
self.symbol = "BTC-USDT"
|
self.symbol = "BTC-USDT"
|
||||||
|
|
@ -53,12 +53,14 @@ class BitcoinQuantTrader:
|
||||||
if result['code'] == '0':
|
if result['code'] == '0':
|
||||||
balances = result['data']
|
balances = result['data']
|
||||||
for balance in balances:
|
for balance in balances:
|
||||||
if balance['ccy'] == 'USDT':
|
details = balance['details']
|
||||||
print(f"USDT余额: {balance['bal']}")
|
for detail in details:
|
||||||
return float(balance['bal'])
|
if detail['ccy'] == 'USDT':
|
||||||
elif balance['ccy'] == 'BTC':
|
print(f"USDT余额: {detail['availBal']}")
|
||||||
print(f"BTC余额: {balance['bal']}")
|
return float(detail['availBal'])
|
||||||
return float(balance['bal'])
|
elif detail['ccy'] == 'BTC':
|
||||||
|
print(f"BTC余额: {detail['availBal']}")
|
||||||
|
# return float(detail['availBal'])
|
||||||
else:
|
else:
|
||||||
print(f"获取余额失败: {result}")
|
print(f"获取余额失败: {result}")
|
||||||
return 0
|
return 0
|
||||||
|
|
@ -92,7 +94,8 @@ class BitcoinQuantTrader:
|
||||||
if result['code'] == '0':
|
if result['code'] == '0':
|
||||||
# 转换为DataFrame
|
# 转换为DataFrame
|
||||||
df = pd.DataFrame(result['data'], columns=[
|
df = pd.DataFrame(result['data'], columns=[
|
||||||
'timestamp', 'open', 'high', 'low', 'close', 'volume', 'volCcy'
|
'timestamp', 'open', 'high', 'low', 'close',
|
||||||
|
'volume', 'volCcy', "volCCyQuote", "confirm"
|
||||||
])
|
])
|
||||||
# 转换数据类型
|
# 转换数据类型
|
||||||
for col in ['open', 'high', 'low', 'close', 'volume']:
|
for col in ['open', 'high', 'low', 'close', 'volume']:
|
||||||
|
|
@ -121,23 +124,61 @@ class BitcoinQuantTrader:
|
||||||
|
|
||||||
def place_market_order(self, side, size):
|
def place_market_order(self, side, size):
|
||||||
"""下市价单"""
|
"""下市价单"""
|
||||||
try:
|
if side == 'sell':
|
||||||
result = self.trade_api.place_order(
|
try:
|
||||||
instId=self.symbol,
|
result = self.trade_api.place_order(
|
||||||
tdMode='cash',
|
instId=self.symbol,
|
||||||
side=side,
|
tdMode='cash',
|
||||||
ordType='market',
|
side=side,
|
||||||
sz=str(size)
|
ordType='market',
|
||||||
)
|
sz=str(size)
|
||||||
if result['code'] == '0':
|
)
|
||||||
print(f"下单成功: {side} {size} BTC")
|
if result['code'] == '0':
|
||||||
return result['data'][0]['ordId']
|
print(f"下单成功: {side} {size} BTC")
|
||||||
else:
|
return result['data'][0]['ordId']
|
||||||
print(f"下单失败: {result}")
|
else:
|
||||||
|
print(f"下单失败: {result}")
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
print(f"下单异常: {e}")
|
||||||
return None
|
return None
|
||||||
|
elif side == 'buy':
|
||||||
|
instrument = self.public_api.get_instruments(instType="SPOT", instId=self.symbol)["data"][0]
|
||||||
|
min_sz = float(instrument["minSz"]) # 最小交易量
|
||||||
|
if size < min_sz:
|
||||||
|
size = min_sz
|
||||||
|
ticker = self.market_api.get_ticker(instId=self.symbol)
|
||||||
|
last_price = float(ticker["data"][0]["last"]) # 最新价格
|
||||||
|
|
||||||
|
# 买入数量是USDT,将BTC转换为USDT
|
||||||
|
usdt_amount = float(last_price * size)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = self.trade_api.place_order(
|
||||||
|
instId=self.symbol,
|
||||||
|
tdMode="cash",
|
||||||
|
side=side,
|
||||||
|
ordType="market",
|
||||||
|
sz=str(usdt_amount)
|
||||||
|
)
|
||||||
|
print("下单结果:", result)
|
||||||
|
except Exception as e:
|
||||||
|
print("错误:", str(e))
|
||||||
|
|
||||||
|
def get_minimun_order_size(self):
|
||||||
|
"""获取最小订单数量"""
|
||||||
|
try:
|
||||||
|
result = self.public_api.get_instruments(instType="SPOT", instId=self.symbol)
|
||||||
|
if result["code"] == "0":
|
||||||
|
instrument = result["data"][0]
|
||||||
|
min_sz = float(instrument["minSz"]) # 最小交易量(BTC)
|
||||||
|
lot_sz = float(instrument["lotSz"]) # 交易量精度
|
||||||
|
print(f"最小交易量 (minSz): {min_sz} BTC")
|
||||||
|
print(f"交易量精度 (lotSz): {lot_sz} BTC")
|
||||||
|
else:
|
||||||
|
print(f"错误: {result['msg']}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"下单异常: {e}")
|
print(f"异常: {str(e)}")
|
||||||
return None
|
|
||||||
|
|
||||||
def simple_moving_average_strategy(self):
|
def simple_moving_average_strategy(self):
|
||||||
"""简单移动平均线策略"""
|
"""简单移动平均线策略"""
|
||||||
|
|
@ -306,9 +347,12 @@ def main():
|
||||||
print("4. 执行RSI策略")
|
print("4. 执行RSI策略")
|
||||||
print("5. 执行网格交易策略")
|
print("5. 执行网格交易策略")
|
||||||
print("6. 运行策略循环")
|
print("6. 运行策略循环")
|
||||||
|
print("7. 买入测试")
|
||||||
|
print("8. 卖出测试")
|
||||||
|
print("9. 获取最小交易量")
|
||||||
print("0. 退出")
|
print("0. 退出")
|
||||||
|
|
||||||
choice = input("请输入选择 (0-6): ").strip()
|
choice = input("请输入选择 (0-9): ").strip()
|
||||||
|
|
||||||
if choice == '0':
|
if choice == '0':
|
||||||
print("退出程序")
|
print("退出程序")
|
||||||
|
|
@ -327,6 +371,28 @@ def main():
|
||||||
strategy = input("选择策略 (sma/rsi/grid): ").strip()
|
strategy = input("选择策略 (sma/rsi/grid): ").strip()
|
||||||
interval = int(input("设置间隔秒数 (默认60): ") or "60")
|
interval = int(input("设置间隔秒数 (默认60): ") or "60")
|
||||||
trader.run_strategy_loop(strategy, interval)
|
trader.run_strategy_loop(strategy, interval)
|
||||||
|
elif choice == '7':
|
||||||
|
position_size = 0.01
|
||||||
|
input_size = input("请输入买入数量: ")
|
||||||
|
if input_size:
|
||||||
|
try:
|
||||||
|
position_size = float(input_size)
|
||||||
|
print(f"买入{position_size}BTC")
|
||||||
|
trader.place_market_order('buy', position_size)
|
||||||
|
except ValueError:
|
||||||
|
print(f"输入无效,默认买入{position_size}BTC")
|
||||||
|
elif choice == '8':
|
||||||
|
position_size = 0.01
|
||||||
|
input_size = input("请输入卖出数量: ")
|
||||||
|
if input_size:
|
||||||
|
try:
|
||||||
|
position_size = float(input_size)
|
||||||
|
print(f"卖出{position_size}BTC")
|
||||||
|
trader.place_market_order('sell', position_size)
|
||||||
|
except ValueError:
|
||||||
|
print(f"输入无效,默认卖出{position_size}BTC")
|
||||||
|
elif choice == '9':
|
||||||
|
trader.get_minimun_order_size()
|
||||||
else:
|
else:
|
||||||
print("无效选择,请重新输入")
|
print("无效选择,请重新输入")
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue