### Start AlphaTrader Service Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Starts the AlphaTrader user service. Use this command to launch the service after installation or after stopping it. ```bash systemctl --user start alphatrader ``` -------------------------------- ### Non-pip-installable tools setup Source: https://github.com/14h034160212/alphatrader/blob/main/requirements-agentreach.txt These tools are not pip-installable and must be set up separately: node.js (>=18) for mcporter, npm install -g mcporter for Exa MCP client, and agent-reach install for channel tooling. ```text # - node.js (>=18) : runtime for mcporter # - npm install -g mcporter : Exa MCP client -> mcporter config add exa https://mcp.exa.ai/mcp # - agent-reach install --env=auto --channels=twitter : channel tooling (uv-installs the `twitter` CLI to ~/.local/bin) ``` -------------------------------- ### Install Ollama and pull DeepSeek-R1 70B Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Installs Ollama and pulls the DeepSeek-R1 70B model (DRL70B:latest, ~42GB). Verifies the installation with 'ollama list', which should display the model and its size. ```bash # Install Ollama (if not installed) curl -fsSL https://ollama.com/install.sh | sh # Pull DeepSeek-R1 70B (~42GB) ollama pull DRL70B:latest # Verify ollama list # Should display: DRL70B:latest 42.5GB ``` -------------------------------- ### Install serenity-trader-stack Source: https://github.com/14h034160212/alphatrader/blob/main/README.md One-command install for the serenity-trader-stack. Idempotent and safe to re-run. Clones three external repos, installs markdown skills into ~/.claude/, writes helper scripts, sets up reports/ folder, and writes CLAUDE.md. ```bash bash install-trader-stack.sh ``` -------------------------------- ### Troubleshoot Service Startup Failure Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Use these commands when the AlphaTrader service fails to start. They show how to view detailed error logs, check port usage, and run a manual startup test with uvicorn. ```bash # View detailed error logs tail -50 /tmp/alphatrader.log # Check port usage ss -tlnp | grep 8000 # Manual startup test cd /data/qbao775/AlphaTrader/backend /data/qbao775/miniconda3/envs/alphatrader/bin/python3 -c " import uvicorn uvicorn.run('main:app', host='0.0.0.0', port=8000) " ``` -------------------------------- ### Install agent-reach from GitHub Source: https://github.com/14h034160212/alphatrader/blob/main/requirements-agentreach.txt agent-reach is not on PyPI; it is installed from GitHub and pulls its own dependencies (yt-dlp, feedparser, loguru, rich, python-dotenv, etc.). It provides the `twitter` channel CLI and the `agent-reach` command. ```text https://github.com/Panniantong/agent-reach/archive/main.zip ``` -------------------------------- ### Create conda environment and install dependencies Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Creates the alphatrader conda environment with Python 3.10, installs PyTorch 2.6.0 for CUDA 12.4, and installs all project dependencies. Uses absolute paths to the conda environment's pip. ```bash conda create -n alphatrader python=3.10 -y # Install PyTorch (CUDA 12.4) /data/qbao775/miniconda3/envs/alphatrader/bin/pip install \ torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124 # Install all project dependencies /data/qbao775/miniconda3/envs/alphatrader/bin/pip install \ numpy pandas \ fastapi "uvicorn[standard]" \ sqlalchemy \ pydantic \ "python-jose[cryptography]" \ bcrypt \ python-multipart \ requests \ yfinance \ ta \ feedparser \ "alpaca-trade-api" \ "alpha_vantage==2.3.1" \ transformers \ huggingface_hub \ accelerate \ sentencepiece \ einops \ safetensors \ tqdm ``` -------------------------------- ### Install and configure Moomoo OpenD for HK trading Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Installs and configures Moomoo OpenD for Hong Kong trading. Requires a logged-in Moomoo account to download the tarball. OpenD must complete a one-time API Questionnaire in the Moomoo app before accepting logins; otherwise it exits with a 'regulatory requirements' error. ```bash # Download OpenD Linux tarball from Moomoo's official site # (region-gated, must use a logged-in Moomoo account) mkdir -p ~/moomoo-opend && cd ~/moomoo-opend # extract the tarball: tar -xzf moomoo_OpenD_*.tar.gz --strip-components=2 # Edit OpenD.xml — fill in your Moomoo UserID + 32-char MD5 of password # (generate MD5 locally: printf '你的密码' | md5sum | cut -d' ' -f1) # Enable telnet (line ~40 of OpenD.xml) for first-time 2FA setup: # 127.0.0.1 # 22222 chmod 600 OpenD.xml # First launch will trigger SMS 2FA. Pipe code in via telnet: nohup ./OpenD > opend.console.log 2>&1 & # Then in another shell (or via Python socket), send to 127.0.0.1:22222: # input_phone_verify_code -code=NNNNNN # Wire SerenityAlphaTrader to OpenD via the DB settings table: # futu_enabled=true # futu_host=127.0.0.1 # futu_port=11111 # futu_security_firm=FUTUAU # for Moomoo NZ/AU. Use FUTUSECURITIES for Futu HK # futu_trade_env=REAL # or SIMULATE for paper # futu_hk_acc_id= # required when futu_trade_env=REAL ``` -------------------------------- ### Install Agent Reach in a separate conda environment Source: https://github.com/14h034160212/alphatrader/blob/main/requirements-agentreach.txt Create a conda environment named 'agentreach' with Python 3.11 and install the requirements file. This must be done in a separate environment, never the trading env. ```bash conda create -n agentreach python=3.11 -y pip install -r requirements-agentreach.txt ``` -------------------------------- ### Install Agent Reach and configure Twitter/Exa Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Installs Agent Reach in its own isolated conda environment (Python 3.11) to power live Serenity tweets, Exa news search, and smart-money/news/deposit watchers. Also configures Exa via mcporter and sets up X/Twitter authentication using a burner account; the twitter.env file is read by fetch_serenity_tweets.sh and must be chmod 600. ```bash conda create -n agentreach python=3.11 -y /data/qbao775/miniconda3/envs/agentreach/bin/pip install \ "https://github.com/Panniantong/agent-reach/archive/main.zip" /data/qbao775/miniconda3/envs/agentreach/bin/agent-reach install --env=auto # zero-config channels /data/qbao775/miniconda3/envs/agentreach/bin/agent-reach install --channels=twitter # X channel tooling # Exa global semantic search (needs node + mcporter, npm-global into miniconda) npm install -g mcporter mcporter config add exa https://mcp.exa.ai/mcp # writes ./config/mcporter.json # X / Twitter auth — use a BURNER account, never your main one (datacenter-IP # scraping can get an account rate-limited/locked). Export cookies with the # Cookie-Editor extension on x.com (Export → Header String), then: # agent-reach configure twitter-cookies "PASTED_STRING" # and store the auth for cron (chmod 600), read by fetch_serenity_tweets.sh: cat > ~/.agent-reach/twitter.env <<'EOF' export TWITTER_AUTH_TOKEN="..." # from the burner account's cookies export TWITTER_CT0="..." EOF chmod 600 ~/.agent-reach/twitter.env ``` -------------------------------- ### Clone AlphaTrader repository Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Clones the AlphaTrader repository and changes into the project directory. Required before any other setup steps. ```bash git clone https://github.com/14H034160212/AlphaTrader.git cd /data/qbao775/AlphaTrader ``` -------------------------------- ### Generate SECRET_KEY and write backend/.env Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Generates a fresh 64-character hex SECRET_KEY and writes it to backend/.env, then restricts permissions to the owner. Run on your local machine, not in chat. The backend refuses to start without SECRET_KEY; start.sh sources this file before launching uvicorn. ```bash python3 -c "import secrets; print(f'SECRET_KEY={secrets.token_hex(32)}')" > backend/.env chmod 600 backend/.env # important — file contains a credential ``` -------------------------------- ### Macro Scenario Lifecycle State Diagram Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Mermaid state diagram for the macro scenario lifecycle: scenarios start ACTIVE, can transition to DECLINING after 3h without evidence or ≥2 resolution keywords, back to ACTIVE with new evidence after a 20-min cooldown, to RESOLVED with ≥4 resolution keywords or AI review, or to EXPIRED after 12h with zero evidence. ```mermaid stateDiagram-v2 [*] --> ACTIVE: Trigger keywords matched / AI creates new scenario ACTIVE --> ACTIVE: Evidence found (evidence_count + 1) ACTIVE --> DECLINING: 3h with no evidence OR resolution keywords ≥ 2 DECLINING --> ACTIVE: New evidence appears (after 20 min cooldown) DECLINING --> RESOLVED: Resolution keywords ≥ 4 OR AI review confirms resolved DECLINING --> EXPIRED: 12h with zero evidence ACTIVE --> RESOLVED: Resolution keywords ≥ 4 OR AI review (every 6h) RESOLVED --> [*] EXPIRED --> [*] ``` -------------------------------- ### Download Kronos model weights from HuggingFace Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Downloads the Kronos model weights and tokenizer from HuggingFace using snapshot_download. The base model ignores .bin files; the tokenizer is downloaded separately. Prints 'Done' when finished. ```bash /data/qbao775/miniconda3/envs/alphatrader/bin/python3 -c " from huggingface_hub import snapshot_download snapshot_download( repo_id='NeoQuasar/Kronos-base', local_dir='/data/qbao775/AlphaTrader/kronos_lib/weights/Kronos-base', ignore_patterns=['*.bin'] ) snapshot_download( repo_id='NeoQuasar/Kronos-Tokenizer-base', local_dir='/data/qbao775/AlphaTrader/kronos_lib/weights/Kronos-Tokenizer-base' ) print('Done') " ``` -------------------------------- ### Configure systemd user service for auto-start Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Creates a systemd user service for auto-starting the backend. The service runs start.sh, restarts on failure after 5 seconds, and logs to /tmp/alphatrader.log. On shared servers where systemctl --user fails, run start.sh via setsid nohup instead. ```bash mkdir -p ~/.config/systemd/user cat > ~/.config/systemd/user/alphatrader.service << 'EOF' [Unit] Description=SerenityAlphaTrader Backend Service After=network.target [Service] Type=simple WorkingDirectory=/data/qbao775/AlphaTrader ExecStart=/bin/bash /data/qbao775/AlphaTrader/start.sh Restart=on-failure RestartSec=5 StandardOutput=append:/tmp/alphatrader.log StandardError=append:/tmp/alphatrader.log [Install] WantedBy=default.target EOF chmod 600 ~/.config/systemd/user/alphatrader.service systemctl --user daemon-reload systemctl --user enable alphatrader ``` -------------------------------- ### Boot sequence: refresh date and snapshot portfolio Source: https://github.com/14h034160212/alphatrader/blob/main/serenity-trader-stack/CLAUDE.md Run before any Claude Code session to anchor today's date and pull fresh positions. The snapshot script requires brokers to be reachable. ```bash cd /home/qbao775/serenity-trader-stack ./scripts/refresh-today.sh # anchors today's date ./scripts/snapshot-portfolio.sh # pulls fresh positions (requires brokers reachable) ``` -------------------------------- ### Swap base LLM via Python script Source: https://github.com/14h034160212/alphatrader/blob/main/RL_PIPELINE.md Run this Python script in the backend/ directory with the alphatrader env active to change the Ollama host and model. Then restart the backend with the provided pkill command; the start.sh while-loop will respawn it. ```python # In backend/ with the alphatrader env active: python -c " from database import SessionLocal, set_setting db = SessionLocal() set_setting(db, 'ollama_host', 'http://localhost:11435', 1) # 11434 = system, 11435 = user set_setting(db, 'ollama_model', 'qwen3.5:35b', 1) db.close() " # Then restart backend (kills python, start.sh while-loop respawns): pkill -9 -f "uvicorn.run.*8888" ``` -------------------------------- ### Project structure overview Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Shows the directory layout of the SerenityAlphaTrader project, including backend, frontend, and Kronos model components. Useful for understanding where each module and configuration file resides. ```text SerenityAlphaTrader/ ├── start.sh # Startup script (includes auto-restart daemon) ├── stop.sh # Stop script ├── rl_training_data.jsonl # RL training data (appended per trade) ├── intelligence_attribution_report.json # Signal attribution analysis report │ ├── backend/ │ ├── main.py # FastAPI app + background tasks │ ├── auth.py # JWT authentication (bcrypt) │ ├── database.py # SQLAlchemy models + SQLite (incl. SignalArchive) │ ├── trading_engine.py # Trading engine (Alpaca Notional orders + short protection) │ ├── market_data.py # Market data + technical indicators │ ├── deepseek_ai.py # DeepSeek-R1 / Ollama AI analysis │ ├── kronos_analysis.py # Kronos K-line prediction (A100 GPU) │ ├── news_intelligence.py # News + macro scenario detection + geopolitical RSS │ ├── social_sentiment.py # StockTwits + Reddit sentiment scanning │ ├── blog_monitor.py # AI company blog RSS monitoring │ ├── event_monitor.py # Earnings / macro event calendar │ ├── intelligence_feedback.py # RL signal feedback & reward calculation │ ├── rl_data_collector.py # RL training data collector │ ├── quant_models.py # Quantitative models (DCF/DDM/VPA) │ ├── notifier.py # Notifications │ ├── trading_platform.db # SQLite runtime database │ └── requirements.txt # Python dependencies (for reference, use conda env) │ ├── frontend/ │ ├── index.html # SPA main page │ ├── app.js # Frontend logic (market/trading/AI analysis) │ └── styles.css # Dark theme styles │ └── kronos_lib/ # Kronos model (cloned from git) ├── model/ # Kronos code │ ├── __init__.py │ └── kronos.py # KronosTokenizer, Kronos, KronosPredictor ├── prediction_results/ # Kronos prediction results (JSON, auto-gzipped >90 days) └── weights/ ├── Kronos-base/ # Model weights (HuggingFace) └── Kronos-Tokenizer-base/ # Tokenizer weights ``` -------------------------------- ### Configure Alpaca and auto-trading via API Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Use these curl commands to configure the trading system via the API. First obtain an access token from the auto-login endpoint, then set Alpaca credentials, disable paper mode, enable auto-trading, and select the AI provider. Replace YOUR_KEY and YOUR_SECRET with actual values. ```bash TOKEN=$(curl -s http://localhost:8000/api/auth/auto-login | \ python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])") # Configure Alpaca for Live trading curl -s -X POST http://localhost:8000/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"key":"alpaca_api_key","value":"YOUR_KEY"}' curl -s -X POST http://localhost:8000/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"key":"alpaca_secret_key","value":"YOUR_SECRET"}' curl -s -X POST http://localhost:8000/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"key":"alpaca_paper_mode","value":"false"}' # Enable auto-trading curl -s -X POST http://localhost:8000/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"key":"auto_trade_enabled","value":"true"}' curl -s -X POST http://localhost:8000/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"key":"ai_provider","value":"ollama"}' ``` -------------------------------- ### Manual control curl commands Source: https://github.com/14h034160212/alphatrader/blob/main/RL_PIPELINE.md Use these curl commands to manually trigger pipeline cycles, model shootouts, LoRA auto-deployment, manual deployment, rollback, and promote shadow XGBoost. The shootout takes about 30 minutes. ```bash # Force a pipeline cycle now curl -X POST http://localhost:8888/api/rl/pipeline/run # Trigger a model shootout (~30 min) curl -X POST 'http://localhost:8888/api/rl/shootout?test_set=challenge' # Enable LoRA auto-deployment curl -X POST http://localhost:8888/api/rl/lora/auto-deploy/true # Manually deploy current adapter curl -X POST http://localhost:8888/api/rl/lora/deploy # Roll back LoRA (revert to Ollama) curl -X POST http://localhost:8888/api/rl/lora/rollback # Promote shadow XGBoost to production curl -X POST http://localhost:8888/api/rl/promote-shadow ``` -------------------------------- ### Troubleshoot Kronos CUDA OOM Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Use these commands when Kronos fails to load due to CUDA out-of-memory. Check GPU memory usage and modify start.sh to select a more idle GPU. ```bash # Check GPU memory usage nvidia-smi --query-gpu=index,memory.used,memory.free --format=csv # Modify start.sh to select a more idle GPU # E.g., Change CUDA_VISIBLE_DEVICES=7 to another free GPU index ``` -------------------------------- ### Troubleshoot Ollama Unresponsive Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Use these commands when Ollama is unresponsive. They check Ollama processes, verify model availability, and restart Ollama. ```bash # Check Ollama processes ps aux | grep ollama # Verify model availability curl http://localhost:11434/api/tags # Restart Ollama pkill ollama && ollama serve & ``` -------------------------------- ### Download Kronos model code Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Clones the Kronos model code into the kronos_lib directory. Must be run from the AlphaTrader project root. ```bash cd /data/qbao775/AlphaTrader/kronos_lib git clone https://github.com/shiyu-coder/Kronos.git . ``` -------------------------------- ### AI 红队对抗 Prompt Source: https://github.com/14h034160212/alphatrader/blob/main/SKILL.md 用于 Step 4 的 AI 红蓝队对抗,要求 AI 从七个角度攻击投资逻辑,并给出验证建议。 ```text 你现在是我的"红队"(Red Team)。请对我的以下投资逻辑进行最严厉的批判性审查。 我的论点是: [粘贴你的完整逻辑] 请从以下角度攻击我的论点: 1. 技术替代路径(有没有办法绕过这个瓶颈?) 2. 产能核实(声称的产能是否真实?) 3. 客户验证(是否有独立的客户确认?) 4. 估值透支(当前价格反映了多少年的增长?) 5. 地缘政治风险(供应链是否依赖单一国家?) 6. 管理层诚信(是否有历史问题?) 7. 流动性风险(日均成交量是否足够退出?) 对每个角度,请给出具体的质疑点,并建议我如何验证或反驳。 ``` -------------------------------- ### 逆向拆解示例:CPO/光互联供应链树 Source: https://github.com/14h034160212/alphatrader/blob/main/SKILL.md 展示从 GPU 集群到晶体生长/原料的逆向供应链拆解,用于 Step 2 绘制供应链地图。 ```text GPU 集群 / 数据中心 ASC(Trainium / Maia) → 网络交换芯片 → 光模块 → 外部光源(ELS)/ CW 激光器 → 衬底材料(InP / SOI) → 晶体生长 / 原料(镓、铟、砷) → 测试 / 封装设备 ``` -------------------------------- ### 反论表模板 Source: https://github.com/14h034160212/alphatrader/blob/main/SKILL.md 用于 Step 4 构建反论表,针对投资论点进行批判性审查,包含五个标准问题及量化指标。 ```text 【反论表:针对 ______ 的批判性审查】 1. 如果客户不放量怎么办? - 量化:如果需求只有预期的 ___%,利润影响是多少? - 对策:______ 2. 如果竞争者绕过这个技术路线怎么办? - 替代技术:______ - 替代时间窗口:______ - 对策:______ 3. 如果估值已经提前反映了预期怎么办? - 当前市值已反映 ___ 年的增长? - 安全边际:______ 4. 如果出现稀释或财报 miss 怎么办? - 最大稀释比例:______ - 历史 miss 频率:______ 5. 如何证伪这个论点?(Falsifiability) - 可观测的证伪信号:______ - 如果 ______ 发生,说明这个论点错了 ``` -------------------------------- ### Troubleshoot Alpaca Sell Rejection Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Use these commands when Alpaca sell orders are rejected due to short protection. They check if the local portfolio syncs with Alpaca actual holdings and query the actual position using the Alpaca API. ```bash # Check if local portfolio syncs with Alpaca actual holding curl -s http://localhost:8000/api/positions -H "Authorization: Bearer $TOKEN" # Query actual position using Alpaca API curl -s https://api.alpaca.markets/v2/positions \ -H "APCA-API-KEY-ID: YOUR_KEY" \ -H "APCA-API-SECRET-KEY: YOUR_SECRET" ``` -------------------------------- ### View Real-Time AlphaTrader Logs Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Streams the AlphaTrader log file in real time to monitor service activity and errors. ```bash tail -f /tmp/alphatrader.log ``` -------------------------------- ### Daily on-demand usage commands Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Daily on-demand usage of the serenity-trader-stack. Run refresh-today.sh and snapshot-portfolio.sh before any session, then use Claude Code slash commands and skills for portfolio review, investment research, and idea generation. No background daemons are required. ```bash # Before any session — refresh date + portfolio snapshot ~/serenity-trader-stack/scripts/refresh-today.sh ~/serenity-trader-stack/scripts/snapshot-portfolio.sh # IB Gateway / OpenD start on demand # In Claude Code (Opus 4.8) /portfolio-review # Re-evaluate current holdings against stored theses /investment-team # 4-master adversarial value research (Buffett/Munger/段/李) /dyp-ask "" # 段永平 persona "用 Serenity 卡点分析 " # Supply-chain chokepoint analysis (existing CN skill) "Run an idea-generation screen for ..." # Anthropic equity-research skill ``` -------------------------------- ### System Architecture Mermaid Graph Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Mermaid graph showing the overall system architecture: data sources (Yahoo Finance, RSS, StockTwits/Reddit, Kronos, DCF/DDM, Global Context, CFTC COT) feed the AI brain, which produces signals that pass through five risk filters before execution via TradingEngine to brokers (Alpaca, Futu, IBKR, Paper). Feedback from execution (RL data, email reports, signal archive) is fed back into the prompt. ```mermaid graph TB subgraph DATA["📡 Information Layer"] YF["Yahoo Finance
Quotes / K-lines / News"] RSS["15 RSS Feeds
Reuters / BBC / White House"] SS["StockTwits / Reddit
Retail Sentiment"] KRONOS["Kronos GPU Model
K-line Prediction (next 5)"] QUANT["DCF / DDM Valuation
Intrinsic Value"] GC["Global Context
VIX / Indices / FX"] COT["CFTC COT
Futures Positioning"] end subgraph SCENARIO["🌍 Macro Scenario Engine"] SCAN["Keyword Scanner
Every 10 min"] AIREV["AI Review
Every 6 hours"] DB_S[("scenario_states
SQLite")] LIFE["ACTIVE → DECLINING → RESOLVED"] end subgraph AI["🧠 AI Brain Layer"] PROMPT["Super-Prompt Builder
Quote + Technicals + Valuation + News
+ Scenarios + Sentiment + Predictions + Lessons"] LLM["Ollama DRL70B
/ DeepSeek-R1 API"] SIGNAL["JSON Signal Output
BUY / SELL / HOLD
confidence + target + stop_loss"] end subgraph FILTER["🛡️ Risk Control Layer"] F1["Gap Filter
Skip BUY if +3% today"] F2["Bear Filter
Skip BUY if SPY < MA20"] F3["Cooldown Filter
No re-buy within 3d of stop-loss"] F4["Market Hours
Skip if market closed"] F5["Kelly Sizing
Half-Kelly × VIX scaling"] end subgraph EXEC["⚡ Execution Layer"] ENGINE["TradingEngine
Auto broker routing"] ALP["Alpaca
US Stocks"] FUTU["Futu
CN / HK"] IBKR["IBKR
Global"] PAPER["Paper
Simulated"] end subgraph FB["🔄 Feedback Loop"] RL["RL Training Data
232MB+ JSONL"] EMAIL["Daily Email Report
P&L / Win Rate"] ARCHIVE["Signal Archive
90-day compression"] end YF --> PROMPT RSS --> PROMPT RSS --> SCAN SS --> PROMPT KRONOS --> PROMPT QUANT --> PROMPT GC --> PROMPT COT --> PROMPT SCAN --> DB_S AIREV --> DB_S DB_S --> LIFE DB_S --> PROMPT PROMPT --> LLM LLM --> SIGNAL SIGNAL --> F1 --> F2 --> F3 --> F4 --> F5 F5 --> ENGINE ENGINE --> ALP ENGINE --> FUTU ENGINE --> IBKR ENGINE --> PAPER ENGINE --> RL ENGINE --> EMAIL ENGINE --> ARCHIVE RL -.->|"Historical lessons
fed back into prompt"| PROMPT ``` -------------------------------- ### Daily monitoring curl commands Source: https://github.com/14h034160212/alphatrader/blob/main/RL_PIPELINE.md Use these curl commands to check pipeline state, model registry, comparisons, errors, challenge set growth, and LoRA service status. All endpoints are on localhost:8888. ```bash # Pipeline state curl http://localhost:8888/api/rl/pipeline # Model registry (every candidate ever trained) curl http://localhost:8888/api/rl/models # Apples-to-apples comparison curl http://localhost:8888/api/rl/compare # Production weak spots curl http://localhost:8888/api/rl/errors # Challenge set growth curl http://localhost:8888/api/rl/challenge # LoRA service curl http://localhost:8888/api/rl/lora/status ``` -------------------------------- ### Cron jobs for intelligence pipeline Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Cron schedule for the intelligence pipeline. All jobs use absolute paths to survive cron's minimal environment. Includes Serenity data refresh, tweet fetching, market regime, smart money, news watch, deposit watch, and daily email reports. ```cron */30 * * * * refresh_serenity_data.sh # yan-labs archive sync 23 */6 * * * fetch_serenity_tweets.sh 25 # LIVE Serenity tweets 17 6 * * * backend/refresh_serenity_intel.py # semiconstocks focus 0 13 * * 1-5 backend/market_regime.py # adaptive cash floor (pre-open) 13 7 * * 1,4 fetch_smart_money.sh # 13F + congress + Musk/Trump 47 13,15,17,19 * * 1-5 backend/news_watch.py # breaking-news alerts (market hours) */30 * * * * backend/deposit_watch.py # deposit auto-detect 33 21 * * 1-5 send_market_reports.sh # daily email (after US close) ``` -------------------------------- ### Trading Loop Sequence Diagram Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Mermaid sequence diagram of the trading loop: auto_trade_loop triggers every ~15-30 min, gathers data in parallel from market_data.py, news_intelligence.py, and Kronos, builds a super-prompt, calls the LLM with /no_think, stores the signal, applies 5 filters, and executes if confidence ≥ 75% (broadcasting via WebSocket) or skips with a logged reason. ```mermaid sequenceDiagram participant Trader as ⏱️ auto_trade_loop participant MD as market_data.py participant NI as news_intelligence.py participant KR as Kronos (A100 GPU) participant AI as LLM (Qwen3.5 35B) participant FLT as Risk Filters participant ENG as TradingEngine participant DB as SQLite Trader->>Trader: Triggered every ~15-30 min loop For each symbol in watchlist par Gather data in parallel Trader->>MD: get_stock_quote + history + indicators + news Trader->>NI: scan_all_threats + detect_catalysts Trader->>KR: predict_next_candles (5 candles) end Trader->>Trader: Build super-prompt (all data merged) Trader->>AI: analyze_stock(prompt) with /no_think AI-->>Trader: signal / confidence / target / stop Trader->>DB: Store AI signal Trader->>FLT: Apply 5 filters alt All filters passed & confidence ≥ 75% FLT->>ENG: Execute trade ENG->>DB: Record trade + update position ENG-->>Trader: Broadcast via WebSocket else Filtered out FLT-->>Trader: Skip (log reason) end end ``` -------------------------------- ### Pre-trade safety checks: ps aux, ss -tlnp, and DB re-read Source: https://github.com/14h034160212/alphatrader/blob/main/serenity-trader-stack/PLAN_D.md Mandatory pre-trade safety checks before any satellite trade. Each command must return empty output; if any check fails, stop and fix before placing an order. ```bash ps aux | grep -E "start\.sh|main:app|uvicorn.*8888" | grep -v grep # must be EMPTY ss -tlnp | grep 8888 # must be EMPTY # re-read auto_trade_enabled from DB fresh (not from memory/assumption) — must be 'false' ``` -------------------------------- ### Restart AlphaTrader Service Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Restarts the AlphaTrader user service. Use this command to apply configuration changes or recover from issues. ```bash systemctl --user restart alphatrader ``` -------------------------------- ### Remove Kill-switch and Restart AlphaTrader Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Removes the kill-switch file to restore normal operation, then restarts the service. The kill-switch prevents startup when the file exists. ```bash rm /data/qbao775/AlphaTrader/.DISABLE_AUTOSTART systemctl --user restart alphatrader ``` -------------------------------- ### Explicit dependencies for fetch scripts Source: https://github.com/14h034160212/alphatrader/blob/main/requirements-agentreach.txt These packages are explicitly used by the fetch scripts: pyyaml for parsing the twitter CLI's YAML output into lens JSON schema, and requests for HTTP requests. ```text pyyaml>=6.0 # parse the twitter CLI's YAML output -> lens JSON schema requests>=2.28.0 ``` -------------------------------- ### Stop AlphaTrader Service Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Stops the AlphaTrader user service. Use this command to halt the service when needed. ```bash systemctl --user stop alphatrader ``` -------------------------------- ### Check AlphaTrader Service Status Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Checks the status of the AlphaTrader user service, including whether it is active and any recent logs. ```bash systemctl --user status alphatrader ``` -------------------------------- ### Verify AlphaTrader API Health Source: https://github.com/14h034160212/alphatrader/blob/main/README.md Checks the health of the AlphaTrader API. A successful response returns a JSON object with status 'ok' and a timestamp. ```bash curl http://localhost:8888/api/health # Returns: {"status":"ok","timestamp":"..."} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.