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:
@@ -1,12 +1,13 @@
|
||||
"""
|
||||
QuantDinger Python API - Flask application factory.
|
||||
DinQuant Python API - Flask application factory.
|
||||
"""
|
||||
from flask import Flask
|
||||
from flask_cors import CORS
|
||||
import logging
|
||||
|
||||
import traceback
|
||||
|
||||
from app.utils.logger import setup_logger, get_logger
|
||||
from flask import Flask
|
||||
from flask_cors import CORS
|
||||
|
||||
from app.utils.logger import get_logger, setup_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -20,6 +21,7 @@ def get_trading_executor():
|
||||
global _trading_executor
|
||||
if _trading_executor is None:
|
||||
from app.services.trading_executor import TradingExecutor
|
||||
|
||||
_trading_executor = TradingExecutor()
|
||||
return _trading_executor
|
||||
|
||||
@@ -29,6 +31,7 @@ def get_pending_order_worker():
|
||||
global _pending_order_worker
|
||||
if _pending_order_worker is None:
|
||||
from app.services.pending_order_worker import PendingOrderWorker
|
||||
|
||||
_pending_order_worker = PendingOrderWorker()
|
||||
return _pending_order_worker
|
||||
|
||||
@@ -37,6 +40,7 @@ def start_polymarket_worker():
|
||||
"""Start the Polymarket background task."""
|
||||
try:
|
||||
from app.services.polymarket_worker import get_polymarket_worker
|
||||
|
||||
get_polymarket_worker().start()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Polymarket worker: {e}")
|
||||
@@ -44,23 +48,25 @@ def start_polymarket_worker():
|
||||
|
||||
def start_portfolio_monitor():
|
||||
"""Start the portfolio monitor service if enabled.
|
||||
|
||||
|
||||
To enable it, set ENABLE_PORTFOLIO_MONITOR=true.
|
||||
"""
|
||||
import os
|
||||
|
||||
enabled = os.getenv("ENABLE_PORTFOLIO_MONITOR", "true").lower() == "true"
|
||||
if not enabled:
|
||||
logger.info("Portfolio monitor is disabled. Set ENABLE_PORTFOLIO_MONITOR=true to enable.")
|
||||
return
|
||||
|
||||
|
||||
# Avoid running twice with Flask reloader
|
||||
debug = os.getenv("PYTHON_API_DEBUG", "false").lower() == "true"
|
||||
if debug:
|
||||
if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
|
||||
return
|
||||
|
||||
|
||||
try:
|
||||
from app.services.portfolio_monitor import start_monitor_service
|
||||
|
||||
start_monitor_service()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start portfolio monitor: {e}")
|
||||
@@ -72,9 +78,10 @@ def start_pending_order_worker():
|
||||
To enable it, set ENABLE_PENDING_ORDER_WORKER=true.
|
||||
"""
|
||||
import os
|
||||
|
||||
# Local deployment: default to enabled so queued orders can be dispatched automatically.
|
||||
# To disable it, set ENABLE_PENDING_ORDER_WORKER=false explicitly.
|
||||
if os.getenv('ENABLE_PENDING_ORDER_WORKER', 'true').lower() != 'true':
|
||||
if os.getenv("ENABLE_PENDING_ORDER_WORKER", "true").lower() != "true":
|
||||
logger.info("Pending order worker is disabled (paper mode). Set ENABLE_PENDING_ORDER_WORKER=true to enable.")
|
||||
return
|
||||
try:
|
||||
@@ -91,6 +98,7 @@ def start_usdt_order_worker():
|
||||
Only starts if USDT_PAY_ENABLED=true.
|
||||
"""
|
||||
import os
|
||||
|
||||
if str(os.getenv("USDT_PAY_ENABLED", "False")).lower() not in ("1", "true", "yes"):
|
||||
logger.info("USDT order worker not started (USDT_PAY_ENABLED is not true).")
|
||||
return
|
||||
@@ -103,6 +111,7 @@ def start_usdt_order_worker():
|
||||
|
||||
try:
|
||||
from app.services.usdt_payment_service import get_usdt_order_worker
|
||||
|
||||
get_usdt_order_worker().start()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start USDT order worker: {e}")
|
||||
@@ -114,37 +123,38 @@ def restore_running_strategies():
|
||||
Local deployment: only restores IndicatorStrategy.
|
||||
"""
|
||||
import os
|
||||
|
||||
# You can disable auto-restore to avoid starting many threads on low-resource hosts.
|
||||
if os.getenv('DISABLE_RESTORE_RUNNING_STRATEGIES', 'false').lower() == 'true':
|
||||
if os.getenv("DISABLE_RESTORE_RUNNING_STRATEGIES", "false").lower() == "true":
|
||||
logger.info("Startup strategy restore is disabled via DISABLE_RESTORE_RUNNING_STRATEGIES")
|
||||
return
|
||||
try:
|
||||
from app.services.strategy import StrategyService
|
||||
|
||||
|
||||
strategy_service = StrategyService()
|
||||
trading_executor = get_trading_executor()
|
||||
|
||||
|
||||
running_strategies = strategy_service.get_running_strategies_with_type()
|
||||
|
||||
|
||||
if not running_strategies:
|
||||
logger.info("No running strategies to restore.")
|
||||
return
|
||||
|
||||
|
||||
logger.info(f"Restoring {len(running_strategies)} running strategies...")
|
||||
|
||||
|
||||
restored_count = 0
|
||||
for strategy_info in running_strategies:
|
||||
strategy_id = strategy_info['id']
|
||||
strategy_type = strategy_info.get('strategy_type', '')
|
||||
|
||||
strategy_id = strategy_info["id"]
|
||||
strategy_type = strategy_info.get("strategy_type", "")
|
||||
|
||||
try:
|
||||
if strategy_type and strategy_type != 'IndicatorStrategy':
|
||||
if strategy_type and strategy_type != "IndicatorStrategy":
|
||||
logger.info(f"Skip restore unsupported strategy type: id={strategy_id}, type={strategy_type}")
|
||||
continue
|
||||
|
||||
success = trading_executor.start_strategy(strategy_id)
|
||||
strategy_type_name = 'IndicatorStrategy'
|
||||
|
||||
strategy_type_name = "IndicatorStrategy"
|
||||
|
||||
if success:
|
||||
restored_count += 1
|
||||
logger.info(f"[OK] {strategy_type_name} {strategy_id} restored")
|
||||
@@ -152,55 +162,58 @@ def restore_running_strategies():
|
||||
logger.warning(f"[FAIL] {strategy_type_name} {strategy_id} restore failed (state may be stale)")
|
||||
# If recovery fails, update the database status to stopped to prevent the policy from being in a "zombie" state.
|
||||
try:
|
||||
strategy_service.update_strategy_status(strategy_id, 'stopped')
|
||||
strategy_service.update_strategy_status(strategy_id, "stopped")
|
||||
logger.info(f"[FIX] Updated strategy {strategy_id} status to 'stopped' after restore failure")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update strategy {strategy_id} status after restore failure: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error restoring strategy {strategy_id}: {str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
logger.info(f"Strategy restore completed: {restored_count}/{len(running_strategies)} restored")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to restore running strategies: {str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
# Do not raise; avoid breaking app startup.
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
def create_app(config_name="default"):
|
||||
"""
|
||||
Flask application factory.
|
||||
|
||||
|
||||
Args:
|
||||
config_name: config name
|
||||
|
||||
|
||||
Returns:
|
||||
Flask app
|
||||
"""
|
||||
app = Flask(__name__)
|
||||
|
||||
app.config['JSON_AS_ASCII'] = False
|
||||
|
||||
|
||||
app.config["JSON_AS_ASCII"] = False
|
||||
|
||||
CORS(app)
|
||||
|
||||
|
||||
setup_logger()
|
||||
|
||||
|
||||
# Initialize database and ensure admin user exists
|
||||
try:
|
||||
from app.utils.db import init_database, get_db_type
|
||||
from app.utils.db import get_db_type, init_database
|
||||
|
||||
logger.info(f"Database type: {get_db_type()}")
|
||||
init_database()
|
||||
|
||||
|
||||
# Ensure admin user exists (multi-user mode)
|
||||
from app.services.user_service import get_user_service
|
||||
|
||||
get_user_service().ensure_admin_exists()
|
||||
except Exception as e:
|
||||
logger.warning(f"Database initialization note: {e}")
|
||||
|
||||
from app.routes import register_routes
|
||||
|
||||
register_routes(app)
|
||||
|
||||
|
||||
# Startup hooks.
|
||||
with app.app_context():
|
||||
start_pending_order_worker()
|
||||
@@ -210,15 +223,17 @@ def create_app(config_name='default'):
|
||||
# Offline calibration to make AI thresholds self-tuning.
|
||||
try:
|
||||
from app.services.ai_calibration import start_ai_calibration_worker
|
||||
|
||||
start_ai_calibration_worker()
|
||||
except Exception:
|
||||
pass
|
||||
# Reflection worker: validate past decisions, run calibration periodically.
|
||||
try:
|
||||
from app.services.reflection import start_reflection_worker
|
||||
|
||||
start_reflection_worker()
|
||||
except Exception:
|
||||
pass
|
||||
restore_running_strategies()
|
||||
|
||||
|
||||
return app
|
||||
|
||||
Reference in New Issue
Block a user