Skip to content

Latest commit

 

History

History
144 lines (112 loc) · 5.55 KB

File metadata and controls

144 lines (112 loc) · 5.55 KB

Momentum Flip Trading Agent — Context & Documentation

Purpose

This agent is a modular, automated trading system designed to trade perpetual futures on Hyperliquid using the Momentum Flip strategy. It detects reversals in price momentum using RSI and MACD indicators across multiple timeframes, then executes trades with disciplined risk management.


Design Philosophy

Modularity

Each concern is isolated into its own module:

  • Data ingestion is separate from signal generation.
  • Signal generation is separate from order execution.
  • Risk management is a hard gate before any order is placed.
  • Logging is passive and never blocks trading logic.

Safety First

  • Every order passes through risk.py before execution.
  • Daily loss caps halt trading automatically.
  • Stop-losses are placed immediately after entry.
  • Position sizing is always percentage-based, never fixed dollar.

Transparency

  • Every signal, order, fill, and rejection is logged with a timestamp.
  • The MCP server exposes real-time strategy state via simple commands.
  • No silent failures — all exceptions are caught, logged, and surfaced.

Strategy: Momentum Flip

What It Detects

A momentum flip is a high-probability reversal signal that occurs when:

  1. RSI crosses back through the 30 (oversold → bullish flip) or 70 (overbought → bearish flip) threshold.
  2. MACD histogram changes sign (negative → positive for long, positive → negative for short).
  3. Both signals align on the same candle across the primary timeframe.

Multi-Level Confirmation

  • Level 1 (Primary): 15m candle — determines trade direction.
  • Level 2 (Filter): 1h candle — must agree on trend direction (no counter-trend trades).
  • Level 3 (Entry Trigger): 5m candle — precise entry timing after Level 1 signal.

Signal Flow

1h trend filter → 15m momentum flip signal → 5m entry trigger → risk check → order execution

Module Overview

File Responsibility
data_feed.py Fetch OHLCV candles via REST; subscribe to live ticks via WebSocket
strategy_flip.py Compute RSI + MACD; detect flip conditions; emit BUY/SELL/HOLD signals
execution.py Place market/limit orders, set TP/SL, cancel open orders via Hyperliquid REST
risk.py Position sizing, stop-loss calculation, daily loss cap enforcement
controller.py Main agent loop; orchestrates all modules; handles start/stop lifecycle
logging_agent.py Structured JSON logging of signals, orders, fills, and P&L
mcp_server.py MCP control server; accepts start_flip, stop_trading, status commands

Usage Instructions

1. Install Dependencies

pip install -r requirements.txt

2. Configure Environment

cp .env.template .env
# Edit .env with your Hyperliquid API credentials and risk parameters

3. Run the Agent

python controller.py

4. Run with MCP Server (optional)

# Terminal 1 — start MCP server
python mcp_server.py

# Terminal 2 — send commands
python mcp_client.py start_flip
python mcp_client.py status
python mcp_client.py stop_trading

5. View Logs

tail -f logs/trades.log

Risk Parameters (configured in .env)

Parameter Description Default
MAX_POSITION_SIZE_USD Maximum notional per trade 500
RISK_PER_TRADE_PCT % of account equity risked per trade 1.0
STOP_LOSS_PCT Stop-loss distance from entry 1.5%
TAKE_PROFIT_PCT Take-profit distance from entry 3.0%
DAILY_LOSS_CAP_USD Agent halts if daily loss exceeds this 100
MAX_OPEN_POSITIONS Maximum concurrent open positions 3

Architecture Diagram

┌─────────────────────────────────────────────────────────┐
│                     controller.py                        │
│              (Main Agent Loop / Orchestrator)            │
└────────┬──────────┬──────────┬──────────┬───────────────┘
         │          │          │          │
    ┌────▼───┐ ┌────▼────┐ ┌──▼───┐ ┌───▼──────┐
    │data_   │ │strategy_│ │risk  │ │execution │
    │feed.py │ │flip.py  │ │.py   │ │.py       │
    └────┬───┘ └────┬────┘ └──┬───┘ └───┬──────┘
         │          │          │          │
         └──────────┴──────────┴──────────┘
                          │
                  ┌───────▼────────┐
                  │ logging_agent  │
                  │     .py        │
                  └───────┬────────┘
                          │
                  ┌───────▼────────┐
                  │  mcp_server.py │
                  │ (Control Plane)│
                  └────────────────┘

Disclaimer

This software is for educational and research purposes. Trading perpetual futures involves significant financial risk. Always test on paper/testnet before deploying real capital. The authors are not responsible for any financial losses.