feat(quant): Human-in-the-Loop Expert Trader Advisory & Dynamic Learning Engine
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Hermes Strategy Learner Daemon Script.
|
||||
Invoked when an Expert Advisor friend types or speaks trading rules in Telegram.
|
||||
Parses rule, stores into expert_strategies.json, updates MEMORY.md, and notifies both parties.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger("HermesStrategyLearner")
|
||||
|
||||
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "8622249634:AAFyJk4eaH3txNVIJ36m-48z8ib4mCUJjfg")
|
||||
MASTER_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "7107005438")
|
||||
BACKEND_STRATEGY_URL = "http://127.0.0.1:8085/api/v1/hermes/advisor/strategy"
|
||||
LOCAL_STRATEGIES_JSON = "/opt/data/skills/trading/expert_strategies.json"
|
||||
MEMORY_MD = "/opt/data/MEMORY.md"
|
||||
|
||||
def send_telegram(chat_id: str, text: str):
|
||||
try:
|
||||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
||||
payload = json.dumps({
|
||||
"chat_id": chat_id,
|
||||
"text": text,
|
||||
"parse_mode": "Markdown"
|
||||
}).encode("utf-8")
|
||||
req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=8) as resp:
|
||||
return resp.status == 200
|
||||
except Exception as e:
|
||||
logger.error(f"Telegram dispatch failed: {e}")
|
||||
return False
|
||||
|
||||
def learn_strategy(author_id: str, author_name: str, advice_text: str):
|
||||
author_id = str(author_id).strip()
|
||||
advice_text = advice_text.strip()
|
||||
logger.info(f"Learning strategy from {author_name} ({author_id}): {advice_text}")
|
||||
|
||||
result_data = None
|
||||
# 1. Try calling backend API
|
||||
try:
|
||||
payload = json.dumps({
|
||||
"advice": advice_text,
|
||||
"author_id": author_id,
|
||||
"author_name": author_name
|
||||
}).encode("utf-8")
|
||||
req = urllib.request.Request(BACKEND_STRATEGY_URL, data=payload, headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
result_data = json.loads(resp.read().decode("utf-8"))
|
||||
except Exception as e:
|
||||
logger.warning(f"Backend strategy API unavailable, performing local synthesis: {e}")
|
||||
|
||||
# Fallback local synthesis if backend is offline
|
||||
if not result_data or not result_data.get("strategy"):
|
||||
is_sell = any(w in advice_text.lower() for w in ["sell", "short", "সেল", "শর্ট", "বিক্রি", "নামবে"])
|
||||
direction = "SELL" if is_sell else "BUY"
|
||||
strat_id = f"strat-exp-{int(datetime.now(timezone.utc).timestamp())}"
|
||||
name = "Expert High Reversal Scalp" if is_sell else "Expert Discount Momentum Ingestion"
|
||||
strategy = {
|
||||
"id": strat_id,
|
||||
"name": name,
|
||||
"author_id": author_id,
|
||||
"author_name": author_name,
|
||||
"symbol": "XAUUSD",
|
||||
"timeframe": "15m",
|
||||
"direction": direction,
|
||||
"trigger_condition": advice_text,
|
||||
"sl_pips": 15.0,
|
||||
"tp_pips": 42.0,
|
||||
"risk_pct": 1.0,
|
||||
"rules_bengali": f"পরামর্শ: '{advice_text}'। মার্কেট কনডিশন ম্যাচ হলে {direction} ট্রেড এক্সিকিউট হবে।",
|
||||
"status": "ACTIVE_WATCH",
|
||||
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
|
||||
}
|
||||
else:
|
||||
strategy = result_data["strategy"]
|
||||
|
||||
# 2. Save into /opt/data/skills/trading/expert_strategies.json
|
||||
try:
|
||||
os.makedirs(os.path.dirname(LOCAL_STRATEGIES_JSON), exist_ok=True)
|
||||
strats = []
|
||||
if os.path.exists(LOCAL_STRATEGIES_JSON):
|
||||
with open(LOCAL_STRATEGIES_JSON, "r", encoding="utf-8") as f:
|
||||
strats = json.load(f)
|
||||
strats.append(strategy)
|
||||
with open(LOCAL_STRATEGIES_JSON, "w", encoding="utf-8") as f:
|
||||
json.dump(strats, f, indent=2, ensure_ascii=False)
|
||||
logger.info(f"Saved strategy to {LOCAL_STRATEGIES_JSON}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving to expert strategies file: {e}")
|
||||
|
||||
# 3. Append to MEMORY.md for persistent agent recall
|
||||
try:
|
||||
if os.path.exists(MEMORY_MD):
|
||||
entry = (
|
||||
f"\n\n### 🧠 Expert Learned Strategy: {strategy['name']}\n"
|
||||
f"- **Author:** {author_name} (Telegram: {author_id})\n"
|
||||
f"- **Condition:** {strategy['trigger_condition']}\n"
|
||||
f"- **Execution:** {strategy['direction']} {strategy['symbol']} ({strategy['timeframe']})\n"
|
||||
f"- **Risk Guard:** 1.0% Equity Max Risk (${strategy['sl_pips']} pips SL)\n"
|
||||
f"- **Status:** ACTIVE_WATCH ({strategy['created_at']})\n"
|
||||
)
|
||||
with open(MEMORY_MD, "a", encoding="utf-8") as f:
|
||||
f.write(entry)
|
||||
logger.info("Appended strategy to MEMORY.md")
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not update MEMORY.md: {e}")
|
||||
|
||||
# 4. Reply to the Expert Friend
|
||||
reply_msg = (
|
||||
f"🎯 *অসংখ্য ধন্যবাদ {author_name} স্যার!*\n\n"
|
||||
f"আপনার কৌশলটি হার্মেসের কোয়ান্ট ব্রেনে সক্রিয় করা হয়েছে:\n"
|
||||
f"• *কৌশলের নাম:* `{strategy['name']}`\n"
|
||||
f"• *অ্যাসেট ও দিক:* {strategy['direction']} {strategy['symbol']} ({strategy['timeframe']})\n"
|
||||
f"• *লজিক:* {strategy['rules_bengali']}\n"
|
||||
f"• *স্টপ লস:* {strategy['sl_pips']} পিপস (সেন্টিনেল ১% ক্যাপিটাল শিল্ড)\n"
|
||||
f"• *টেক প্রফিট:* {strategy['tp_pips']} পিপস (১:২.৮ আর:আর)\n\n"
|
||||
f"মার্কেটে এই সেটআপ আসামাত্রই হার্মেস স্বয়ংক্রিয়ভাবে এক্সিকিউট করবে এবং আপনাকে রেজাল্ট কার্ড পাঠাবে।"
|
||||
)
|
||||
send_telegram(author_id, reply_msg)
|
||||
|
||||
# 5. Alert Master Redwan
|
||||
if author_id != MASTER_CHAT_ID:
|
||||
master_alert = (
|
||||
f"🧠 *[New Strategy Learned!]*\n"
|
||||
f"উস্তাদ, আপনার এক্সপার্ট বন্ধু *{author_name}* হার্মেসকে একটি নতুন উইনিং স্ট্র্যাটেজি শিখিয়েছেন:\n\n"
|
||||
f"• *নাম:* `{strategy['name']}`\n"
|
||||
f"• *দিক:* {strategy['direction']} XAUUSD\n"
|
||||
f"• *লজিক:* {strategy['rules_bengali']}\n"
|
||||
f"• *রিস্ক শিল্ড:* ১% ক্যাপ্ড ($০.১৫ Max)\n"
|
||||
f"হার্মেস এটি সরাসরি ওয়াচলিস্টে সক্রিয় করেছে।"
|
||||
)
|
||||
send_telegram(MASTER_CHAT_ID, master_alert)
|
||||
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Hermes Strategy Learner")
|
||||
parser.add_argument("--author-id", required=True, help="Telegram User ID")
|
||||
parser.add_argument("--author-name", default="Expert Advisor", help="Telegram Name")
|
||||
parser.add_argument("--advice", required=True, help="Trading Advice / Rules Text")
|
||||
args = parser.parse_args()
|
||||
|
||||
learn_strategy(args.author_id, args.author_name, args.advice)
|
||||
Reference in New Issue
Block a user