Add position validation endpoint and Telegram /validate command

- New API endpoint: /api/trading/validate-positions
- Validates TP1, TP2, SL, leverage, and position size against current settings
- Fixed position size calculation: config stores collateral, positions store total value
- Added /validate command to Telegram bot for remote checking
- Returns detailed report of any mismatches with expected vs actual values
This commit is contained in:
mindesbunister
2025-10-27 19:20:36 +01:00
parent eeb90ad455
commit dde25ad2c1
2 changed files with 318 additions and 0 deletions

View File

@@ -99,6 +99,82 @@ async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
print(f"❌ Error: {e}", flush=True)
await update.message.reply_text(f"❌ Error: {str(e)}")
async def validate_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /validate command - check if positions match settings"""
# Only process from YOUR chat
if update.message.chat_id != ALLOWED_CHAT_ID:
await update.message.reply_text("❌ Unauthorized")
return
print(f"🔍 /validate command received", flush=True)
try:
# Fetch validation from trading bot API
response = requests.post(
f"{TRADING_BOT_URL}/api/trading/validate-positions",
headers={'Authorization': f'Bearer {API_SECRET_KEY}'},
timeout=10
)
print(f"📥 API Response: {response.status_code}", flush=True)
if not response.ok:
await update.message.reply_text(f"❌ Error validating positions: {response.status_code}")
return
data = response.json()
if not data.get('success'):
await update.message.reply_text("❌ Failed to validate positions")
return
# Get summary
summary = data.get('summary', {})
config = data.get('config', {})
positions = data.get('positions', [])
if not positions:
await update.message.reply_text("📊 *No positions to validate*\n\nAll clear!", parse_mode='Markdown')
return
# Build validation report
message = "🔍 *Position Validation Report*\n\n"
message += f"*Current Settings:*\n"
message += f" Leverage: {config.get('leverage')}x\n"
message += f" Position Size: ${config.get('positionSize')}\n"
message += f" TP1: {config.get('tp1Percent')}%\n"
message += f" TP2: {config.get('tp2Percent')}%\n"
message += f" SL: {config.get('stopLossPercent')}%\n\n"
message += f"*Summary:*\n"
message += f" Total: {summary.get('totalPositions')}\n"
message += f" ✅ Valid: {summary.get('validPositions')}\n"
message += f" ⚠️ Issues: {summary.get('positionsWithIssues')}\n\n"
# Show each position with issues
for pos in positions:
if not pos['isValid']:
message += f"*{pos['symbol']} {pos['direction'].upper()}*\n"
message += f"Entry: ${pos['entryPrice']:.4f}\n"
for issue in pos['issues']:
emoji = "" if issue['type'] == 'error' else "⚠️"
message += f"{emoji} {issue['message']}\n"
message += "\n"
if summary.get('validPositions') == summary.get('totalPositions'):
message = "✅ *All positions valid!*\n\n" + message
await update.message.reply_text(message, parse_mode='Markdown')
print(f"✅ Validation sent", flush=True)
except Exception as e:
print(f"❌ Error: {e}", flush=True)
await update.message.reply_text(f"❌ Error: {str(e)}")
async def trade_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle trade commands like /buySOL, /sellBTC, etc."""
@@ -161,6 +237,7 @@ def main():
print(f"🤖 Trading Bot: {TRADING_BOT_URL}", flush=True)
print(f"\n✅ Commands:", flush=True)
print(f" /status - Show open positions", flush=True)
print(f" /validate - Validate positions against settings", flush=True)
print(f" /buySOL, /sellSOL", flush=True)
print(f" /buyBTC, /sellBTC", flush=True)
print(f" /buyETH, /sellETH", flush=True)
@@ -170,6 +247,7 @@ def main():
# Add command handlers
application.add_handler(CommandHandler("status", status_command))
application.add_handler(CommandHandler("validate", validate_command))
application.add_handler(CommandHandler("buySOL", trade_command))
application.add_handler(CommandHandler("sellSOL", trade_command))
application.add_handler(CommandHandler("buyBTC", trade_command))