diff --git a/__pycache__/config.cpython-312.pyc b/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000..ab71eea Binary files /dev/null and b/__pycache__/config.cpython-312.pyc differ diff --git a/config.py b/config.py index e8f776a..c84f45e 100644 --- a/config.py +++ b/config.py @@ -1,10 +1,13 @@ # OKX API 配置 # 请将以下信息替换为你的实际API密钥 - # API密钥配置 -API_KEY = "your_api_key_here" -SECRET_KEY = "your_secret_key_here" -PASSPHRASE = "your_passphrase_here" +# API_KEY = "7286d434-225b-401f-b3af-fd595e15d23f" +# SECRET_KEY = "80B95C5757F9208F70282A85C9DDBC86" +# PASSPHRASE = "Bengbu_2001" +# 模拟盘API密钥配置 +API_KEY = "f309e789-3497-4ed3-896f-d18bdc4d9817" +SECRET_KEY = "9152809391B110E2E647FDE12A37E96D" +PASSPHRASE = "Bengbu@2001" # 交易配置 TRADING_CONFIG = { @@ -21,12 +24,12 @@ TRADING_CONFIG = { # 网格交易参数 "grid_levels": 5, # 网格数量 - "grid_range": 0.02, # 网格范围(2%) + "grid_range": 0.005, # 网格范围(0.5%) # 风险控制 "max_position": 0.01, # 最大持仓量(BTC) - "stop_loss_pct": 0.05, # 止损百分比(5%) - "take_profit_pct": 0.10, # 止盈百分比(10%) + "stop_loss_pct": 0.005, # 止损百分比(0.5%) + "take_profit_pct": 0.01, # 止盈百分比(1%) } # 时间间隔配置 diff --git a/play.py b/play.py index 515f9e1..7298c52 100644 --- a/play.py +++ b/play.py @@ -1,7 +1,7 @@ -import okx.api.account as Account -import okx.api.trade as Trade -import okx.api.market as Market -import okx.api.public as Public +import okx.Account as Account +import okx.Trade as Trade +import okx.MarketData as Market +import okx.PublicData as Public import pandas as pd import numpy as np import time @@ -24,23 +24,23 @@ class BitcoinQuantTrader: self.passphrase = passphrase # 初始化API客户端 - flag = "0" if sandbox else "1" # 0:沙盒环境 1:实盘环境 + flag = "1" if sandbox else "0" # 0:实盘环境 1:沙盒环境 - self.account_api = Account.Account( - api_key, secret_key, passphrase, - flag=flag, debug=False + self.account_api = Account.AccountAPI( + api_key=api_key, api_secret_key=secret_key, passphrase=passphrase, + flag=flag ) - self.trade_api = Trade.Trade( - api_key, secret_key, passphrase, - flag=flag, debug=False + self.trade_api = Trade.TradeAPI( + api_key=api_key, api_secret_key=secret_key, passphrase=passphrase, + flag=flag ) - self.market_api = Market.Market( - api_key, secret_key, passphrase, - flag=flag, debug=False + self.market_api = Market.MarketAPI( + api_key=api_key, api_secret_key=secret_key, passphrase=passphrase, + flag=flag ) - self.public_api = Public.Public( - api_key, secret_key, passphrase, - flag=flag, debug=False + self.public_api = Public.PublicAPI( + api_key=api_key, api_secret_key=secret_key, passphrase=passphrase, + flag=flag ) self.symbol = "BTC-USDT" @@ -53,12 +53,14 @@ class BitcoinQuantTrader: if result['code'] == '0': balances = result['data'] for balance in balances: - if balance['ccy'] == 'USDT': - print(f"USDT余额: {balance['bal']}") - return float(balance['bal']) - elif balance['ccy'] == 'BTC': - print(f"BTC余额: {balance['bal']}") - return float(balance['bal']) + details = balance['details'] + for detail in details: + if detail['ccy'] == 'USDT': + print(f"USDT余额: {detail['availBal']}") + return float(detail['availBal']) + elif detail['ccy'] == 'BTC': + print(f"BTC余额: {detail['availBal']}") + # return float(detail['availBal']) else: print(f"获取余额失败: {result}") return 0 @@ -92,7 +94,8 @@ class BitcoinQuantTrader: if result['code'] == '0': # 转换为DataFrame 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']: @@ -121,23 +124,61 @@ class BitcoinQuantTrader: def place_market_order(self, side, size): """下市价单""" - try: - result = self.trade_api.place_order( - instId=self.symbol, - tdMode='cash', - side=side, - ordType='market', - sz=str(size) - ) - if result['code'] == '0': - print(f"下单成功: {side} {size} BTC") - return result['data'][0]['ordId'] - else: - print(f"下单失败: {result}") + if side == 'sell': + try: + result = self.trade_api.place_order( + instId=self.symbol, + tdMode='cash', + side=side, + ordType='market', + sz=str(size) + ) + if result['code'] == '0': + print(f"下单成功: {side} {size} BTC") + return result['data'][0]['ordId'] + else: + print(f"下单失败: {result}") + return None + except Exception as e: + print(f"下单异常: {e}") 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: - print(f"下单异常: {e}") - return None + print(f"异常: {str(e)}") def simple_moving_average_strategy(self): """简单移动平均线策略""" @@ -306,9 +347,12 @@ def main(): print("4. 执行RSI策略") print("5. 执行网格交易策略") print("6. 运行策略循环") + print("7. 买入测试") + print("8. 卖出测试") + print("9. 获取最小交易量") print("0. 退出") - choice = input("请输入选择 (0-6): ").strip() + choice = input("请输入选择 (0-9): ").strip() if choice == '0': print("退出程序") @@ -327,6 +371,28 @@ def main(): strategy = input("选择策略 (sma/rsi/grid): ").strip() interval = int(input("设置间隔秒数 (默认60): ") or "60") 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: print("无效选择,请重新输入")