I had more ideas but decided to clean up instead, thank your for confirming.
# cleanup_trading212.py
# COMPLETE Cleanup Script for All Trading212 API Tests
# Run this once to disable, secure, and clean everything
import os
import glob
import re
import shutil
def main_cleanup():
print("š COMPLETE TRADING212 SCRIPTS CLEANUP")
print("=" * 60)
# Phase 1: Disable all scripts
disable_scripts()
# Phase 2: Security check for API keys
check_exposed_keys()
# Phase 3: Cleanup temporary files
cleanup_temp_files()
# Phase 4: Final verification
final_report()
def disable_scripts():
"""Disable all Trading212 scripts by renaming them"""
print("\nš PHASE 1: DISABLING SCRIPTS")
print("-" * 40)
trading_scripts = [
# Main API clients
"trading212_api.py", "trading212_practice.py", "trading212_working.py",
# Test and discovery scripts
"environment_check.py", "endpoint_discovery.py", "api_discovery.py",
"simple_test.py", "test_corrected_api.py", "test_new_key.py",
"live_api_micro_test.py", "trading212_permission_fix.py",
"final_api_test.py", "validate_key.py", "test_practice_connection.py",
# Alternative approaches
"trading212_automation.py", "alternative_suggestions.py",
"platform_migration.py", "funding_guide.py",
# Cleanup scripts (will self-disable)
"disable_trading_scripts.py", "quick_cleanup.py", "security_check.py"
]
disabled_count = 0
not_found = []
for script in trading_scripts:
if os.path.exists(script):
try:
new_name = script + ".disabled"
os.rename(script, new_name)
print(f"ā
Disabled: {script} ā {new_name}")
disabled_count += 1
except Exception as e:
print(f"ā Failed to disable {script}: {e}")
else:
not_found.append(script)
print(f"\nš Disabled {disabled_count} scripts")
if not_found:
print(f"ā¹ļø Not found: {len(not_found)} scripts")
def check_exposed_keys():
"""Check for any exposed API keys in Python files"""
print("\nš PHASE 2: SECURITY CHECK FOR API KEYS")
print("-" * 40)
key_patterns = [
r'API_KEY\s*=\s*["\'][^"\']{10,}["\']',
r'api_key\s*=\s*["\'][^"\']{10,}["\']',
r'LIVE_API_KEY\s*=\s*["\'][^"\']{10,}["\']',
r'NEW_API_KEY\s*=\s*["\'][^"\']{10,}["\']',
r'T212-API-KEY\s+[^\s]{20,}',
r'Bearer\s+[^\s]{20,}',
r'["\'][a-zA-Z0-9]{30,50}["\']' # Generic long strings that might be keys
]
exposed_files = []
for file in glob.glob("*.py") + glob.glob("*.py.disabled"):
try:
with open(file, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
lines = content.split('\n')
for i, line in enumerate(lines, 1):
for pattern in key_patterns:
if re.search(pattern, line, re.IGNORECASE):
# Check if it's a placeholder
if not any(placeholder in line for placeholder in ["YOUR_", "PLACEHOLDER", "EXAMPLE"]):
exposed_files.append((file, i, line.strip()))
break
except Exception as e:
print(f"ā ļø Could not read {file}: {e}")
if exposed_files:
print("šØ POTENTIAL API KEYS FOUND:")
for file, line_num, line_content in exposed_files:
print(f" š {file}: Line {line_num}")
print(f" {line_content[:80]}...")
print("\nš Please manually remove API keys from these files!")
else:
print("ā
No exposed API keys found")
def cleanup_temp_files():
"""Remove all temporary and generated files"""
print("\nš§¹ PHASE 3: CLEANING TEMPORARY FILES")
print("-" * 40)
# Files and folders to remove
cleanup_targets = [
"__pycache__",
"*.pyc",
"*.log",
"test_*.json",
"debug_*.txt",
"*.tmp",
"temp_*"
]
removed_count = 0
for pattern in cleanup_targets:
for item in glob.glob(pattern):
try:
if os.path.isdir(item):
shutil.rmtree(item)
print(f"šļø Removed folder: {item}")
else:
os.remove(item)
print(f"šļø Removed file: {item}")
removed_count += 1
except Exception as e:
print(f"ā ļø Could not remove {item}: {e}")
print(f"š Removed {removed_count} temporary items")
def final_report():
"""Generate final cleanup report"""
print("\nš PHASE 4: FINAL CLEANUP REPORT")
print("-" * 40)
# Count remaining files
python_files = glob.glob("*.py")
disabled_files = glob.glob("*.py.disabled")
print(f"š Active Python files: {len(python_files)}")
print(f"š Disabled Python files: {len(disabled_files)}")
if python_files:
print("\nš Remaining active files:")
for file in python_files:
print(f" - {file}")
print("\nšÆ CLEANUP ACTIONS COMPLETED:")
print("ā
All Trading212 scripts disabled")
print("ā
API key security check performed")
print("ā
Temporary files cleaned up")
print("ā
Desktop environment secured")
print("\nš” RECOMMENDATIONS:")
print("1. Manually delete .disabled files if you want complete removal")
print("2. Empty Recycle Bin for permanent deletion")
print("3. Consider using virtual environments for future projects")
print("4. Store API keys in environment variables, not code")
def safe_self_cleanup():
"""Safely handle self-cleanup of this script"""
print("\n" + "=" * 60)
response = input("š§¹ Delete this cleanup script too? (y/n): ").lower().strip()
if response in ['y', 'yes']:
try:
current_script = os.path.basename(__file__)
if os.path.exists(current_script):
os.remove(current_script)
print(f"ā
Deleted: {current_script}")
print("š CLEANUP COMPLETE! All scripts removed.")
except Exception as e:
print(f"ā Could not delete this script: {e}")
print("š” Please manually delete cleanup_trading212.py")
else:
print("š” This cleanup script remains for future use.")
print(" Run it again if you need to clean up more files.")
if __name__ == "__main__":
try:
main_cleanup()
safe_self_cleanup()
except Exception as e:
print(f"š„ Cleanup error: {e}")
print("š” Please run the script again or manually delete files.")
print("\n" + "=" * 60)
print("š CLEANUP PROCESS FINISHED")
print("=" * 60)