Refactor code for improved readability and consistency

- Cleaned up whitespace and formatting in various files including http.py, language.py, logger.py, safe_exec.py, and SQL migration scripts.
- Consolidated import statements and removed unnecessary blank lines.
- Updated logging configuration for better clarity.
- Enhanced the safe execution code with improved error handling and logging.
- Removed commented-out code and unnecessary variables in backfill_zero_trades.py and other scripts.
- Added a pyproject.toml for Ruff and Vulture configuration.
- Introduced requirements-dev.txt for development dependencies.
- Removed commented-out stock entries in init.sql for cleaner migration scripts.
This commit is contained in:
dienakdz
2026-04-09 14:30:51 +07:00
parent 103055b3df
commit 87f2845483
157 changed files with 19026 additions and 17773 deletions
+27 -34
View File
@@ -2,7 +2,8 @@
data source factory
Return the corresponding data source according to the market type
"""
from typing import Dict, List, Any, Optional
from typing import Any, Dict, List, Optional
from app.data_sources.base import BaseDataSource
from app.utils.logger import get_logger
@@ -12,17 +13,17 @@ logger = get_logger(__name__)
class DataSourceFactory:
"""data source factory"""
_sources: Dict[str, BaseDataSource] = {}
@classmethod
def get_source(cls, market: str) -> BaseDataSource:
"""
Get the data source for the specified market
Args:
market: market type (Crypto, USStock, Forex, Futures)
Returns:
Data source instance
"""
@@ -45,74 +46,67 @@ class DataSourceFactory:
return cls.get_source("Futures")
# Default to Crypto for safety (most callers want a ticker for crypto pairs).
return cls.get_source("Crypto")
@classmethod
def _create_source(cls, market: str) -> BaseDataSource:
"""Create data source instance"""
if market == 'Crypto':
if market == "Crypto":
from app.data_sources.crypto import CryptoDataSource
return CryptoDataSource()
elif market == 'CNStock':
from app.data_sources.cn_stock import CNStockDataSource
return CNStockDataSource()
elif market == 'HKStock':
from app.data_sources.hk_stock import HKStockDataSource
return HKStockDataSource()
elif market == 'USStock':
elif market == "USStock":
from app.data_sources.us_stock import USStockDataSource
return USStockDataSource()
elif market == 'Forex':
elif market == "Forex":
from app.data_sources.forex import ForexDataSource
return ForexDataSource()
elif market == 'Futures':
elif market == "Futures":
from app.data_sources.futures import FuturesDataSource
return FuturesDataSource()
else:
raise ValueError(f"Unsupported market type: {market}")
@classmethod
def get_kline(
cls,
market: str,
symbol: str,
timeframe: str,
limit: int,
before_time: Optional[int] = None
cls, market: str, symbol: str, timeframe: str, limit: int, before_time: Optional[int] = None
) -> List[Dict[str, Any]]:
"""
A convenient way to obtain K-line data
Args:
market: market type
symbol: trading pair/stock code
timeframe: time period
limit: number of data items
before_time: Get data before this time
Returns:
K-line data list
"""
try:
source = cls.get_source(market)
klines = source.get_kline(symbol, timeframe, limit, before_time)
# Make sure the data is sorted by time
klines.sort(key=lambda x: x['time'])
klines.sort(key=lambda x: x["time"])
return klines
except Exception as e:
logger.error(f"Failed to fetch K-lines {market}:{symbol} - {str(e)}")
return []
@classmethod
def get_ticker(cls, market: str, symbol: str) -> Dict[str, Any]:
"""
The convenient way to get realtime quotes
Args:
market: market type
symbol: trading pair/stock code
Returns:
Real-time quotation data: {
'last': latest price,
@@ -126,8 +120,7 @@ class DataSourceFactory:
return source.get_ticker(symbol)
except NotImplementedError:
logger.warning(f"get_ticker not implemented for market: {market}")
return {'last': 0, 'symbol': symbol}
return {"last": 0, "symbol": symbol}
except Exception as e:
logger.error(f"Failed to fetch ticker {market}:{symbol} - {str(e)}")
return {'last': 0, 'symbol': symbol}
return {"last": 0, "symbol": symbol}