Gr8/nytimes.py

103 lines
3.2 KiB
Python
Raw Permalink Normal View History

2025-09-10 15:02:31 +03:00
import MetaTrader5 as mt5
import os
import json
import logging
# ---------------------------------------
# Logging Setup
# ---------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
log = logging.getLogger()
# ---------------------------------------
# Load config.json
# ---------------------------------------
def load_config(filepath="config.json"):
log.info(f"Loading configuration file: {filepath}")
if not os.path.exists(filepath):
log.error("Configuration file missing.")
raise FileNotFoundError(f"Config not found: {filepath}")
with open(filepath, "r") as f:
config = json.load(f)
# Log loaded credentials (hide password for security)
log.info(f"Config loaded: Username={config['username']} | Server={config['server']} | Path={config['mt5Pathway']}")
return config
# ---------------------------------------
# Initialize MetaTrader 5
# ---------------------------------------
def initialize_mt5(config):
log.info("Starting MetaTrader 5 initialization...")
# Validate terminal path
if not os.path.exists(config["mt5Pathway"]):
log.error(f"MT5 terminal not found: {config['mt5Pathway']}")
raise FileNotFoundError(f"Invalid MT5 path: {config['mt5Pathway']}")
# Try to initialize
log.info("Attempting to initialize MT5...")
connected = mt5.initialize(
path=config["mt5Pathway"],
login=int(config["username"]),
password=config["password"],
server=config["server"]
)
if not connected:
err = mt5.last_error()
log.error(f"MT5 initialization failed → Code {err[0]}: {err[1]}")
raise RuntimeError(f"MT5 initialize failed: {err}")
log.info("MT5 initialized successfully and connection established.")
# ---------------------------------------
# Shutdown MetaTrader 5
# ---------------------------------------
def shutdown_mt5():
log.info("Shutting down MetaTrader 5...")
mt5.shutdown()
log.info("MT5 shutdown complete.")
# ---------------------------------------
# Main Function
# ---------------------------------------
def main():
log.info("===== Starting NY Times Levels Script =====")
try:
# Load configuration
config = load_config()
# Initialize MT5
initialize_mt5(config)
# Test basic account info
account_info = mt5.account_info()
if account_info:
log.info(f"Connected to account {account_info.login} | Balance: {account_info.balance} | Equity: {account_info.equity}")
else:
log.warning("Failed to fetch account info. Connection might be unstable.")
# Example: Print all symbols to check connection
symbols = mt5.symbols_get()
log.info(f"Total symbols loaded: {len(symbols)}")
if len(symbols) > 0:
log.info(f"First symbol: {symbols[0].name}")
except Exception as e:
log.error(f"Fatal error in main(): {e}")
finally:
shutdown_mt5()
log.info("===== Script Finished =====")
# ---------------------------------------
# Run
# ---------------------------------------
if __name__ == "__main__":
main()