Browse Source

Refactor trading_commands and market commands for token normalization

- Replaced the custom `_normalize_token_case` function with a shared `normalize_token_case` utility for consistent token case handling across trading and market commands.
- Updated the constructor of `TradingCommands` to specify types for `trading_engine` and `notification_manager`.
- Improved code clarity and maintainability by consolidating token normalization logic.
Carles Sentis 2 days ago
parent
commit
e54de9dd05
3 changed files with 15 additions and 22 deletions
  1. 2 1
      src/commands/info/market.py
  2. 12 20
      src/commands/trading_commands.py
  3. 1 1
      trading_bot.py

+ 2 - 1
src/commands/info/market.py

@@ -3,6 +3,7 @@ from typing import Dict, Any, List, Optional
 from telegram import Update
 from telegram import Update
 from telegram.ext import ContextTypes
 from telegram.ext import ContextTypes
 from .base import InfoCommandsBase
 from .base import InfoCommandsBase
+from .utils import normalize_token_case
 from src.config.config import Config
 from src.config.config import Config
 from src.utils.token_display_formatter import get_formatter
 from src.utils.token_display_formatter import get_formatter
 
 
@@ -30,7 +31,7 @@ class MarketCommands(InfoCommandsBase):
                 return
                 return
 
 
             # Get token from command arguments or use default
             # Get token from command arguments or use default
-            token = context.args[0].upper() if context.args else Config.DEFAULT_TRADING_TOKEN
+            token = normalize_token_case(context.args[0]) if context.args else Config.DEFAULT_TRADING_TOKEN
             
             
             # Construct the full market symbol
             # Construct the full market symbol
             symbol = f"{token}/USDC:USDC"
             symbol = f"{token}/USDC:USDC"

+ 12 - 20
src/commands/trading_commands.py

@@ -4,30 +4,22 @@ Trading Commands - Handles all trading-related Telegram commands.
 """
 """
 
 
 import logging
 import logging
-from typing import Optional
+from typing import Optional, Dict
 from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
 from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
 from telegram.ext import ContextTypes
 from telegram.ext import ContextTypes
 
 
 from src.config.config import Config
 from src.config.config import Config
-from src.utils.token_display_formatter import get_formatter, normalize_token_case
+from src.trading.trading_engine import TradingEngine
+from src.notifications.notification_manager import NotificationManager
+from src.commands.info.utils import normalize_token_case
+from src.utils.token_display_formatter import get_formatter
 
 
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
 
 
-def _normalize_token_case(token: str) -> str:
-    """
-    Normalize token case: if any characters are already uppercase, keep as-is.
-    Otherwise, convert to uppercase. This handles mixed-case tokens like kPEPE, kBONK.
-    """
-    # Check if any character is already uppercase
-    if any(c.isupper() for c in token):
-        return token  # Keep original case for mixed-case tokens
-    else:
-        return token.upper()  # Convert to uppercase for all-lowercase input
-
 class TradingCommands:
 class TradingCommands:
     """Handles all trading-related Telegram commands."""
     """Handles all trading-related Telegram commands."""
     
     
-    def __init__(self, trading_engine, notification_manager, management_commands_handler=None, info_commands_handler=None):
+    def __init__(self, trading_engine: TradingEngine, notification_manager: NotificationManager, management_commands_handler=None, info_commands_handler=None):
         """Initialize trading commands with required dependencies."""
         """Initialize trading commands with required dependencies."""
         self.trading_engine = trading_engine
         self.trading_engine = trading_engine
         self.notification_manager = notification_manager
         self.notification_manager = notification_manager
@@ -57,7 +49,7 @@ class TradingCommands:
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             usdc_amount = float(context.args[1])
             usdc_amount = float(context.args[1])
             
             
             # Parse arguments for price and stop loss
             # Parse arguments for price and stop loss
@@ -182,7 +174,7 @@ This will {"place a limit buy order" if limit_price else "execute a market buy o
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             usdc_amount = float(context.args[1])
             usdc_amount = float(context.args[1])
             
             
             # Parse arguments (similar to long_command)
             # Parse arguments (similar to long_command)
@@ -301,7 +293,7 @@ This will {"place a limit sell order" if limit_price else "execute a market sell
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             
             
             # Find the position
             # Find the position
             position = await self.trading_engine.find_position(token)
             position = await self.trading_engine.find_position(token)
@@ -378,7 +370,7 @@ This will {"place a limit sell order" if limit_price else "execute a market sell
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             stop_price = float(context.args[1])
             stop_price = float(context.args[1])
             
             
             # Find the position
             # Find the position
@@ -491,7 +483,7 @@ This will place a limit {exit_side} order at {await formatter.format_price_with_
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             tp_price = float(context.args[1])
             tp_price = float(context.args[1])
             
             
             # Find the position
             # Find the position
@@ -595,7 +587,7 @@ This will place a limit {exit_side} order at {await formatter.format_price_with_
                 ))
                 ))
                 return
                 return
             
             
-            token = _normalize_token_case(context.args[0])
+            token = normalize_token_case(context.args[0])
             
             
             confirmation_text = f"""
             confirmation_text = f"""
 🚫 <b>Cancel All Orders Confirmation</b>
 🚫 <b>Cancel All Orders Confirmation</b>

+ 1 - 1
trading_bot.py

@@ -14,7 +14,7 @@ from datetime import datetime
 from pathlib import Path
 from pathlib import Path
 
 
 # Bot version
 # Bot version
-BOT_VERSION = "2.4.266"
+BOT_VERSION = "2.4.267"
 
 
 # Add src directory to Python path
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))
 sys.path.insert(0, str(Path(__file__).parent / "src"))