Files
aura-trade/backend/app/broker/account_vault.py
T

153 lines
5.3 KiB
Python

import os
import json
import logging
from typing import List, Dict, Optional, Any
from pydantic import BaseModel
logger = logging.getLogger("AuraTrade.AccountVault")
VAULT_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "data")
VAULT_FILE = os.path.join(VAULT_DIR, "accounts_vault.json")
class AccountItem(BaseModel):
id: str
name: str
account_id: int
server: str
password: str
is_active: bool = False
role: str = "MASTER" # MASTER or FOLLOWER
mirror_enabled: bool = True
created_at: Optional[str] = None
class AccountVaultService:
def __init__(self):
os.makedirs(VAULT_DIR, exist_ok=True)
if not os.path.exists(VAULT_FILE):
# Seed with default initial account
initial_accounts = [
{
"id": "acc-425437997",
"name": "Exness Real Gold Scalper",
"account_id": 425437997,
"server": "Exness-MT5Real15",
"password": "",
"is_active": True,
"created_at": "2026-10-22"
}
]
self._save(initial_accounts)
def _load(self) -> List[Dict[str, Any]]:
try:
with open(VAULT_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Error loading accounts vault: {e}")
return []
def _save(self, accounts: List[Dict[str, Any]]):
try:
with open(VAULT_FILE, "w", encoding="utf-8") as f:
json.dump(accounts, f, indent=2)
except Exception as e:
logger.error(f"Error saving accounts vault: {e}")
def list_accounts(self) -> List[Dict[str, Any]]:
"""Returns safe accounts list with masked passwords."""
accounts = self._load()
safe_list = []
for a in accounts:
item = dict(a)
item["role"] = a.get("role", "MASTER" if a.get("account_id") == 425437997 else "FOLLOWER")
item["mirror_enabled"] = a.get("mirror_enabled", True)
item["has_password"] = bool(a.get("password"))
item["password"] = "••••••••" if a.get("password") else ""
safe_list.append(item)
return safe_list
def get_active_account(self) -> Optional[Dict[str, Any]]:
accounts = self._load()
for a in accounts:
if a.get("is_active"):
return a
if accounts:
# Default to first if none marked active
accounts[0]["is_active"] = True
self._save(accounts)
return accounts[0]
return None
def get_mirror_accounts(self) -> List[Dict[str, Any]]:
"""Returns follower accounts configured for automated copy-trading."""
accounts = self._load()
active = self.get_active_account()
active_id = active.get("account_id") if active else None
followers = []
for a in accounts:
if a.get("account_id") != active_id and a.get("role") == "FOLLOWER" and a.get("mirror_enabled", True):
followers.append(a)
return followers
def add_account(self, name: str, account_id: int, server: str, password: str, role: str = "FOLLOWER", mirror_enabled: bool = True) -> Dict[str, Any]:
accounts = self._load()
# Check if already exists
for a in accounts:
if a.get("account_id") == account_id:
# Update existing
a["name"] = name
a["server"] = server
a["role"] = role
a["mirror_enabled"] = mirror_enabled
if password:
a["password"] = password
self._save(accounts)
return a
# Add new
new_acc = {
"id": f"acc-{account_id}",
"name": name or f"MT5 #{account_id}",
"account_id": account_id,
"server": server,
"password": password,
"role": role,
"mirror_enabled": mirror_enabled,
"is_active": len(accounts) == 0,
"created_at": "2026-10-23"
}
accounts.append(new_acc)
self._save(accounts)
return new_acc
def set_active(self, account_id: int) -> Optional[Dict[str, Any]]:
accounts = self._load()
target = None
for a in accounts:
if a.get("account_id") == account_id:
a["is_active"] = True
target = a
else:
a["is_active"] = False
if target:
self._save(accounts)
return target
return None
def delete_account(self, account_id: int) -> bool:
accounts = self._load()
if len(accounts) <= 1:
return False # Cannot delete the only account
new_list = [a for a in accounts if a.get("account_id") != account_id]
if len(new_list) < len(accounts):
# If deleted account was active, activate first remaining
if not any(a.get("is_active") for a in new_list):
new_list[0]["is_active"] = True
self._save(new_list)
return True
return False
# Global singleton
account_vault = AccountVaultService()