diff --git a/trading_system/binance_client.py b/trading_system/binance_client.py index 50c261d..e61cf81 100644 --- a/trading_system/binance_client.py +++ b/trading_system/binance_client.py @@ -71,6 +71,35 @@ class BinanceClient: api_key_display = f"{self.api_key[:4]}...{self.api_key[-4:]}" if self.api_key and len(self.api_key) > 8 else self.api_key api_secret_display = f"{self.api_secret[:4]}...{self.api_secret[-4:]}" if self.api_secret and len(self.api_secret) > 8 else self.api_secret logger.info(f"初始化币安客户端: {api_key_display}, {api_secret_display}, {self.testnet}") + + def _refresh_api_credentials(self): + """刷新API密钥(从配置管理器重新读取,确保使用最新值)""" + # 优先从配置管理器读取(会从Redis获取最新值) + if config._config_manager: + try: + # 强制从Redis重新加载配置 + config._config_manager.reload_from_redis() + new_api_key = config._config_manager.get('BINANCE_API_KEY') + new_api_secret = config._config_manager.get('BINANCE_API_SECRET') + + # 如果获取到新值且与当前值不同,更新 + if new_api_key and new_api_key != self.api_key: + old_key_display = f"{self.api_key[:4]}...{self.api_key[-4:]}" if self.api_key and len(self.api_key) > 8 else self.api_key + new_key_display = f"{new_api_key[:4]}...{new_api_key[-4:]}" if new_api_key and len(new_api_key) > 8 else new_api_key + logger.info(f"检测到API密钥已更新: {old_key_display} -> {new_key_display}") + self.api_key = new_api_key + # 如果客户端已连接,需要重新连接以使用新密钥 + if self.client: + logger.warning("API密钥已更新,但客户端已连接,需要重新连接才能使用新密钥") + + if new_api_secret and new_api_secret != self.api_secret: + logger.info("检测到API密钥Secret已更新") + self.api_secret = new_api_secret + # 如果客户端已连接,需要重新连接以使用新密钥 + if self.client: + logger.warning("API密钥Secret已更新,但客户端已连接,需要重新连接才能使用新密钥") + except Exception as e: + logger.debug(f"从配置管理器刷新API密钥失败: {e},使用现有值") # 初始化 Redis 缓存 @@ -91,6 +120,9 @@ class BinanceClient: timeout: 连接超时时间(秒),默认从config读取 retries: 重试次数,默认从config读取 """ + # 连接前刷新API密钥(确保使用最新值,支持热更新) + self._refresh_api_credentials() + timeout = timeout or config.CONNECTION_TIMEOUT retries = retries or config.CONNECTION_RETRIES @@ -102,7 +134,7 @@ class BinanceClient: f"测试网: {self.testnet}, 超时: {timeout}秒)..." ) - # 创建客户端 + # 创建客户端(使用最新的API密钥) self.client = await AsyncClient.create( api_key=self.api_key, api_secret=self.api_secret,