Security guidelines for using ForexSmartBot in production.
β Never hardcode credentials:
# BAD
api_key = "sk-1234567890abcdef"
password = "mypassword"β Use environment variables:
# GOOD
import os
api_key = os.getenv('API_KEY')
password = os.getenv('PASSWORD')β Use .env files:
# .env file (not in git)
API_KEY=sk-1234567890abcdef
PASSWORD=mypassword
# In code
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('API_KEY')Set appropriate file permissions:
# Configuration files
chmod 600 config/secrets.json
# Log files
chmod 644 logs/*.log
# Scripts
chmod 755 scripts/*.pyAlways validate user input:
def validate_symbol(symbol: str) -> bool:
"""Validate trading symbol."""
if not symbol or len(symbol) > 20:
return False
# Check format
if not re.match(r'^[A-Z]{3,6}(=X)?$', symbol):
return False
return True
# Use validation
if not validate_symbol(user_input):
raise ValueError("Invalid symbol")If using databases, use parameterized queries:
# BAD
query = f"SELECT * FROM trades WHERE symbol = '{symbol}'"
# GOOD
query = "SELECT * FROM trades WHERE symbol = ?"
cursor.execute(query, (symbol,))Store securely:
# Use keyring for secure storage
import keyring
# Store
keyring.set_password("forexsmartbot", "api_key", api_key)
# Retrieve
api_key = keyring.get_password("forexsmartbot", "api_key")Implement rate limiting:
from functools import wraps
import time
def rate_limit(calls_per_second):
min_interval = 1.0 / calls_per_second
last_called = [0.0]
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kwargs)
last_called[0] = time.time()
return ret
return wrapper
return decorator
@rate_limit(10) # 10 calls per second
def api_call():
# Your API call
passAlways use HTTPS for API calls:
# GOOD
url = "https://api.example.com/data"
# BAD
url = "http://api.example.com/data" # InsecureEncrypt sensitive data:
from cryptography.fernet import Fernet
# Generate key (store securely)
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt
encrypted = cipher.encrypt(b"sensitive data")
# Decrypt
decrypted = cipher.decrypt(encrypted)Sanitize data before storage:
import html
# Sanitize user input
user_input = html.escape(user_input)
# Validate data types
if not isinstance(value, (int, float)):
raise TypeError("Invalid data type")Use secure file storage:
import os
import stat
# Create secure file
with open('secrets.json', 'w') as f:
f.write(secrets)
# Set permissions
os.chmod('secrets.json', stat.S_IRUSR | stat.S_IWUSR) # 600Use strong passwords:
import secrets
import string
def generate_password(length=16):
"""Generate secure random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
return ''.join(secrets.choice(alphabet) for _ in range(length))Use secure tokens:
import secrets
# Generate secure token
token = secrets.token_urlsafe(32)
# Store securely (not in code)
# Use environment variables or secure storageSecure session handling:
import secrets
from datetime import datetime, timedelta
class Session:
def __init__(self, user_id):
self.user_id = user_id
self.token = secrets.token_urlsafe(32)
self.expires = datetime.now() + timedelta(hours=1)
def is_valid(self):
return datetime.now() < self.expiresβ Bad error messages:
# BAD
raise Exception(f"API key {api_key} is invalid")β Safe error messages:
# GOOD
raise ValueError("Invalid API credentials")Don't log sensitive data:
# BAD
logger.info(f"API key: {api_key}")
# GOOD
logger.info("API authentication successful")Handle exceptions securely:
try:
# Sensitive operation
result = process_data(data)
except Exception as e:
# Log error without sensitive data
logger.error(f"Processing failed: {type(e).__name__}")
# Don't expose stack traces in production
if DEBUG_MODE:
raise
else:
return NoneScan for vulnerabilities:
# Using pip-audit
pip install pip-audit
pip-audit
# Using safety
pip install safety
safety checkUse security linters:
# Bandit for security issues
pip install bandit
bandit -r forexsmartbot/
# Pylint security checks
pylint --enable=security forexsmartbot/Keep dependencies updated:
# Check for updates
pip list --outdated
# Update securely
pip install --upgrade package-nameRestrict network access:
- Only allow necessary ports
- Block unnecessary services
- Use VPN for remote access
Always use encrypted connections:
import ssl
# Verify SSL certificates
context = ssl.create_default_context()
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIREDMonitor network activity:
import logging
# Log network requests
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('requests')
logger.setLevel(logging.INFO)Validate strategies before sharing:
from forexsmartbot.builder import StrategyBuilder
builder = StrategyBuilder()
# ... build strategy ...
# Validate before sharing
is_valid, errors = builder.validate_strategy()
if not is_valid:
raise ValueError(f"Strategy validation failed: {errors}")Review shared strategies:
- Check for malicious code
- Verify functionality
- Test thoroughly
- Review dependencies
Run strategies in sandbox:
# Use restricted execution environment
# (Future feature: Strategy sandbox)Separate environments:
- Development
- Staging
- Production
Use different credentials for each:
ENV = os.getenv('ENVIRONMENT', 'development')
if ENV == 'production':
api_key = os.getenv('PROD_API_KEY')
else:
api_key = os.getenv('DEV_API_KEY')Implement access control:
def require_permission(permission):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not has_permission(permission):
raise PermissionError("Access denied")
return func(*args, **kwargs)
return wrapper
return decorator
@require_permission('trade')
def execute_trade():
# Trading logic
passLog all sensitive operations:
import logging
audit_logger = logging.getLogger('audit')
def log_trade(trade_details):
audit_logger.info(f"Trade executed: {trade_details}")
# Don't log sensitive data like API keys- All credentials in environment variables
- No hardcoded secrets
- Dependencies scanned for vulnerabilities
- Code reviewed for security issues
- SSL/TLS enabled
- Firewall configured
- Access control implemented
- Audit logging enabled
- Monitor for suspicious activity
- Regular security updates
- Backup encryption enabled
- Log rotation configured
- Error messages don't expose sensitive data
- Regular security audits
- Dependency updates
- Access review
- Incident response plan
- Security monitoring
-
Immediately:
- Disable affected accounts
- Revoke compromised credentials
- Isolate affected systems
-
Investigate:
- Review logs
- Identify scope
- Document findings
-
Remediate:
- Fix vulnerabilities
- Update credentials
- Patch systems
-
Notify:
- Affected users
- Security team
- Authorities (if required)
Remember: Security is an ongoing process, not a one-time setup.