chore(log): add class name in log
This commit is contained in:
92
main.py
92
main.py
@@ -45,7 +45,6 @@ logging.basicConfig(
|
||||
logging.StreamHandler(),
|
||||
],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MexcSpotMarket:
|
||||
@@ -61,6 +60,7 @@ class MexcSpotMarket:
|
||||
def __init__(self, config):
|
||||
"""初始化市场数据查询接口"""
|
||||
self.market = mexc_spot_v3.mexc_market(config)
|
||||
self.logger = logging.getLogger(self.__class__.__module__ + '.' + self.__class__.__name__)
|
||||
|
||||
def get_exchange_info(self, symbol: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
@@ -75,18 +75,18 @@ class MexcSpotMarket:
|
||||
params = {"symbol": symbol}
|
||||
|
||||
try:
|
||||
logger.info("查询交易对信息: %s", symbol)
|
||||
self.logger.info("查询交易对信息: %s", symbol)
|
||||
exchange_info = self.market.get_exchangeInfo(params)
|
||||
|
||||
if not exchange_info or "symbols" not in exchange_info:
|
||||
logger.error("获取交易对信息失败: %s", exchange_info)
|
||||
self.logger.error("获取交易对信息失败: %s", exchange_info)
|
||||
return None
|
||||
|
||||
logger.info("获取交易对信息成功")
|
||||
self.logger.info("获取交易对信息成功")
|
||||
return exchange_info
|
||||
|
||||
except Exception as e:
|
||||
logger.error("查询交易所信息失败: %s", str(e))
|
||||
self.logger.error("查询交易所信息失败: %s", str(e))
|
||||
return None
|
||||
|
||||
def get_price(self, symbol: str) -> Optional[float]:
|
||||
@@ -106,20 +106,20 @@ class MexcSpotMarket:
|
||||
params = {"symbol": symbol}
|
||||
|
||||
try:
|
||||
logger.info("查询交易对价格: %s", symbol)
|
||||
self.logger.info("查询交易对价格: %s", symbol)
|
||||
price_data = self.market.get_price(params)
|
||||
|
||||
if not price_data or "price" not in price_data:
|
||||
logger.error("获取价格数据失败: %s", price_data)
|
||||
self.logger.error("获取价格数据失败: %s", price_data)
|
||||
return None
|
||||
|
||||
price_str = price_data["price"]
|
||||
price = float(price_str)
|
||||
logger.info("获取价格成功: %s = %f", symbol, price)
|
||||
self.logger.info("获取价格成功: %s = %f", symbol, price)
|
||||
return price
|
||||
|
||||
except Exception as e:
|
||||
logger.error("查询价格失败: %s", str(e))
|
||||
self.logger.error("查询价格失败: %s", str(e))
|
||||
return None
|
||||
|
||||
|
||||
@@ -159,6 +159,7 @@ class MexcSpotTrade:
|
||||
self.market = MexcSpotMarket(config)
|
||||
self.csv_file = f"output/{config_file_name}.csv"
|
||||
self.symbol_mapping = symbol_mapping
|
||||
self.logger = logging.getLogger(self.__class__.__module__ + '.' + self.__class__.__name__)
|
||||
|
||||
def _api_get_balance(self) -> str:
|
||||
"""
|
||||
@@ -168,16 +169,16 @@ class MexcSpotTrade:
|
||||
账户余额字典或None(如果失败)
|
||||
"""
|
||||
try:
|
||||
logger.info("查询账户余额")
|
||||
self.logger.info("查询账户余额")
|
||||
account_info = self.trader.get_account_info()
|
||||
account_info_balance = account_info.get("balances", [])
|
||||
balances = ""
|
||||
for item in account_info_balance:
|
||||
balances += f"{item['available']} {item['asset']} "
|
||||
logger.info("获取账户余额成功")
|
||||
self.logger.info("获取账户余额成功")
|
||||
return balances
|
||||
except Exception as e:
|
||||
logger.error("查询账户信息失败: %s", str(e))
|
||||
self.logger.error("查询账户信息失败: %s", str(e))
|
||||
return f"ERROR: {str(e)}"
|
||||
|
||||
def _api_get_order(self, symbol: str, order_id: str) -> Optional[Dict[str, Any]]:
|
||||
@@ -198,12 +199,12 @@ class MexcSpotTrade:
|
||||
}
|
||||
|
||||
try:
|
||||
logger.info("查询订单状态, 订单ID: %s", order_id)
|
||||
self.logger.info("查询订单状态, 订单ID: %s", order_id)
|
||||
order = self.trader.get_order(params)
|
||||
logger.info("订单状态: %s", order.get("status"))
|
||||
self.logger.info("订单状态: %s", order.get("status"))
|
||||
return order
|
||||
except Exception as e:
|
||||
logger.error("查询订单失败: %s", str(e))
|
||||
self.logger.error("查询订单失败: %s", str(e))
|
||||
return None
|
||||
|
||||
def _tool_map_symbol(self, symbol: str) -> str:
|
||||
@@ -319,10 +320,10 @@ class MexcSpotTrade:
|
||||
)
|
||||
writer.writerow(row)
|
||||
|
||||
logger.info("交易记录成功, 订单ID: %s", order_id)
|
||||
self.logger.info("交易记录成功, 订单ID: %s", order_id)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("记录交易失败: %s", str(e))
|
||||
self.logger.error("记录交易失败: %s", str(e))
|
||||
return False
|
||||
|
||||
def _tool_calculate_quantity(
|
||||
@@ -350,7 +351,7 @@ class MexcSpotTrade:
|
||||
"""
|
||||
processed_quantity = round(quantity, base_asset_precision)
|
||||
if processed_quantity * price < quote_amount_precision:
|
||||
logger.info(
|
||||
self.logger.info(
|
||||
"计算的quantity小于最低要求:%f * %f = %f < %f,进行调整",
|
||||
processed_quantity,
|
||||
price,
|
||||
@@ -360,7 +361,7 @@ class MexcSpotTrade:
|
||||
processed_quantity = round(
|
||||
quantity + 10 ** (-base_asset_precision), base_asset_precision
|
||||
)
|
||||
logger.info("调整后的quantity: %f", processed_quantity)
|
||||
self.logger.info("调整后的quantity: %f", processed_quantity)
|
||||
return processed_quantity
|
||||
|
||||
def trade(
|
||||
@@ -385,7 +386,7 @@ class MexcSpotTrade:
|
||||
|
||||
# 基本参数验证
|
||||
if side not in ["BUY", "SELL"]:
|
||||
logger.error("无效的交易方向: %s", side)
|
||||
self.logger.error("无效的交易方向: %s", side)
|
||||
return None
|
||||
|
||||
order_type = order_type.upper()
|
||||
@@ -399,7 +400,7 @@ class MexcSpotTrade:
|
||||
if order_type in ["LIMIT", "LIMIT_MAKER"] and "price" not in processed_kwargs:
|
||||
current_price = self.market.get_price(symbol)
|
||||
if current_price is None:
|
||||
logger.error("无法获取实时价格,交易取消")
|
||||
self.logger.error("无法获取实时价格,交易取消")
|
||||
return None
|
||||
clean_price = current_price
|
||||
# 防止挂单不成交
|
||||
@@ -407,7 +408,7 @@ class MexcSpotTrade:
|
||||
processed_kwargs["price"] = current_price * 1.01 # 买入加价1%
|
||||
elif side == "SELL":
|
||||
processed_kwargs["price"] = current_price * 0.99 # 卖出减价1%
|
||||
logger.info("使用调整1%%后价格作为限价: %f", processed_kwargs["price"])
|
||||
self.logger.info("使用调整1%%后价格作为限价: %f", processed_kwargs["price"])
|
||||
|
||||
# 处理LIMIT订单只有quoteOrderQty没有quantity的情况
|
||||
if (
|
||||
@@ -428,11 +429,11 @@ class MexcSpotTrade:
|
||||
processed_quantity = self._tool_calculate_quantity(
|
||||
quantity, clean_price, base_asset_precision, quote_amount_precision
|
||||
)
|
||||
logger.info("根据quoteOrderQty计算quantity: %f", processed_quantity)
|
||||
self.logger.info("根据quoteOrderQty计算quantity: %f", processed_quantity)
|
||||
processed_kwargs["quantity"] = str(processed_quantity)
|
||||
processed_kwargs.pop("quoteOrderQty")
|
||||
except (ValueError, KeyError) as e:
|
||||
logger.error("计算quantity失败: %s", str(e))
|
||||
self.logger.error("计算quantity失败: %s", str(e))
|
||||
return None
|
||||
|
||||
# 准备订单参数
|
||||
@@ -446,46 +447,46 @@ class MexcSpotTrade:
|
||||
# 验证参数
|
||||
is_valid, error_msg = self._tool_validate_order_params(order_type, base_params)
|
||||
if not is_valid:
|
||||
logger.error("订单参数验证失败: %s", error_msg)
|
||||
self.logger.error("订单参数验证失败: %s", error_msg)
|
||||
return None
|
||||
|
||||
try:
|
||||
logger.info("准备下单 %s %s 订单, 交易对: %s", side, order_type, symbol)
|
||||
logger.debug("订单参数: %s", base_params)
|
||||
self.logger.info("准备下单 %s %s 订单, 交易对: %s", side, order_type, symbol)
|
||||
self.logger.debug("订单参数: %s", base_params)
|
||||
|
||||
# 测试订单
|
||||
test_result = self.trader.post_order_test(base_params.copy())
|
||||
if test_result != {}:
|
||||
logger.error("订单测试失败,参数有误: %s", test_result)
|
||||
self.logger.error("订单测试失败,参数有误: %s", test_result)
|
||||
return None
|
||||
|
||||
logger.info("订单参数测试通过,准备正式下单")
|
||||
self.logger.info("订单参数测试通过,准备正式下单")
|
||||
|
||||
# 正式下单
|
||||
order = self.trader.post_order(base_params.copy())
|
||||
order_id = order.get("orderId")
|
||||
|
||||
if not order_id:
|
||||
logger.error("下单失败: 未获取到订单ID")
|
||||
logger.error(base_params.copy())
|
||||
logger.error(order)
|
||||
self.logger.error("下单失败: 未获取到订单ID")
|
||||
self.logger.error(base_params.copy())
|
||||
self.logger.error(order)
|
||||
return None
|
||||
|
||||
logger.info("订单创建成功, 订单ID: %s", order_id)
|
||||
self.logger.info("订单创建成功, 订单ID: %s", order_id)
|
||||
|
||||
# 查询订单详情
|
||||
logger.info("等待1秒后查询订单状态...")
|
||||
self.logger.info("等待1秒后查询订单状态...")
|
||||
time.sleep(1)
|
||||
order_detail = self._api_get_order(symbol, order_id)
|
||||
if not order_detail:
|
||||
logger.error("获取订单详情失败")
|
||||
self.logger.error("获取订单详情失败")
|
||||
return None
|
||||
|
||||
# 如果不是FILLED则重复查询最多10次
|
||||
retry_count = 0
|
||||
while order_detail.get("status") != "FILLED" and retry_count < 10:
|
||||
retry_count += 1
|
||||
logger.info(
|
||||
self.logger.info(
|
||||
"订单未完成(状态: %s),等待1秒后第%s次重试查询...",
|
||||
order_detail.get("status", "UNKNOWN"),
|
||||
retry_count,
|
||||
@@ -493,15 +494,15 @@ class MexcSpotTrade:
|
||||
time.sleep(1)
|
||||
order_detail = self._api_get_order(symbol, order_id)
|
||||
if not order_detail:
|
||||
logger.error("获取订单详情失败")
|
||||
self.logger.error("获取订单详情失败")
|
||||
return None
|
||||
|
||||
# 记录交易
|
||||
if order_detail.get("status") == "FILLED":
|
||||
if not self._tool_record_transaction(order_detail):
|
||||
logger.error("交易记录失败")
|
||||
self.logger.error("交易记录失败")
|
||||
else:
|
||||
logger.warning(
|
||||
self.logger.warning(
|
||||
"订单未完成(状态: %s),未被记录到CSV。订单ID: %s",
|
||||
order_detail.get("status", "UNKNOWN"),
|
||||
order_id,
|
||||
@@ -510,7 +511,7 @@ class MexcSpotTrade:
|
||||
return order_detail
|
||||
|
||||
except Exception as e:
|
||||
logger.error("交易执行失败: %s", str(e))
|
||||
self.logger.error("交易执行失败: %s", str(e))
|
||||
return None
|
||||
|
||||
|
||||
@@ -533,6 +534,7 @@ class TradingConfig:
|
||||
"""
|
||||
|
||||
self.config_file = config_file
|
||||
self.logger = logging.getLogger(self.__class__.__module__ + '.' + self.__class__.__name__)
|
||||
self.config_data = self._load_config()
|
||||
|
||||
def _load_config(self) -> Dict[str, Any]:
|
||||
@@ -540,16 +542,16 @@ class TradingConfig:
|
||||
try:
|
||||
with open(self.config_file, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
logger.info("成功加载配置文件: %s", self.config_file)
|
||||
self.logger.info("成功加载配置文件: %s", self.config_file)
|
||||
return config
|
||||
except FileNotFoundError:
|
||||
logger.error("配置文件不存在: %s", self.config_file)
|
||||
self.logger.error("配置文件不存在: %s", self.config_file)
|
||||
return {}
|
||||
except json.JSONDecodeError:
|
||||
logger.error("配置文件格式错误,不是有效的JSON")
|
||||
self.logger.error("配置文件格式错误,不是有效的JSON")
|
||||
return {}
|
||||
except Exception as e:
|
||||
logger.error("加载配置文件时出错: %s", str(e))
|
||||
self.logger.error("加载配置文件时出错: %s", str(e))
|
||||
return {}
|
||||
|
||||
def get_today_trades(self) -> List[Dict[str, Any]]:
|
||||
@@ -601,6 +603,8 @@ def git_commit(repo_path: str = ".") -> str:
|
||||
def main():
|
||||
"""主函数"""
|
||||
|
||||
logger = logging.getLogger(f"{__name__}.main")
|
||||
|
||||
logger.info("=" * 40)
|
||||
# 获取主程序Git仓库版本
|
||||
app_commit = git_commit(".")[:10]
|
||||
|
Reference in New Issue
Block a user