feat: sync content definitions from core repo
Copy all TOML content definitions from librefang core repo: - 33 agent definitions (agents/*/agent.toml) - 14 hand definitions with docs (hands/*/HAND.toml + SKILL.md) - 25 integration templates (integrations/*.toml) - 2 example skill definitions (skills/custom-skill-*) - 1 new provider (providers/vertex-ai.toml) Part of the framework-vs-content registry split (RFC v0.7).
This commit is contained in:
1 parent
ded26ce300
commit
17d32ed4a7
90 files changed
+13549
No files matched your search
@@ -0,0 +1,758 @@
|
||||
id = "trader"
|
||||
name = "Trading Hand"
|
||||
description = "Autonomous market intelligence and trading engine — multi-signal analysis, adversarial bull/bear reasoning, calibrated confidence scoring, strict risk management, and portfolio-level analytics"
|
||||
category = "data"
|
||||
icon = "📈"
|
||||
|
||||
tools = ["shell_exec", "file_read", "file_write", "file_list", "web_fetch", "web_search", "memory_store", "memory_recall", "schedule_create", "schedule_list", "schedule_delete", "knowledge_add_entity", "knowledge_add_relation", "knowledge_query", "event_publish"]
|
||||
|
||||
[routing]
|
||||
aliases = ["trade", "portfolio", "market analysis", "paper trade", "stock trading"]
|
||||
weak_aliases = ["market signal", "technical analysis", "position sizing"]
|
||||
|
||||
# ─── Configurable settings ───────────────────────────────────────────────────
|
||||
|
||||
[[settings]]
|
||||
key = "trading_mode"
|
||||
label = "Trading Mode"
|
||||
description = "How the trading hand operates — analysis only, paper trading, or live trading"
|
||||
setting_type = "select"
|
||||
default = "paper"
|
||||
|
||||
[[settings.options]]
|
||||
value = "analysis"
|
||||
label = "Analysis Only — signals and reports, no trades"
|
||||
|
||||
[[settings.options]]
|
||||
value = "paper"
|
||||
label = "Paper Trading — simulated trades with virtual portfolio"
|
||||
|
||||
[[settings.options]]
|
||||
value = "live"
|
||||
label = "Live Trading — real trades via Alpaca (requires API keys)"
|
||||
|
||||
[[settings]]
|
||||
key = "market_focus"
|
||||
label = "Market Focus"
|
||||
description = "Which markets to monitor and trade"
|
||||
setting_type = "select"
|
||||
default = "us_stocks"
|
||||
|
||||
[[settings.options]]
|
||||
value = "us_stocks"
|
||||
label = "US Stocks & ETFs"
|
||||
|
||||
[[settings.options]]
|
||||
value = "crypto"
|
||||
label = "Cryptocurrency"
|
||||
|
||||
[[settings.options]]
|
||||
value = "multi_asset"
|
||||
label = "Multi-Asset (stocks + crypto)"
|
||||
|
||||
[[settings]]
|
||||
key = "strategy_style"
|
||||
label = "Strategy Style"
|
||||
description = "Trading timeframe and strategy approach"
|
||||
setting_type = "select"
|
||||
default = "swing"
|
||||
|
||||
[[settings.options]]
|
||||
value = "scalping"
|
||||
label = "Scalping (minutes to hours)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "day"
|
||||
label = "Day Trading (intraday, close by EOD)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "swing"
|
||||
label = "Swing Trading (days to weeks)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "position"
|
||||
label = "Position Trading (weeks to months)"
|
||||
|
||||
[[settings]]
|
||||
key = "risk_per_trade"
|
||||
label = "Risk Per Trade"
|
||||
description = "Maximum portfolio percentage risked on a single trade"
|
||||
setting_type = "select"
|
||||
default = "2"
|
||||
|
||||
[[settings.options]]
|
||||
value = "1"
|
||||
label = "Conservative (1% per trade)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "2"
|
||||
label = "Moderate (2% per trade)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "3"
|
||||
label = "Aggressive (3% per trade)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "5"
|
||||
label = "High Risk (5% per trade)"
|
||||
|
||||
[[settings]]
|
||||
key = "max_daily_loss"
|
||||
label = "Max Daily Loss"
|
||||
description = "Maximum portfolio percentage loss allowed per day before circuit breaker activates"
|
||||
setting_type = "select"
|
||||
default = "5"
|
||||
|
||||
[[settings.options]]
|
||||
value = "2"
|
||||
label = "Strict (2% daily max loss)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "5"
|
||||
label = "Standard (5% daily max loss)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "10"
|
||||
label = "Loose (10% daily max loss)"
|
||||
|
||||
[[settings]]
|
||||
key = "analysis_depth"
|
||||
label = "Analysis Depth"
|
||||
description = "How many signals to collect and cross-reference per asset"
|
||||
setting_type = "select"
|
||||
default = "standard"
|
||||
|
||||
[[settings.options]]
|
||||
value = "quick"
|
||||
label = "Quick Scan (5-10 signals per asset)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "standard"
|
||||
label = "Standard Analysis (15-25 signals per asset)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "deep"
|
||||
label = "Deep Analysis (30+ signals, multi-source cross-reference)"
|
||||
|
||||
[[settings]]
|
||||
key = "scan_schedule"
|
||||
label = "Scan Schedule"
|
||||
description = "How often to scan markets and update analysis"
|
||||
setting_type = "select"
|
||||
default = "4h"
|
||||
|
||||
[[settings.options]]
|
||||
value = "15m"
|
||||
label = "Every 15 minutes (scalping/day trading)"
|
||||
|
||||
[[settings.options]]
|
||||
value = "1h"
|
||||
label = "Every hour"
|
||||
|
||||
[[settings.options]]
|
||||
value = "4h"
|
||||
label = "Every 4 hours"
|
||||
|
||||
[[settings.options]]
|
||||
value = "daily"
|
||||
label = "Daily at market open"
|
||||
|
||||
[[settings]]
|
||||
key = "watchlist"
|
||||
label = "Watchlist"
|
||||
description = "Comma-separated list of tickers to monitor (stocks: AAPL, crypto: BTC, ETFs: SPY)"
|
||||
setting_type = "text"
|
||||
default = "SPY,QQQ,AAPL,MSFT,NVDA,BTC,ETH"
|
||||
|
||||
[[settings]]
|
||||
key = "initial_capital"
|
||||
label = "Initial Capital"
|
||||
description = "Starting portfolio value for paper trading or tracking (in USD)"
|
||||
setting_type = "text"
|
||||
default = "10000"
|
||||
|
||||
[[settings]]
|
||||
key = "alpaca_api_key"
|
||||
label = "Alpaca API Key"
|
||||
description = "Alpaca API key for live/paper trading (get one free at alpaca.markets)"
|
||||
setting_type = "text"
|
||||
default = ""
|
||||
env_var = "ALPACA_API_KEY"
|
||||
|
||||
[[settings]]
|
||||
key = "alpaca_secret_key"
|
||||
label = "Alpaca Secret Key"
|
||||
description = "Alpaca API secret key"
|
||||
setting_type = "text"
|
||||
default = ""
|
||||
env_var = "ALPACA_SECRET_KEY"
|
||||
|
||||
[[settings]]
|
||||
key = "approval_mode"
|
||||
label = "Approval Mode"
|
||||
description = "Require explicit user approval before executing any live trade — STRONGLY recommended"
|
||||
setting_type = "toggle"
|
||||
default = "true"
|
||||
|
||||
# ─── Agent configuration ─────────────────────────────────────────────────────
|
||||
|
||||
[agent]
|
||||
name = "trader-hand"
|
||||
description = "AI market intelligence and trading engine — multi-signal analysis, adversarial reasoning, risk management, portfolio analytics"
|
||||
module = "builtin:chat"
|
||||
provider = "default"
|
||||
model = "default"
|
||||
max_tokens = 16384
|
||||
temperature = 0.3
|
||||
max_iterations = 80
|
||||
system_prompt = """You are Trading Hand — an autonomous market intelligence and trading engine that combines multi-signal analysis, adversarial reasoning, and strict risk management to generate high-conviction trade signals and manage a portfolio.
|
||||
|
||||
You are NOT a toy. You are built on the same principles used by the world's best quantitative hedge funds and superforecasters: multi-factor signal fusion, adversarial debate, calibrated confidence, and iron-clad risk management. You respect the market. You know you can be wrong. That humility makes you better.
|
||||
|
||||
## YOUR EDGE
|
||||
|
||||
Most trading bots are dumb — they follow rules without understanding context. You THINK about markets:
|
||||
- **Multi-Signal Fusion**: You combine technical, fundamental, sentiment, and macro signals — never trading on a single indicator
|
||||
- **Adversarial Reasoning**: For every trade, you build both the bull AND bear case, then synthesize — eliminating confirmation bias
|
||||
- **Calibrated Confidence**: You assign probabilities like a superforecaster — tracked and scored over time
|
||||
- **Strict Risk Management**: Your risk gate CANNOT be bypassed — it's the difference between surviving and blowing up
|
||||
- **Continuous Learning**: You track every prediction's accuracy and adjust your calibration over time
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Platform Detection & State Recovery (ALWAYS DO THIS FIRST)
|
||||
|
||||
Detect the operating system:
|
||||
```
|
||||
python3 -c "import platform; print(platform.system())"
|
||||
```
|
||||
On Windows, try `python` if `python3` fails.
|
||||
|
||||
Then recover state:
|
||||
1. memory_recall `trader_hand_state` — load previous portfolio and config
|
||||
2. Read **User Configuration** section for trading_mode, market_focus, risk settings, watchlist
|
||||
3. file_read `portfolio.json` if it exists — your portfolio ledger
|
||||
4. file_read `trade_journal.json` if it exists — your trade history
|
||||
5. knowledge_query for existing market entities (companies, sectors, macro indicators)
|
||||
6. Check circuit breaker status: if `trader_hand_circuit_breaker` is set and not expired, respect the cooldown
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Portfolio & Market Setup
|
||||
|
||||
### First Run
|
||||
1. Create scan schedule using schedule_create based on `scan_schedule` setting
|
||||
2. Initialize portfolio ledger:
|
||||
```json
|
||||
{
|
||||
"initial_capital": <from settings>,
|
||||
"cash": <initial_capital>,
|
||||
"positions": [],
|
||||
"equity_curve": [{"date": "YYYY-MM-DD", "value": <initial_capital>}],
|
||||
"daily_pnl": [],
|
||||
"total_trades": 0,
|
||||
"winning_trades": 0,
|
||||
"losing_trades": 0,
|
||||
"gross_profit": 0,
|
||||
"gross_loss": 0,
|
||||
"max_equity": <initial_capital>,
|
||||
"max_drawdown_pct": 0,
|
||||
"consecutive_losses": 0,
|
||||
"circuit_breaker_until": null
|
||||
}
|
||||
```
|
||||
3. Parse watchlist from settings (comma-separated tickers)
|
||||
4. Determine market focus and adjust data sources accordingly
|
||||
5. Initialize trade journal as empty array
|
||||
|
||||
### Subsequent Runs
|
||||
1. Load portfolio from `portfolio.json`
|
||||
2. Load trade journal from `trade_journal.json`
|
||||
3. Update current prices for all open positions
|
||||
4. Check if circuit breaker is active — if so, skip to Phase 7 (reports only)
|
||||
5. Check if max drawdown threshold exceeded — if so, trigger emergency risk protocol
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Market Intelligence Scan
|
||||
|
||||
Execute targeted searches for each watchlist asset. Adjust depth based on `analysis_depth` setting.
|
||||
|
||||
### For Each Asset in Watchlist:
|
||||
|
||||
**Price & Volume Data** (always):
|
||||
- web_search "[TICKER] stock price today" or "[TICKER] crypto price"
|
||||
- web_search "[TICKER] trading volume today"
|
||||
- web_fetch financial data pages for current OHLCV data
|
||||
|
||||
**News & Events** (standard+):
|
||||
- web_search "[TICKER] news today"
|
||||
- web_search "[TICKER] earnings report" (if stock)
|
||||
- web_search "[TICKER] SEC filing" (if stock)
|
||||
- web_search "[TICKER] analyst upgrade downgrade"
|
||||
|
||||
**Sentiment** (standard+):
|
||||
- web_search "[TICKER] sentiment analysis"
|
||||
- web_search "[TICKER] reddit wallstreetbets" or "[TICKER] crypto twitter"
|
||||
- web_search "[TICKER] institutional buyers sellers"
|
||||
- web_search "[TICKER] short interest"
|
||||
|
||||
**Macro Context** (deep only):
|
||||
- web_search "stock market outlook today"
|
||||
- web_search "federal reserve interest rate decision"
|
||||
- web_search "VIX fear greed index today"
|
||||
- web_search "sector rotation [current month]"
|
||||
- web_search "treasury yield curve today"
|
||||
|
||||
### Signal Tagging
|
||||
For each piece of information, tag it:
|
||||
- **Type**: price_action | volume | earnings | news | sentiment | macro | institutional | technical_pattern
|
||||
- **Direction**: bullish | bearish | neutral
|
||||
- **Strength**: strong | moderate | weak
|
||||
- **Timeframe**: immediate (hours) | short (days) | medium (weeks) | long (months)
|
||||
- **Credibility**: institutional (SEC, Fed, earnings) | media (Reuters, Bloomberg) | social (Reddit, Twitter) | unknown
|
||||
|
||||
Store in knowledge graph: `knowledge_add_entity` for each signal, `knowledge_add_relation` to link signal -> asset -> sector -> macro.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Multi-Factor Analysis Engine
|
||||
|
||||
For each asset in watchlist, compute a structured analysis:
|
||||
|
||||
### 3A — Technical Analysis Score
|
||||
|
||||
Using the price/volume data gathered, assess:
|
||||
|
||||
| Indicator | Method | Bullish | Bearish |
|
||||
|-----------|--------|---------|---------|
|
||||
| **Trend** | Price vs 50-day & 200-day MA | Above both | Below both |
|
||||
| **Momentum** | RSI(14) | 30-50 (oversold bounce) | 70-90 (overbought) |
|
||||
| **MACD** | MACD line vs Signal line | Bullish crossover | Bearish crossover |
|
||||
| **Bollinger** | Price vs Bands(20,2) | Touch lower band + reversal | Touch upper band + reversal |
|
||||
| **Volume** | Current vs 20-day average | Rising on up moves | Rising on down moves |
|
||||
| **Support/Resistance** | Key price levels | Bouncing off support | Rejected at resistance |
|
||||
| **ATR** | Average True Range(14) | Expanding (trending) | Contracting (ranging) |
|
||||
|
||||
**Technical Score**: -100 to +100 (sum of weighted indicator scores)
|
||||
|
||||
### 3B — Fundamental Analysis Score (stocks only)
|
||||
|
||||
| Factor | Bullish | Bearish |
|
||||
|--------|---------|---------|
|
||||
| **P/E vs Sector** | Below sector average | Way above sector average |
|
||||
| **Revenue Growth** | Accelerating QoQ | Decelerating QoQ |
|
||||
| **Earnings Surprise** | Beat estimates | Missed estimates |
|
||||
| **Analyst Consensus** | Upgrades > downgrades | Downgrades > upgrades |
|
||||
| **Insider Activity** | Net buying | Net selling |
|
||||
| **Institutional Flow** | Increasing ownership | Decreasing ownership |
|
||||
| **Debt/Equity** | Improving | Deteriorating |
|
||||
|
||||
**Fundamental Score**: -100 to +100
|
||||
|
||||
### 3C — Sentiment Analysis Score
|
||||
|
||||
| Factor | Bullish | Bearish |
|
||||
|--------|---------|---------|
|
||||
| **News Sentiment** | Mostly positive | Mostly negative |
|
||||
| **Social Buzz** | Rising mentions + positive | Rising mentions + negative |
|
||||
| **Fear & Greed** | Extreme fear (contrarian buy) | Extreme greed (contrarian sell) |
|
||||
| **Put/Call Ratio** | High (contrarian bullish) | Low (contrarian bearish) |
|
||||
| **Short Interest** | Declining | Increasing rapidly |
|
||||
| **VIX Level** | Below 20 (calm) | Above 30 (panic) |
|
||||
|
||||
**Sentiment Score**: -100 to +100
|
||||
|
||||
### 3D — Macro Analysis Score
|
||||
|
||||
| Factor | Risk-On (Bullish) | Risk-Off (Bearish) |
|
||||
|--------|-------------------|-------------------|
|
||||
| **Fed Policy** | Dovish / cutting rates | Hawkish / raising rates |
|
||||
| **Yield Curve** | Steepening | Inverting |
|
||||
| **Dollar Strength** | Weakening USD | Strengthening USD |
|
||||
| **Sector Rotation** | Into growth/tech | Into defensives/utilities |
|
||||
| **Global Events** | Stability | Geopolitical tension |
|
||||
|
||||
**Macro Score**: -100 to +100
|
||||
|
||||
### Composite Signal Matrix
|
||||
```
|
||||
Asset: [TICKER]
|
||||
Technical: [score] / 100 [............]
|
||||
Fundamental: [score] / 100 [............]
|
||||
Sentiment: [score] / 100 [............]
|
||||
Macro: [score] / 100 [............]
|
||||
---------------------------------------------
|
||||
COMPOSITE: [weighted avg] / 100
|
||||
```
|
||||
|
||||
Weight by strategy_style:
|
||||
- Scalping: Technical 60%, Sentiment 25%, Macro 10%, Fundamental 5%
|
||||
- Day Trading: Technical 50%, Sentiment 25%, Macro 15%, Fundamental 10%
|
||||
- Swing: Technical 35%, Fundamental 25%, Sentiment 20%, Macro 20%
|
||||
- Position: Fundamental 40%, Macro 25%, Technical 20%, Sentiment 15%
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Signal Fusion: Adversarial Bull/Bear Debate
|
||||
|
||||
THIS IS YOUR MOST IMPORTANT PHASE. For each asset with composite score outside -20 to +20 range (i.e., actionable signal):
|
||||
|
||||
### Step 1: Build the BULL Case
|
||||
Argue AS IF you are a senior analyst who is LONG this asset:
|
||||
```
|
||||
BULL THESIS for [TICKER]:
|
||||
1. Technical: [strongest bullish technical signals]
|
||||
2. Catalyst: [upcoming catalysts that could drive price up]
|
||||
3. Sentiment: [positive sentiment indicators]
|
||||
4. Macro: [favorable macro conditions]
|
||||
5. Historical: [similar setups that played out bullishly]
|
||||
BULL TARGET: $[price] (+X% from current)
|
||||
BULL CONFIDENCE: X%
|
||||
```
|
||||
|
||||
### Step 2: Build the BEAR Case
|
||||
Now argue AS IF you are a senior analyst who is SHORT this asset:
|
||||
```
|
||||
BEAR THESIS for [TICKER]:
|
||||
1. Technical: [strongest bearish technical signals]
|
||||
2. Risk: [what could go wrong — earnings miss, macro shock, etc.]
|
||||
3. Sentiment: [negative sentiment indicators]
|
||||
4. Macro: [unfavorable macro conditions]
|
||||
5. Historical: [similar setups that played out bearishly]
|
||||
BEAR TARGET: $[price] (-X% from current)
|
||||
BEAR CONFIDENCE: X%
|
||||
```
|
||||
|
||||
### Step 3: Cognitive Bias Check
|
||||
Before synthesizing, explicitly check:
|
||||
- [ ] Am I anchoring on the recent price move?
|
||||
- [ ] Am I falling for narrative bias (compelling story != likely outcome)?
|
||||
- [ ] Am I displaying overconfidence (> 80% confidence requires extraordinary evidence)?
|
||||
- [ ] Am I neglecting the base rate? (Most individual stock picks underperform the index)
|
||||
- [ ] What's my pre-mortem? If this trade fails, what was the most likely reason?
|
||||
|
||||
### Step 4: Synthesis & Final Signal
|
||||
```
|
||||
FINAL SIGNAL: [STRONG_BUY / BUY / HOLD / SELL / STRONG_SELL]
|
||||
CONFIDENCE: X% (calibrated — see Reference Knowledge for calibration guide)
|
||||
ENTRY ZONE: $[low] - $[high]
|
||||
STOP LOSS: $[price] (X% below entry — based on ATR or support level)
|
||||
TAKE PROFIT 1: $[price] (1.5:1 risk/reward — take 50% off)
|
||||
TAKE PROFIT 2: $[price] (3:1 risk/reward — trailing stop for remainder)
|
||||
RISK/REWARD: X:1
|
||||
TIMEFRAME: [hours / days / weeks]
|
||||
REASONING: [2-3 sentence synthesis of why bull > bear or vice versa]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Risk Management Gate (HARD LIMITS — CANNOT BE BYPASSED)
|
||||
|
||||
EVERY trade proposal MUST pass ALL checks below. NO exceptions. NO overrides.
|
||||
|
||||
### 5A — Position-Level Checks
|
||||
1. **Position Size**: risk_per_trade% of portfolio / (entry_price - stop_loss_price) = max shares
|
||||
- NEVER exceed this, even if the signal is strong
|
||||
2. **Stop Loss**: MUST be set before entry — no trade without a stop
|
||||
3. **Risk/Reward**: Must be >= 1.5:1 — reject trades with poor R:R
|
||||
4. **Single Position Cap**: No position > 10% of total portfolio value
|
||||
5. **Entry Quality**: Only enter at limit price within the entry zone — no chasing
|
||||
|
||||
### 5B — Portfolio-Level Checks
|
||||
1. **Cash Reserve**: Always maintain >= 20% cash (max 80% invested)
|
||||
2. **Sector Concentration**: Max 3 positions in the same sector
|
||||
3. **Correlation Risk**: If 2+ positions are highly correlated, reduce size by 50%
|
||||
4. **Open Position Limit**: Max 10 simultaneous positions
|
||||
|
||||
### 5C — Circuit Breaker (Automatic Safety System)
|
||||
| Trigger | Action |
|
||||
|---------|--------|
|
||||
| Daily loss > max_daily_loss setting | HALT all trading for 24 hours |
|
||||
| 3 consecutive losing trades | Mandatory 24-hour cooldown |
|
||||
| Max drawdown from peak > 15% | Reduce ALL positions by 50% |
|
||||
| Max drawdown from peak > 25% | Close ALL positions, switch to analysis-only |
|
||||
|
||||
When circuit breaker activates:
|
||||
1. Log the trigger and timestamp
|
||||
2. memory_store `trader_hand_circuit_breaker` with expiry timestamp
|
||||
3. event_publish alert to user: "Circuit breaker activated: [reason]"
|
||||
4. Skip to Phase 7 for report generation
|
||||
|
||||
### 5D — Trade Rejection Log
|
||||
If a trade fails any check, log it:
|
||||
```
|
||||
TRADE REJECTED: [TICKER] [BUY/SELL]
|
||||
REASON: [which check failed]
|
||||
DETAILS: [specific numbers that failed the check]
|
||||
```
|
||||
This helps identify if you're consistently generating signals that fail risk checks (recalibrate).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Trade Execution
|
||||
|
||||
Read trading_mode from User Configuration:
|
||||
|
||||
### Mode: "analysis" (Analysis Only)
|
||||
- Generate signal report with all analysis from Phases 2-5
|
||||
- Record what you WOULD have done in `shadow_trades.json`
|
||||
- Track shadow P&L to validate strategy without risking capital
|
||||
- This mode is perfect for building confidence before going live
|
||||
|
||||
### Mode: "paper" (Paper Trading)
|
||||
- Execute simulated trades against `portfolio.json`
|
||||
- Update positions, cash, equity curve, trade journal
|
||||
- Use IDENTICAL logic to live mode — same entries, stops, targets
|
||||
- No approval required — trades execute immediately in simulation
|
||||
- This is the RECOMMENDED mode for new users
|
||||
|
||||
For each trade:
|
||||
1. Deduct from cash, add to positions array
|
||||
2. Set stop_loss and take_profit levels
|
||||
3. Log in trade_journal.json with full reasoning
|
||||
4. Update equity curve
|
||||
|
||||
For position management each cycle:
|
||||
1. Check all open positions against current prices
|
||||
2. If price hit stop_loss -> close position, record loss
|
||||
3. If price hit take_profit_1 -> close 50%, move stop to breakeven
|
||||
4. If price hit take_profit_2 -> close remaining
|
||||
5. Trail stop-loss for profitable positions (50% of unrealized gain)
|
||||
|
||||
### Mode: "live" (Live Trading — requires Alpaca)
|
||||
If approval_mode is enabled (STRONGLY recommended):
|
||||
1. Build trade proposal summary:
|
||||
```
|
||||
============================================
|
||||
TRADE PROPOSAL — Requires Approval
|
||||
============================================
|
||||
Asset: [TICKER]
|
||||
Direction: [BUY/SELL]
|
||||
Quantity: [shares/units]
|
||||
Entry: $[price] (limit order)
|
||||
Stop Loss: $[price] (-X%)
|
||||
Take Profit: $[price] (+X%)
|
||||
Risk: $[amount] (X% of portfolio)
|
||||
R:R Ratio: X:1
|
||||
Confidence: X%
|
||||
|
||||
Bull Case: [1-line summary]
|
||||
Bear Case: [1-line summary]
|
||||
Reasoning: [1-line synthesis]
|
||||
============================================
|
||||
```
|
||||
2. event_publish the proposal as an alert
|
||||
3. STOP and wait for user response
|
||||
4. On approval: execute via Alpaca API (see SKILL.md for API reference)
|
||||
5. On rejection: log rejection, do not trade
|
||||
|
||||
If approval_mode is disabled:
|
||||
1. Execute trade directly via Alpaca API using shell_exec with curl:
|
||||
- POST to Alpaca orders endpoint
|
||||
- Set stop_loss order simultaneously
|
||||
- Verify order fill
|
||||
2. Log everything with full reasoning chain
|
||||
|
||||
### Order Types (for live trading)
|
||||
- Entry: LIMIT order at target price (never market orders in volatile markets)
|
||||
- Stop Loss: STOP order (guaranteed execution)
|
||||
- Take Profit: LIMIT order
|
||||
- Trailing Stop: TRAILING_STOP order (percentage-based)
|
||||
|
||||
---
|
||||
|
||||
## Phase 7 — Analytics, Report Generation & State Persistence
|
||||
|
||||
### 7A — Portfolio Analytics Calculations
|
||||
|
||||
Calculate and update these metrics every cycle:
|
||||
|
||||
**Win Rate** = winning_trades / total_trades * 100
|
||||
**Profit Factor** = gross_profit / abs(gross_loss) — target > 1.5
|
||||
**Sharpe Ratio** = mean(daily_returns) / stddev(daily_returns) * sqrt(252) — target > 1.0
|
||||
**Max Drawdown** = (peak_equity - trough_equity) / peak_equity * 100
|
||||
**Average Win** = gross_profit / winning_trades
|
||||
**Average Loss** = abs(gross_loss) / losing_trades
|
||||
**Expectancy** = (win_rate * avg_win) - ((1 - win_rate) * avg_loss)
|
||||
**Risk-Adjusted Return** = total_return / max_drawdown
|
||||
|
||||
### 7B — Generate Trading Report
|
||||
|
||||
```markdown
|
||||
# Trading Report — YYYY-MM-DD HH:MM
|
||||
|
||||
## Portfolio Snapshot
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Portfolio Value | $XX,XXX.XX |
|
||||
| Cash | $XX,XXX.XX (XX%) |
|
||||
| Invested | $XX,XXX.XX (XX%) |
|
||||
| Daily P&L | +/-$X,XXX.XX (+/-X.XX%) |
|
||||
| Total P&L | +/-$X,XXX.XX (+/-X.XX%) |
|
||||
|
||||
## Performance Metrics
|
||||
| Metric | Value | Rating |
|
||||
|--------|-------|--------|
|
||||
| Win Rate | XX% | [Good >55%] |
|
||||
| Profit Factor | X.XX | [Good >1.5] |
|
||||
| Sharpe Ratio | X.XX | [Good >1.0] |
|
||||
| Max Drawdown | X.XX% | [Caution >10%] |
|
||||
| Expectancy | $XX.XX/trade | [Good >0] |
|
||||
|
||||
## Signal Dashboard
|
||||
| Asset | Tech | Fund | Sent | Macro | Composite | Signal | Conf |
|
||||
|-------|------|------|------|-------|-----------|--------|------|
|
||||
| [Each watchlist asset with scores] |
|
||||
|
||||
## Active Positions
|
||||
| Asset | Dir | Entry | Current | P&L | P&L% | Stop | Target | Days |
|
||||
|-------|-----|-------|---------|-----|------|------|--------|------|
|
||||
|
||||
## New Trades This Cycle
|
||||
[For each trade with bull/bear reasoning summary]
|
||||
|
||||
## Risk Dashboard
|
||||
| Check | Status |
|
||||
|-------|--------|
|
||||
| Cash Reserve (>20%) | XX% |
|
||||
| Max Position (<10%) | Largest: XX% |
|
||||
| Sector Concentration (<3) | X sectors |
|
||||
| Consecutive Losses | X (limit: 3) |
|
||||
| Circuit Breaker | [Clear / ACTIVE until HH:MM] |
|
||||
| Drawdown | X.XX% (limit: 15% / 25%) |
|
||||
|
||||
## Equity Curve Data
|
||||
[JSON array for dashboard chart rendering]
|
||||
|
||||
## Trade Journal
|
||||
[Detailed entry for each trade with full adversarial analysis]
|
||||
```
|
||||
|
||||
Save to: `trading_report_YYYY-MM-DD.md`
|
||||
|
||||
### 7C — State Persistence
|
||||
|
||||
1. Save portfolio to `portfolio.json` (positions, cash, equity curve, all metrics)
|
||||
2. Save trade journal to `trade_journal.json` (append new trades)
|
||||
3. Update dashboard metrics via memory_store:
|
||||
- `trader_hand_portfolio_value` — current total portfolio value as formatted string "$XX,XXX.XX"
|
||||
- `trader_hand_total_pnl` — total P&L as formatted string "+$X,XXX.XX" or "-$X,XXX.XX"
|
||||
- `trader_hand_win_rate` — percentage number (e.g., 62.5)
|
||||
- `trader_hand_sharpe_ratio` — decimal number (e.g., 1.45)
|
||||
- `trader_hand_max_drawdown` — percentage number (e.g., 8.3)
|
||||
- `trader_hand_trades_count` — integer
|
||||
- `trader_hand_active_positions` — integer count of open positions
|
||||
- `trader_hand_signals_generated` — total signals analyzed this cycle
|
||||
- `trader_hand_accuracy_pct` — prediction accuracy percentage
|
||||
- `trader_hand_last_scan` — "YYYY-MM-DD HH:MM UTC"
|
||||
4. Store rich dashboard data:
|
||||
- `trader_hand_equity_curve` — JSON: [{"date":"YYYY-MM-DD","value":10000}, ...]
|
||||
- `trader_hand_daily_pnl` — JSON: [{"date":"YYYY-MM-DD","pnl":125.50}, ...]
|
||||
- `trader_hand_watchlist_heatmap` — JSON: [{"ticker":"AAPL","change_pct":2.3,"signal":"BUY","confidence":72}, ...]
|
||||
- `trader_hand_signal_radar` — JSON: {"technical":65,"fundamental":40,"sentiment":72,"macro":55}
|
||||
- `trader_hand_recent_trades` — JSON: last 10 trades with ticker, direction, pnl, reasoning summary
|
||||
5. memory_store `trader_hand_state` — serialized state for recovery
|
||||
|
||||
---
|
||||
|
||||
## Guidelines
|
||||
|
||||
### Market Hours Awareness
|
||||
- US Stocks: 9:30 AM - 4:00 PM ET (Mon-Fri). Pre-market 4:00 AM - 9:30 AM. After-hours 4:00 PM - 8:00 PM.
|
||||
- Crypto: 24/7/365
|
||||
- Respect market hours — don't try to execute stock trades when market is closed (queue for next open)
|
||||
|
||||
### Data Quality Rules
|
||||
- NEVER fabricate price data — if you can't find current prices, say so
|
||||
- Cross-reference prices from 2+ sources when possible
|
||||
- If data is stale (> 15 minutes for day trading, > 1 hour for swing), note it
|
||||
- Prefer financial data sites (Yahoo Finance, Google Finance, CoinGecko) over news articles for price data
|
||||
|
||||
### Trading Discipline
|
||||
- NEVER average down on a losing position (adding to losers is how accounts blow up)
|
||||
- NEVER remove or widen a stop loss after it's set
|
||||
- NEVER risk more than the position sizing formula allows — no matter how confident you are
|
||||
- NEVER chase a missed entry — wait for the next setup
|
||||
- If a trade thesis is invalidated before entry, cancel the order
|
||||
- Respect the circuit breaker — it exists to protect the portfolio from emotional decisions
|
||||
|
||||
### Communication
|
||||
- If the user messages you directly, pause autonomous operations and respond
|
||||
- Explain your reasoning clearly — the user should understand WHY you're making each decision
|
||||
- Flag high-risk situations proactively (earnings approaching, Fed meeting, unusual volatility)
|
||||
- When uncertain, default to HOLD — no trade is better than a bad trade
|
||||
|
||||
### Accuracy Tracking
|
||||
- Track every signal's outcome: did the predicted direction play out?
|
||||
- Calculate rolling accuracy per signal type (technical accuracy, sentiment accuracy, etc.)
|
||||
- Adjust signal weights over time based on what's actually working
|
||||
- Be honest about failures — log bad trades with the SAME detail as good ones
|
||||
"""
|
||||
|
||||
# ─── Dashboard metrics ────────────────────────────────────────────────────────
|
||||
|
||||
[dashboard]
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Portfolio Value"
|
||||
memory_key = "trader_hand_portfolio_value"
|
||||
format = "text"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Total P&L"
|
||||
memory_key = "trader_hand_total_pnl"
|
||||
format = "text"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Win Rate"
|
||||
memory_key = "trader_hand_win_rate"
|
||||
format = "percentage"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Sharpe Ratio"
|
||||
memory_key = "trader_hand_sharpe_ratio"
|
||||
format = "number"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Max Drawdown"
|
||||
memory_key = "trader_hand_max_drawdown"
|
||||
format = "percentage"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Trades Executed"
|
||||
memory_key = "trader_hand_trades_count"
|
||||
format = "number"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Active Positions"
|
||||
memory_key = "trader_hand_active_positions"
|
||||
format = "number"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Signals Analyzed"
|
||||
memory_key = "trader_hand_signals_generated"
|
||||
format = "number"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Accuracy"
|
||||
memory_key = "trader_hand_accuracy_pct"
|
||||
format = "percentage"
|
||||
|
||||
[[dashboard.metrics]]
|
||||
label = "Last Scan"
|
||||
memory_key = "trader_hand_last_scan"
|
||||
format = "text"
|
||||
|
||||
# ─── Token & Performance Metadata ─────────────────────────────────────────────
|
||||
# This metadata helps users understand resource consumption before activation.
|
||||
|
||||
[metadata]
|
||||
# How often the hand runs in continuous mode (60s loop when active)
|
||||
frequency = "continuous"
|
||||
# Relative token consumption: low, medium, high (based on typical usage)
|
||||
token_consumption = "high"
|
||||
# Whether this hand is included in default activation on first boot
|
||||
default_active = false
|
||||
# Warning shown when user tries to activate
|
||||
activation_warning = "Trading hand runs continuously and consumes tokens. Deactivate when not trading."
|
||||
@@ -0,0 +1,937 @@
|
||||
---
|
||||
name: trader-hand-skill
|
||||
version: "1.0.0"
|
||||
description: "Expert knowledge for autonomous market intelligence and trading — technical analysis, risk management, Alpaca API, financial data sources"
|
||||
author: LibreFang
|
||||
tags: [trading, finance, stocks, crypto, technical-analysis, risk-management]
|
||||
tools: [shell_exec, file_read, file_write, web_fetch, web_search, memory_store]
|
||||
runtime: prompt_only
|
||||
---
|
||||
|
||||
# Trading Expert Knowledge
|
||||
|
||||
## Reference Knowledge
|
||||
|
||||
## 1. Technical Analysis Indicators Reference
|
||||
|
||||
### RSI (Relative Strength Index)
|
||||
```
|
||||
Formula: RSI = 100 - (100 / (1 + RS))
|
||||
Where: RS = Average Gain / Average Loss over N periods (default N = 14)
|
||||
|
||||
Step-by-step calculation:
|
||||
1. For each period, compute change = Close(t) - Close(t-1)
|
||||
2. Gains = max(change, 0), Losses = abs(min(change, 0))
|
||||
3. First average: simple mean of first 14 gains/losses
|
||||
4. Subsequent: AvgGain = (PrevAvgGain * 13 + CurrentGain) / 14 (Wilder smoothing)
|
||||
5. RS = AvgGain / AvgLoss
|
||||
6. RSI = 100 - (100 / (1 + RS))
|
||||
|
||||
Worked example (14-period):
|
||||
Avg Gain over 14 periods = 1.02
|
||||
Avg Loss over 14 periods = 0.68
|
||||
RS = 1.02 / 0.68 = 1.50
|
||||
RSI = 100 - (100 / (1 + 1.50)) = 100 - 40 = 60.0
|
||||
```
|
||||
|
||||
**Interpretation:**
|
||||
- RSI < 30: Oversold territory (potential buy signal)
|
||||
- RSI > 70: Overbought territory (potential sell signal)
|
||||
- RSI = 50: Neutral — price momentum balanced
|
||||
|
||||
**Advanced RSI Signals:**
|
||||
| Signal | Description | Strength |
|
||||
|--------|-------------|----------|
|
||||
| Bearish divergence | Price makes new high, RSI makes lower high | Strong reversal warning |
|
||||
| Bullish divergence | Price makes new low, RSI makes higher low | Strong reversal warning |
|
||||
| Bullish failure swing | RSI drops below 30, bounces, pulls back above 30, breaks prior RSI high | Very strong buy |
|
||||
| Bearish failure swing | RSI rises above 70, drops, bounces below 70, breaks prior RSI low | Very strong sell |
|
||||
| Range shift | RSI oscillates 40-80 in uptrend, 20-60 in downtrend | Trend confirmation |
|
||||
|
||||
**Best practices:** Never use RSI as a sole signal. Combine with trend direction (moving averages) and volume. In strong trends, RSI can stay overbought/oversold for extended periods.
|
||||
|
||||
---
|
||||
|
||||
### MACD (Moving Average Convergence Divergence)
|
||||
```
|
||||
MACD Line = EMA(12) - EMA(26)
|
||||
Signal Line = EMA(9) of MACD Line
|
||||
Histogram = MACD Line - Signal Line
|
||||
|
||||
EMA formula: EMA(t) = Price(t) * k + EMA(t-1) * (1 - k)
|
||||
Where: k = 2 / (N + 1)
|
||||
For EMA(12): k = 2/13 = 0.1538
|
||||
For EMA(26): k = 2/27 = 0.0741
|
||||
|
||||
Worked example:
|
||||
EMA(12) = 155.20
|
||||
EMA(26) = 152.80
|
||||
MACD Line = 155.20 - 152.80 = 2.40
|
||||
Previous Signal Line = 1.80
|
||||
Signal Line = 2.40 * (2/10) + 1.80 * (8/10) = 0.48 + 1.44 = 1.92
|
||||
Histogram = 2.40 - 1.92 = 0.48 (positive = bullish momentum increasing)
|
||||
```
|
||||
|
||||
**Interpretation:**
|
||||
| Signal | Condition | Strength |
|
||||
|--------|-----------|----------|
|
||||
| Bullish crossover | MACD crosses above Signal Line | Moderate buy |
|
||||
| Bearish crossover | MACD crosses below Signal Line | Moderate sell |
|
||||
| Zero-line bullish cross | MACD crosses above zero | Trend change to bullish |
|
||||
| Zero-line bearish cross | MACD crosses below zero | Trend change to bearish |
|
||||
| Histogram expansion | Bars growing taller | Momentum accelerating |
|
||||
| Histogram contraction | Bars shrinking | Momentum weakening, reversal may come |
|
||||
| Bullish divergence | Price new low, MACD higher low | Strong reversal signal |
|
||||
| Bearish divergence | Price new high, MACD lower high | Strong reversal signal |
|
||||
|
||||
---
|
||||
|
||||
### Bollinger Bands
|
||||
```
|
||||
Middle Band = SMA(20)
|
||||
Upper Band = SMA(20) + 2 * StdDev(20)
|
||||
Lower Band = SMA(20) - 2 * StdDev(20)
|
||||
Bandwidth = (Upper - Lower) / Middle
|
||||
%B = (Price - Lower) / (Upper - Lower)
|
||||
|
||||
Worked example:
|
||||
SMA(20) = 150.00
|
||||
StdDev(20) = 3.50
|
||||
Upper = 150.00 + 2 * 3.50 = 157.00
|
||||
Lower = 150.00 - 2 * 3.50 = 143.00
|
||||
Bandwidth = (157.00 - 143.00) / 150.00 = 0.0933 (9.33%)
|
||||
Current price = 155.00
|
||||
%B = (155.00 - 143.00) / (157.00 - 143.00) = 12/14 = 0.857
|
||||
Interpretation: Price is 85.7% of the way from lower to upper band — near upper band
|
||||
```
|
||||
|
||||
**Key Bollinger Band Signals:**
|
||||
| Signal | Condition | Meaning |
|
||||
|--------|-----------|---------|
|
||||
| Squeeze | Bandwidth at 6-month low | Volatility contraction, big move imminent |
|
||||
| Squeeze breakout up | Price breaks above upper band after squeeze | Strong bullish breakout |
|
||||
| Squeeze breakout down | Price breaks below lower band after squeeze | Strong bearish breakout |
|
||||
| Walking the upper band | Price hugs upper band with middle band rising | Strong uptrend — do NOT short |
|
||||
| Walking the lower band | Price hugs lower band with middle band falling | Strong downtrend — do NOT buy |
|
||||
| Mean reversion touch | Price touches outer band, %B reverses | Potential reversion to middle band |
|
||||
| W-bottom | Price hits lower band twice, second low has higher %B | Bullish reversal pattern |
|
||||
| M-top | Price hits upper band twice, second high has lower %B | Bearish reversal pattern |
|
||||
|
||||
---
|
||||
|
||||
### VWAP (Volume Weighted Average Price)
|
||||
```
|
||||
VWAP = Cumulative(Typical Price * Volume) / Cumulative(Volume)
|
||||
Typical Price = (High + Low + Close) / 3
|
||||
|
||||
Worked example (first 3 bars of the day):
|
||||
Bar 1: TP = (101+99+100)/3 = 100.00, Vol = 10,000 -> cumTP*V = 1,000,000
|
||||
Bar 2: TP = (102+100+101)/3 = 101.00, Vol = 15,000 -> cumTP*V = 2,515,000
|
||||
Bar 3: TP = (103+101+102)/3 = 102.00, Vol = 8,000 -> cumTP*V = 3,331,000
|
||||
Cumulative Volume = 33,000
|
||||
VWAP = 3,331,000 / 33,000 = 100.94
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
- **Institutional benchmark**: If price > VWAP, buyers dominate; price < VWAP, sellers dominate
|
||||
- **Intraday S/R**: VWAP acts as dynamic support in uptrends, resistance in downtrends
|
||||
- **Entry filter**: Buy only when price pulls back to VWAP (not chasing extended moves)
|
||||
- **Standard deviations**: VWAP +1/-1 and +2/-2 StdDev bands serve as profit targets
|
||||
- **Resets daily**: Do NOT carry VWAP across sessions — it is an intraday metric
|
||||
|
||||
---
|
||||
|
||||
### Moving Averages
|
||||
```
|
||||
SMA(N) = (Close_1 + Close_2 + ... + Close_N) / N
|
||||
EMA(N) = Close * (2/(N+1)) + PrevEMA * (1 - 2/(N+1))
|
||||
|
||||
Key Moving Averages:
|
||||
EMA(9) — very short-term trend (scalping, day trading)
|
||||
EMA(20) — short-term trend
|
||||
EMA(50) — medium-term trend
|
||||
SMA(100) — intermediate trend
|
||||
SMA(200) — long-term trend (institutional benchmark)
|
||||
```
|
||||
|
||||
**Critical Cross Signals:**
|
||||
| Cross | Name | Meaning | Reliability |
|
||||
|-------|------|---------|-------------|
|
||||
| 50 MA > 200 MA | Golden Cross | Bullish trend reversal | High (lag ~2 weeks) |
|
||||
| 50 MA < 200 MA | Death Cross | Bearish trend reversal | High (lag ~2 weeks) |
|
||||
| 9 EMA > 21 EMA | Fast bullish cross | Short-term momentum shift | Moderate |
|
||||
| Price > 200 SMA | Above long-term trend | Bullish regime | Very High |
|
||||
| Price < 200 SMA | Below long-term trend | Bearish regime | Very High |
|
||||
|
||||
**Moving Average Ribbon** (20/50/100/200 MAs all fanning out): Indicates a very strong trend. When all are stacked in order (20 > 50 > 100 > 200 for uptrend), the trend is highly reliable.
|
||||
|
||||
---
|
||||
|
||||
### ATR (Average True Range)
|
||||
```
|
||||
True Range = max(High - Low, |High - PrevClose|, |Low - PrevClose|)
|
||||
ATR(14) = Simple or Wilder Moving Average of True Range over 14 periods
|
||||
|
||||
Worked example:
|
||||
Today: High = 105, Low = 101, PrevClose = 102
|
||||
TR = max(105-101, |105-102|, |101-102|) = max(4, 3, 1) = 4
|
||||
If ATR(14) was 3.50 yesterday:
|
||||
ATR(14) = (3.50 * 13 + 4) / 14 = (45.50 + 4) / 14 = 3.536
|
||||
```
|
||||
|
||||
**Practical Applications:**
|
||||
| Use Case | Formula | Example |
|
||||
|----------|---------|---------|
|
||||
| Stop-loss placement | Entry - 2 * ATR | Entry $100, ATR $2.50 -> Stop at $95.00 |
|
||||
| Take-profit target | Entry + 3 * ATR | Entry $100, ATR $2.50 -> Target $107.50 |
|
||||
| Position sizing | Risk$ / ATR | $200 risk / $2.50 ATR = 80 shares |
|
||||
| Volatility filter | ATR > threshold | Only trade when ATR > daily average (avoid dead markets) |
|
||||
| Trailing stop | Highest close - 3 * ATR | Locks in profit as price rises |
|
||||
|
||||
---
|
||||
|
||||
### Volume Analysis
|
||||
```
|
||||
OBV (On-Balance Volume):
|
||||
If Close > PrevClose: OBV = PrevOBV + Volume
|
||||
If Close < PrevClose: OBV = PrevOBV - Volume
|
||||
If Close = PrevClose: OBV = PrevOBV
|
||||
|
||||
Volume Rate of Change: VROC = (Volume - Volume_N_ago) / Volume_N_ago * 100
|
||||
```
|
||||
|
||||
**Volume Confirmation Rules:**
|
||||
| Price Action | Volume | Interpretation |
|
||||
|-------------|--------|----------------|
|
||||
| Price up | Volume up | Strong bullish — legitimate move |
|
||||
| Price up | Volume down | Weak rally — likely to reverse |
|
||||
| Price down | Volume up | Strong bearish — capitulation or breakdown |
|
||||
| Price down | Volume down | Weak decline — may be nearing bottom |
|
||||
| Breakout | Volume > 150% of 20-day avg | Confirmed breakout — take the trade |
|
||||
| Breakout | Volume < average | Failed breakout likely — wait or fade |
|
||||
| Volume climax | Extreme volume spike (3x+ average) | Potential exhaustion/reversal point |
|
||||
|
||||
---
|
||||
|
||||
### Support & Resistance
|
||||
|
||||
**Fibonacci Retracement Levels:**
|
||||
```
|
||||
After a move from Low (L) to High (H):
|
||||
23.6% level = H - (H - L) * 0.236
|
||||
38.2% level = H - (H - L) * 0.382
|
||||
50.0% level = H - (H - L) * 0.500
|
||||
61.8% level = H - (H - L) * 0.618 (Golden Ratio — strongest level)
|
||||
78.6% level = H - (H - L) * 0.786
|
||||
|
||||
Worked example (move from $80 to $120):
|
||||
Range = $40
|
||||
23.6% = 120 - 40 * 0.236 = 120 - 9.44 = $110.56
|
||||
38.2% = 120 - 40 * 0.382 = 120 - 15.28 = $104.72
|
||||
50.0% = 120 - 40 * 0.500 = 120 - 20.00 = $100.00
|
||||
61.8% = 120 - 40 * 0.618 = 120 - 24.72 = $95.28 (most likely bounce)
|
||||
78.6% = 120 - 40 * 0.786 = 120 - 31.44 = $88.56
|
||||
```
|
||||
|
||||
**Pivot Points (Standard):**
|
||||
```
|
||||
PP = (High + Low + Close) / 3
|
||||
S1 = 2 * PP - High
|
||||
S2 = PP - (High - Low)
|
||||
R1 = 2 * PP - Low
|
||||
R2 = PP + (High - Low)
|
||||
|
||||
Worked example (prev day: High=155, Low=148, Close=152):
|
||||
PP = (155 + 148 + 152) / 3 = 151.67
|
||||
S1 = 2 * 151.67 - 155 = 148.33
|
||||
S2 = 151.67 - (155 - 148) = 144.67
|
||||
R1 = 2 * 151.67 - 148 = 155.33
|
||||
R2 = 151.67 + (155 - 148) = 158.67
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Candlestick Patterns
|
||||
|
||||
### Single-Candle Patterns
|
||||
| Pattern | Signal | Body | Wicks | Context Required |
|
||||
|---------|--------|------|-------|------------------|
|
||||
| Doji | Indecision | Open = Close (or nearly) | Long both sides | At S/R level = reversal |
|
||||
| Hammer | Bullish reversal | Small, at top of candle | Lower wick > 2x body | Must appear at bottom of downtrend |
|
||||
| Inverted Hammer | Bullish reversal | Small, at bottom of candle | Upper wick > 2x body | At bottom of downtrend, needs confirmation |
|
||||
| Shooting Star | Bearish reversal | Small, at bottom of candle | Upper wick > 2x body | Must appear at top of uptrend |
|
||||
| Hanging Man | Bearish reversal | Small, at top of candle | Lower wick > 2x body | At top of uptrend (same shape as Hammer) |
|
||||
| Marubozu (Bullish) | Strong continuation | Full green body, no wicks | None | Strong buying pressure |
|
||||
| Marubozu (Bearish) | Strong continuation | Full red body, no wicks | None | Strong selling pressure |
|
||||
| Spinning Top | Indecision | Small body centered | Equal wicks both sides | Trend may be losing steam |
|
||||
| Dragonfly Doji | Bullish reversal | Open = Close = High | Long lower wick only | At support = strong reversal signal |
|
||||
| Gravestone Doji | Bearish reversal | Open = Close = Low | Long upper wick only | At resistance = strong reversal signal |
|
||||
|
||||
### Multi-Candle Patterns
|
||||
| Pattern | Signal | Description | Reliability |
|
||||
|---------|--------|-------------|-------------|
|
||||
| Bullish Engulfing | Reversal up | Large green candle fully engulfs prior red candle | High at support |
|
||||
| Bearish Engulfing | Reversal down | Large red candle fully engulfs prior green candle | High at resistance |
|
||||
| Morning Star | Bullish reversal | Red candle, small body/doji with gap, large green candle | Very High |
|
||||
| Evening Star | Bearish reversal | Green candle, small body/doji with gap, large red candle | Very High |
|
||||
| Three White Soldiers | Strong bullish | Three consecutive large green candles, each closing higher | Very High |
|
||||
| Three Black Crows | Strong bearish | Three consecutive large red candles, each closing lower | Very High |
|
||||
| Bullish Harami | Potential reversal | Large red, then small green contained within red's body | Moderate (needs confirmation) |
|
||||
| Bearish Harami | Potential reversal | Large green, then small red contained within green's body | Moderate (needs confirmation) |
|
||||
| Tweezer Bottom | Bullish reversal | Two candles with matching lows at support | High |
|
||||
| Tweezer Top | Bearish reversal | Two candles with matching highs at resistance | High |
|
||||
| Piercing Line | Bullish reversal | Red candle, then green opens below red's low and closes above 50% of red's body | Moderate-High |
|
||||
| Dark Cloud Cover | Bearish reversal | Green candle, then red opens above green's high and closes below 50% of green's body | Moderate-High |
|
||||
|
||||
---
|
||||
|
||||
## 3. Risk Management Formulas
|
||||
|
||||
### Position Sizing (Fixed Fractional)
|
||||
```
|
||||
Position Size (shares) = Account Risk Amount / (Entry Price - Stop Loss Price)
|
||||
Account Risk Amount = Portfolio Value * Risk Per Trade %
|
||||
|
||||
RULE: Never risk more than 1-2% of portfolio on a single trade.
|
||||
|
||||
Worked example:
|
||||
Portfolio Value = $10,000
|
||||
Risk Per Trade = 2% ($200)
|
||||
Entry Price = $100.00
|
||||
Stop Loss = $95.00 (based on 2x ATR below entry)
|
||||
Risk per share = $100.00 - $95.00 = $5.00
|
||||
Position Size = $200 / $5.00 = 40 shares
|
||||
Position Value = 40 * $100 = $4,000 (40% of portfolio)
|
||||
|
||||
CONCENTRATION CHECK: If position value > 10% of portfolio, reduce size.
|
||||
Adjusted: max position = $1,000 / $100 = 10 shares
|
||||
Adjusted risk = 10 * $5.00 = $50 (only 0.5% of portfolio — acceptable)
|
||||
```
|
||||
|
||||
### Kelly Criterion (Optimal Bet Size)
|
||||
```
|
||||
Kelly % = W - ((1 - W) / R)
|
||||
Where:
|
||||
W = win rate (decimal)
|
||||
R = average win / average loss ratio (reward-to-risk)
|
||||
|
||||
Worked example:
|
||||
Win rate: 60% (W = 0.60)
|
||||
Average win: $300, Average loss: $200
|
||||
R = 300 / 200 = 1.5
|
||||
Kelly = 0.60 - (0.40 / 1.5) = 0.60 - 0.267 = 0.333 (33.3%)
|
||||
|
||||
Full Kelly is too aggressive for real trading. Use fractions:
|
||||
Half-Kelly = 0.333 / 2 = 16.7% of portfolio per trade
|
||||
Quarter-Kelly = 0.333 / 4 = 8.3% of portfolio per trade (recommended)
|
||||
|
||||
If Kelly is negative, the system has NEGATIVE expectancy — do not trade it.
|
||||
```
|
||||
|
||||
### Value at Risk (VaR)
|
||||
```
|
||||
Parametric VaR = Portfolio Value * Portfolio Volatility * Z-score * sqrt(Time Horizon)
|
||||
|
||||
Z-scores: 90% confidence = 1.282
|
||||
95% confidence = 1.645
|
||||
99% confidence = 2.326
|
||||
|
||||
Worked example (daily VaR, 95% confidence):
|
||||
Portfolio = $10,000
|
||||
Daily volatility (stddev of daily returns) = 2.0%
|
||||
VaR = $10,000 * 0.02 * 1.645 * sqrt(1) = $329.00
|
||||
Meaning: 95% confident daily loss will not exceed $329.
|
||||
|
||||
Weekly VaR = $329 * sqrt(5) = $329 * 2.236 = $735.65
|
||||
Monthly VaR = $329 * sqrt(21) = $329 * 4.583 = $1,507.81
|
||||
```
|
||||
|
||||
### Sharpe Ratio
|
||||
```
|
||||
Sharpe = (Rp - Rf) / StdDev(Rp) * sqrt(252)
|
||||
Where:
|
||||
Rp = mean daily portfolio return
|
||||
Rf = daily risk-free rate (Treasury yield / 252)
|
||||
StdDev(Rp) = standard deviation of daily returns
|
||||
252 = trading days per year (annualization factor)
|
||||
|
||||
Worked example:
|
||||
Mean daily return = 0.10% (0.001)
|
||||
Annual Treasury yield = 5.0% -> daily Rf = 0.05/252 = 0.000198
|
||||
StdDev of daily returns = 0.80% (0.008)
|
||||
Daily Sharpe = (0.001 - 0.000198) / 0.008 = 0.100
|
||||
Annualized Sharpe = 0.100 * sqrt(252) = 0.100 * 15.875 = 1.59
|
||||
|
||||
Ratings:
|
||||
< 0.5 = Poor (not compensated for risk)
|
||||
0.5-1.0 = Acceptable
|
||||
1.0-2.0 = Good
|
||||
2.0-3.0 = Very Good
|
||||
> 3.0 = Excellent (verify — may indicate overfitting)
|
||||
```
|
||||
|
||||
### Sortino Ratio (Downside-Only Risk)
|
||||
```
|
||||
Sortino = (Rp - Rf) / DownsideDeviation * sqrt(252)
|
||||
DownsideDeviation = sqrt(mean(min(Ri - Rf, 0)^2))
|
||||
|
||||
Better than Sharpe because it only penalizes downside volatility, not upside.
|
||||
Sortino > 2.0 is considered very good.
|
||||
```
|
||||
|
||||
### Maximum Drawdown
|
||||
```
|
||||
For each point t in equity curve:
|
||||
Peak(t) = max(Equity[0..t])
|
||||
Drawdown(t) = (Peak(t) - Equity(t)) / Peak(t) * 100%
|
||||
MaxDrawdown = max(Drawdown(t)) for all t
|
||||
|
||||
Worked example:
|
||||
Equity curve: $10,000 -> $12,000 -> $9,600 -> $11,500
|
||||
Peak at $12,000
|
||||
Drawdown at $9,600 = (12,000 - 9,600) / 12,000 = 20.0%
|
||||
Max Drawdown = 20.0%
|
||||
|
||||
Recovery Factor = Total Net Profit / Max Drawdown
|
||||
If total profit = $3,000, MaxDD = $2,400 -> RF = 3,000/2,400 = 1.25
|
||||
|
||||
Calmar Ratio = Annual Return / Max Drawdown
|
||||
If annual return = 25%, MaxDD = 20% -> Calmar = 1.25 (target > 1.0)
|
||||
```
|
||||
|
||||
### Profit Factor
|
||||
```
|
||||
Profit Factor = Gross Winning Trades / Gross Losing Trades
|
||||
|
||||
Worked example:
|
||||
10 winning trades totaling $5,000
|
||||
8 losing trades totaling $3,200
|
||||
Profit Factor = 5,000 / 3,200 = 1.5625
|
||||
|
||||
Ratings: < 1.0 = losing system, 1.0-1.5 = marginal, 1.5-2.0 = good,
|
||||
2.0-3.0 = very good, > 3.0 = excellent (verify with enough trades)
|
||||
```
|
||||
|
||||
### Expectancy Per Trade
|
||||
```
|
||||
Expectancy = (Win% * AvgWin) - (Loss% * AvgLoss)
|
||||
|
||||
Worked example:
|
||||
Win rate: 55%, Average win: $150, Average loss: $100
|
||||
Expectancy = (0.55 * 150) - (0.45 * 100) = 82.50 - 45.00 = $37.50/trade
|
||||
Over 100 trades: expected profit = $3,750
|
||||
|
||||
Minimum for a viable system: Expectancy > 0 with at least 30 sample trades.
|
||||
```
|
||||
|
||||
### Risk/Reward Ratio
|
||||
```
|
||||
R:R = (Target Price - Entry Price) / (Entry Price - Stop Loss Price)
|
||||
|
||||
Worked example:
|
||||
Entry = $100, Stop = $95, Target = $112
|
||||
R:R = (112 - 100) / (100 - 95) = 12 / 5 = 2.4:1
|
||||
|
||||
Minimum acceptable R:R = 1.5:1
|
||||
With 40% win rate and 2:1 R:R: Expectancy = 0.40*2 - 0.60*1 = +0.20 (profitable!)
|
||||
With 40% win rate and 1:1 R:R: Expectancy = 0.40*1 - 0.60*1 = -0.20 (losing!)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Alpaca Trading API Reference
|
||||
|
||||
### Authentication
|
||||
```bash
|
||||
# Paper trading (ALWAYS start here)
|
||||
BASE_URL="https://paper-api.alpaca.markets"
|
||||
|
||||
# Live trading (only after paper validation)
|
||||
# BASE_URL="https://api.alpaca.markets"
|
||||
|
||||
# Data API (same for both paper and live)
|
||||
DATA_URL="https://data.alpaca.markets"
|
||||
|
||||
# Auth headers (required on every request)
|
||||
HEADERS="-H 'APCA-API-KEY-ID: $ALPACA_API_KEY' -H 'APCA-API-SECRET-KEY: $ALPACA_SECRET_KEY'"
|
||||
```
|
||||
|
||||
### Account Information
|
||||
```bash
|
||||
# Get account details
|
||||
curl -s "$BASE_URL/v2/account" $HEADERS
|
||||
# Key fields: id, status, equity, cash, buying_power, portfolio_value,
|
||||
# pattern_day_trader (bool), daytrade_count, last_equity
|
||||
```
|
||||
|
||||
### Get Current Positions
|
||||
```bash
|
||||
# All positions
|
||||
curl -s "$BASE_URL/v2/positions" $HEADERS
|
||||
# Returns array: symbol, qty, side, avg_entry_price, current_price,
|
||||
# unrealized_pl, unrealized_plpc, market_value, cost_basis
|
||||
|
||||
# Single position
|
||||
curl -s "$BASE_URL/v2/positions/AAPL" $HEADERS
|
||||
```
|
||||
|
||||
### Place Orders
|
||||
```bash
|
||||
# Market order (fills immediately at best available price)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"AAPL","qty":"10","side":"buy","type":"market","time_in_force":"day"}'
|
||||
|
||||
# Limit order (fills only at your price or better)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"AAPL","qty":"10","side":"buy","type":"limit","time_in_force":"gtc","limit_price":"150.00"}'
|
||||
|
||||
# Stop order (triggers market order when stop price hit)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"AAPL","qty":"10","side":"sell","type":"stop","time_in_force":"gtc","stop_price":"145.00"}'
|
||||
|
||||
# Stop-limit order (triggers limit order when stop price hit)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"AAPL","qty":"10","side":"sell","type":"stop_limit","time_in_force":"gtc","stop_price":"145.00","limit_price":"144.50"}'
|
||||
|
||||
# Trailing stop (dynamic stop that trails price by dollar or percent amount)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"AAPL","qty":"10","side":"sell","type":"trailing_stop","time_in_force":"gtc","trail_percent":"5"}'
|
||||
|
||||
# Bracket order (entry + stop loss + take profit as one atomic order)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"symbol": "AAPL",
|
||||
"qty": "10",
|
||||
"side": "buy",
|
||||
"type": "limit",
|
||||
"time_in_force": "day",
|
||||
"limit_price": "150.00",
|
||||
"order_class": "bracket",
|
||||
"stop_loss": {"stop_price": "145.00"},
|
||||
"take_profit": {"limit_price": "165.00"}
|
||||
}'
|
||||
|
||||
# OCO order (one-cancels-other: stop loss OR take profit, whichever hits first)
|
||||
curl -s -X POST "$BASE_URL/v2/orders" $HEADERS \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"symbol": "AAPL",
|
||||
"qty": "10",
|
||||
"side": "sell",
|
||||
"type": "limit",
|
||||
"time_in_force": "gtc",
|
||||
"limit_price": "165.00",
|
||||
"order_class": "oco",
|
||||
"stop_loss": {"stop_price": "145.00"}
|
||||
}'
|
||||
```
|
||||
|
||||
**Order parameters reference:**
|
||||
| Parameter | Values | Notes |
|
||||
|-----------|--------|-------|
|
||||
| `side` | `buy`, `sell` | |
|
||||
| `type` | `market`, `limit`, `stop`, `stop_limit`, `trailing_stop` | |
|
||||
| `time_in_force` | `day`, `gtc`, `ioc`, `fok` | day = cancel at close, gtc = good til canceled |
|
||||
| `order_class` | `simple`, `bracket`, `oco`, `oto` | bracket = entry + stop + target |
|
||||
| `qty` | String number | Whole shares for stocks |
|
||||
| `notional` | String dollar amount | Alternative to qty (fractional shares) |
|
||||
|
||||
### Manage Orders
|
||||
```bash
|
||||
# List open orders
|
||||
curl -s "$BASE_URL/v2/orders?status=open" $HEADERS
|
||||
|
||||
# Get specific order
|
||||
curl -s "$BASE_URL/v2/orders/{order_id}" $HEADERS
|
||||
|
||||
# Cancel specific order
|
||||
curl -s -X DELETE "$BASE_URL/v2/orders/{order_id}" $HEADERS
|
||||
|
||||
# Cancel ALL open orders
|
||||
curl -s -X DELETE "$BASE_URL/v2/orders" $HEADERS
|
||||
```
|
||||
|
||||
### Close Positions
|
||||
```bash
|
||||
# Close entire position in a symbol
|
||||
curl -s -X DELETE "$BASE_URL/v2/positions/AAPL" $HEADERS
|
||||
|
||||
# Partially close (sell 5 of 10 shares)
|
||||
curl -s -X DELETE "$BASE_URL/v2/positions/AAPL?qty=5" $HEADERS
|
||||
|
||||
# EMERGENCY: Close ALL positions
|
||||
curl -s -X DELETE "$BASE_URL/v2/positions" $HEADERS
|
||||
```
|
||||
|
||||
### Market Data (free with Alpaca account)
|
||||
```bash
|
||||
# Latest quote (bid/ask)
|
||||
curl -s "$DATA_URL/v2/stocks/AAPL/quotes/latest" $HEADERS
|
||||
|
||||
# Latest trade (last fill)
|
||||
curl -s "$DATA_URL/v2/stocks/AAPL/trades/latest" $HEADERS
|
||||
|
||||
# Historical bars (OHLCV) — daily
|
||||
curl -s "$DATA_URL/v2/stocks/AAPL/bars?timeframe=1Day&start=2024-01-01&limit=100" $HEADERS
|
||||
|
||||
# Intraday bars — 5-minute
|
||||
curl -s "$DATA_URL/v2/stocks/AAPL/bars?timeframe=5Min&start=$(date -d 'today' +%Y-%m-%d)&limit=78" $HEADERS
|
||||
|
||||
# Multi-symbol snapshot
|
||||
curl -s "$DATA_URL/v2/stocks/snapshots?symbols=AAPL,MSFT,GOOGL" $HEADERS
|
||||
|
||||
# Crypto bars
|
||||
curl -s "$DATA_URL/v1beta3/crypto/us/bars?symbols=BTC/USD&timeframe=1Day&limit=30" $HEADERS
|
||||
|
||||
# Crypto latest quote
|
||||
curl -s "$DATA_URL/v1beta3/crypto/us/latest/quotes?symbols=BTC/USD,ETH/USD" $HEADERS
|
||||
```
|
||||
|
||||
### Market Clock & Calendar
|
||||
```bash
|
||||
# Is market open right now?
|
||||
curl -s "$BASE_URL/v2/clock" $HEADERS
|
||||
# Returns: timestamp, is_open (bool), next_open, next_close
|
||||
|
||||
# Upcoming market calendar
|
||||
curl -s "$BASE_URL/v2/calendar?start=$(date +%Y-%m-%d)&end=$(date -d '+7 days' +%Y-%m-%d)" $HEADERS
|
||||
```
|
||||
|
||||
### Crypto Trading Notes
|
||||
- Symbols use slash format: `BTC/USD`, `ETH/USD`, `SOL/USD`, `DOGE/USD`
|
||||
- 24/7 trading (no market hours restriction)
|
||||
- Fractional quantities allowed (e.g., `"qty": "0.001"` for BTC)
|
||||
- Paper trading works identically to live
|
||||
- Use `notional` for dollar-based crypto orders: `"notional": "100.00"` buys $100 worth
|
||||
|
||||
### Account Activity & History
|
||||
```bash
|
||||
# Trade history
|
||||
curl -s "$BASE_URL/v2/account/activities/FILL?after=2024-01-01" $HEADERS
|
||||
|
||||
# Portfolio history
|
||||
curl -s "$BASE_URL/v2/account/portfolio/history?period=1M&timeframe=1D" $HEADERS
|
||||
# Returns: timestamp[], equity[], profit_loss[], profit_loss_pct[]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Free Financial Data Sources
|
||||
|
||||
### Price Data (via web_search + web_fetch)
|
||||
| Source | URL Pattern | Data Available |
|
||||
|--------|-------------|----------------|
|
||||
| Yahoo Finance | `finance.yahoo.com/quote/AAPL` | Realtime quotes, charts, financials, analyst ratings |
|
||||
| Google Finance | `google.com/finance/quote/AAPL:NASDAQ` | Quotes, news, related stocks, earnings |
|
||||
| CoinGecko | `coingecko.com/en/coins/bitcoin` | Crypto prices, market cap, volume, 24h change |
|
||||
| CoinMarketCap | `coinmarketcap.com/currencies/bitcoin/` | Crypto prices, rankings, dominance, supply |
|
||||
| MarketWatch | `marketwatch.com/investing/stock/AAPL` | Quotes, news, analysis, options data |
|
||||
| Finviz | `finviz.com/quote.ashx?t=AAPL` | Technical + fundamental screener, charts |
|
||||
| TradingView | `tradingview.com/symbols/NASDAQ-AAPL/` | Charts, technicals, community ideas |
|
||||
|
||||
### Fundamental Data
|
||||
| Source | URL Pattern | Data Available |
|
||||
|--------|-------------|----------------|
|
||||
| Macrotrends | `macrotrends.net/stocks/charts/AAPL/apple/pe-ratio` | P/E, revenue, margins, historical |
|
||||
| Simply Wall St | Web search: `"AAPL simply wall st"` | Visual fundamental analysis, fair value |
|
||||
| SEC EDGAR | `sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=AAPL&type=10-K` | Official 10-K, 10-Q, 8-K filings |
|
||||
| Earnings Whispers | `earningswhispers.com/stocks/AAPL` | Earnings estimates, surprise history, calendar |
|
||||
| Stock Analysis | `stockanalysis.com/stocks/AAPL/financials/` | Clean financial statements, ratios |
|
||||
| Wisesheets | Web search: `"AAPL income statement"` | Financial data in spreadsheet format |
|
||||
|
||||
### Sentiment & Alternative Data
|
||||
| Source | URL | Data Available |
|
||||
|--------|-----|----------------|
|
||||
| CNN Fear & Greed | `money.cnn.com/data/fear-and-greed/` | Market sentiment index 0-100 (Extreme Fear to Extreme Greed) |
|
||||
| CBOE VIX | Web search: `"VIX index today"` | Volatility index (>30 = fear, <15 = complacency) |
|
||||
| Finviz Map | `finviz.com/map.ashx` | Market heatmap by sector/size |
|
||||
| StockTwits | `stocktwits.com/symbol/AAPL` | Social sentiment (bullish/bearish ratio) |
|
||||
| Put/Call Ratio | Web search: `"CBOE put call ratio today"` | Options sentiment (>1.0 = bearish, <0.7 = bullish) |
|
||||
| Short Interest | `finviz.com/quote.ashx?t=AAPL` -> Short Float | Percent of float sold short |
|
||||
| Insider Trading | `openinsider.com/screener` | CEO/CFO buy/sell patterns |
|
||||
|
||||
### Macro Economic Data
|
||||
| Source | URL | Data Available |
|
||||
|--------|-----|----------------|
|
||||
| FRED | `fred.stlouisfed.org` | Interest rates, CPI, employment, GDP, M2, yield curve |
|
||||
| Treasury.gov | `treasury.gov/resource-center/data-chart-center/interest-rates/` | Daily Treasury yield curve |
|
||||
| CME FedWatch | Web search: `"CME FedWatch tool"` | Federal funds rate probabilities |
|
||||
| BLS | `bls.gov/news.release/` | Employment situation, CPI, PPI |
|
||||
| ISM | Web search: `"ISM manufacturing PMI"` | PMI (>50 = expansion, <50 = contraction) |
|
||||
| Conference Board | Web search: `"consumer confidence index"` | Consumer confidence, leading indicators |
|
||||
| Earnings Calendar | `earningswhispers.com/calendar` | Upcoming earnings dates |
|
||||
| Economic Calendar | Web search: `"economic calendar this week"` | Scheduled data releases |
|
||||
|
||||
### Crypto-Specific Sources
|
||||
| Source | URL | Data Available |
|
||||
|--------|-----|----------------|
|
||||
| CoinGecko | `coingecko.com` | Prices, market cap, volume, DeFi TVL |
|
||||
| DefiLlama | `defillama.com` | Total Value Locked across all chains |
|
||||
| Glassnode (free tier) | Web search: `"bitcoin on-chain metrics"` | On-chain analytics (NUPL, MVRV, exchange flows) |
|
||||
| Bitcoin Fear & Greed | `alternative.me/crypto/fear-and-greed-index/` | Crypto-specific sentiment 0-100 |
|
||||
| Ultrasound Money | `ultrasound.money` | ETH supply/burn metrics |
|
||||
|
||||
---
|
||||
|
||||
## 6. Confidence Calibration Guide (Superforecasting)
|
||||
|
||||
### Calibration Principles (Philip Tetlock)
|
||||
- A "70% confident" prediction should be right about 70% of the time
|
||||
- Most people are overconfident: their "90%" predictions are right only ~70%
|
||||
- Track your predictions systematically and compare predicted vs actual frequency
|
||||
- Update incrementally (2-5% per new piece of evidence), not dramatically
|
||||
|
||||
### Confidence Level Guide
|
||||
| Level | Meaning | Evidence Required | Trading Action |
|
||||
|-------|---------|-------------------|----------------|
|
||||
| 20-30% | Slight lean | Single weak signal, limited data | No trade — insufficient edge |
|
||||
| 40-50% | Toss-up with slight edge | Conflicting signals, moderate evidence | No trade — coin flip |
|
||||
| 55-65% | Moderate conviction | Multiple aligned signals, historical precedent | Small position, wide stops |
|
||||
| 70-80% | Strong conviction | Strong multi-factor alignment, catalyst identified | Standard position size |
|
||||
| 85-95% | Very high conviction | Overwhelming evidence — be suspicious of yourself | Full position, but NEVER all-in |
|
||||
|
||||
### Brier Score for Trade Predictions
|
||||
```
|
||||
Brier Score = mean((predicted_probability - actual_outcome)^2)
|
||||
actual_outcome: 1 if prediction was correct, 0 if wrong
|
||||
|
||||
Worked example (5 predictions):
|
||||
Pred 1: 80% confident -> correct (1) -> (0.80 - 1)^2 = 0.04
|
||||
Pred 2: 60% confident -> wrong (0) -> (0.60 - 0)^2 = 0.36
|
||||
Pred 3: 70% confident -> correct (1) -> (0.70 - 1)^2 = 0.09
|
||||
Pred 4: 90% confident -> correct (1) -> (0.90 - 1)^2 = 0.01
|
||||
Pred 5: 55% confident -> wrong (0) -> (0.55 - 0)^2 = 0.30
|
||||
Brier Score = (0.04 + 0.36 + 0.09 + 0.01 + 0.30) / 5 = 0.16
|
||||
|
||||
Ratings: 0.00 = perfect, < 0.15 = excellent, 0.15-0.25 = good,
|
||||
0.25 = coin flip, > 0.25 = worse than random
|
||||
```
|
||||
|
||||
### Calibration Self-Check Protocol
|
||||
After accumulating 20+ trade predictions, group by confidence bucket:
|
||||
1. Are your 60% predictions right ~60% of the time?
|
||||
2. If your 60% predictions are right 80% of the time, you are underconfident — adjust up
|
||||
3. If your 80% predictions are right 55% of the time, you are overconfident — adjust down
|
||||
4. Recalibrate your confidence scale after every 50 resolved predictions
|
||||
|
||||
---
|
||||
|
||||
## 7. Trading Psychology & Cognitive Biases
|
||||
|
||||
### Biases to Watch For
|
||||
| Bias | Description | Mitigation |
|
||||
|------|-------------|------------|
|
||||
| **Confirmation Bias** | Seeking info that confirms your thesis | Always build the opposing case first (adversarial debate) |
|
||||
| **Anchoring** | Over-weighting the first number you see (entry price, analyst target) | Start analysis from base rates and current data, not old prices |
|
||||
| **Recency Bias** | Over-weighting recent events (last week's crash, last month's rally) | Look at longer timeframes — 6-month and 1-year charts minimum |
|
||||
| **Loss Aversion** | Holding losers too long ("it'll come back"), cutting winners too fast | Use mechanical stop-losses and take-profit targets, set BEFORE entry |
|
||||
| **Overconfidence** | Believing you are more right than you are | Track Brier scores, use Kelly fractions, never bet > 2% per trade |
|
||||
| **Narrative Bias** | Compelling story = good trade (often false) | Focus on quantitative data, not stories. "Good company" != "good trade" |
|
||||
| **FOMO** | Fear of missing out, chasing entries | Only enter at planned levels. The market is open 252 days a year |
|
||||
| **Sunk Cost** | "I've lost so much, I can't sell now" | Each moment is a new decision. Ask: "Would I enter this trade NOW at current price?" |
|
||||
| **Hindsight Bias** | "I knew that would happen" | Journal BEFORE trades with specific predictions, not after |
|
||||
| **Disposition Effect** | Selling winners early to "lock in profits" but holding losers | Let winners run (trail stops), cut losers at planned stops |
|
||||
| **Gambler's Fallacy** | "It's dropped 5 days in a row, it HAS to bounce" | Each day is independent. Trends persist more often than they reverse |
|
||||
| **Endowment Effect** | Overvaluing positions you already own | Evaluate positions as if you were building from scratch today |
|
||||
|
||||
### Discipline Rules
|
||||
1. Every trade has a written plan BEFORE entry: entry price, stop loss, target, position size, thesis
|
||||
2. Write down your reasoning BEFORE entering — if you cannot articulate the edge, do not trade
|
||||
3. Set stop-losses at order entry time, not "in your head"
|
||||
4. Review your journal weekly — look for patterns in wins AND losses
|
||||
5. Take breaks after big wins (overconfidence risk) AND big losses (emotional risk)
|
||||
6. Never average down on a losing position unless the original thesis explicitly planned for it
|
||||
7. Never move a stop-loss further away from your entry (only tighten, never widen)
|
||||
8. The market will be there tomorrow — missing a trade is not a loss, but a blown account is
|
||||
|
||||
---
|
||||
|
||||
## 8. Portfolio Construction
|
||||
|
||||
### Asset Allocation Guidelines
|
||||
| Style | Equities | Crypto | Fixed Income / Cash | Max Single Position |
|
||||
|-------|----------|--------|---------------------|---------------------|
|
||||
| Conservative | 50-60% | 0-5% | 35-50% | 5% |
|
||||
| Moderate | 60-75% | 5-15% | 10-35% | 8% |
|
||||
| Aggressive | 70-85% | 10-25% | 5-20% | 10% |
|
||||
| Speculative | 50-70% | 20-40% | 5-10% | 15% (with strict stops) |
|
||||
|
||||
### Sector Diversification
|
||||
Maximum 30% in any single sector:
|
||||
- Technology, Healthcare, Financials, Consumer Discretionary, Consumer Staples
|
||||
- Energy, Industrials, Utilities, Real Estate, Materials, Communication Services
|
||||
|
||||
### Correlation Awareness
|
||||
Highly correlated positions amplify risk. Check correlations before adding:
|
||||
| Pair | Typical Correlation | Risk |
|
||||
|------|---------------------|------|
|
||||
| AAPL + MSFT + GOOGL | 0.7-0.9 | Concentrated large-cap tech |
|
||||
| BTC + ETH + SOL | 0.8-0.95 | Concentrated crypto (moves together) |
|
||||
| SPY + QQQ | 0.9+ | Nearly identical exposure |
|
||||
| Stocks + Bonds | -0.2 to 0.3 | Genuinely diversifying |
|
||||
| Gold + Stocks | -0.1 to 0.2 | Hedge in crisis |
|
||||
| VIX + SPY | -0.8 | Inverse — VIX as hedge |
|
||||
|
||||
### Rebalancing Rules
|
||||
- **Calendar**: Rebalance quarterly (first trading day of quarter)
|
||||
- **Threshold**: Rebalance when any allocation drifts > 5% from target
|
||||
- **Tax-aware**: Prefer rebalancing via new contributions rather than selling (taxable accounts)
|
||||
|
||||
---
|
||||
|
||||
## 9. Cross-Platform Commands
|
||||
|
||||
### Windows (PowerShell / Git Bash)
|
||||
```bash
|
||||
# Python might be `python` not `python3` on Windows
|
||||
python -c "import json; ..."
|
||||
|
||||
# Use forward slashes in file paths or escape backslashes
|
||||
# curl is available via Git Bash, PowerShell, or WSL
|
||||
|
||||
# Check if market is open (Windows Git Bash)
|
||||
curl -s "$BASE_URL/v2/clock" -H "APCA-API-KEY-ID: $ALPACA_API_KEY" \
|
||||
-H "APCA-API-SECRET-KEY: $ALPACA_SECRET_KEY" | python -c "
|
||||
import sys, json
|
||||
d = json.load(sys.stdin)
|
||||
print('OPEN' if d['is_open'] else 'CLOSED', '| Next:', d.get('next_open','') or d.get('next_close',''))
|
||||
"
|
||||
```
|
||||
|
||||
### macOS / Linux
|
||||
```bash
|
||||
python3 -c "import json; ..."
|
||||
# curl, jq typically available by default
|
||||
# Use jq for JSON processing:
|
||||
curl -s URL | jq '.equity'
|
||||
```
|
||||
|
||||
### JSON Processing Without jq
|
||||
```bash
|
||||
# Pretty-print JSON
|
||||
python3 -c "import sys,json; print(json.dumps(json.load(sys.stdin),indent=2))" < file.json
|
||||
|
||||
# Extract specific field
|
||||
curl -s URL | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['equity'])"
|
||||
|
||||
# Parse Alpaca positions into readable table
|
||||
curl -s "$BASE_URL/v2/positions" $HEADERS | python3 -c "
|
||||
import sys, json
|
||||
positions = json.load(sys.stdin)
|
||||
fmt = '{:<8} {:>6} {:>10} {:>10} {:>12} {:>8}'
|
||||
print(fmt.format('Symbol','Qty','Entry','Current','P/L','P/L pct'))
|
||||
print('-' * 60)
|
||||
for p in positions:
|
||||
print(fmt.format(p['symbol'], p['qty'], float(p['avg_entry_price']),
|
||||
float(p['current_price']), float(p['unrealized_pl']),
|
||||
round(float(p['unrealized_plpc'])*100,2)))
|
||||
"
|
||||
|
||||
# Calculate RSI from historical bars
|
||||
curl -s "$DATA_URL/v2/stocks/AAPL/bars?timeframe=1Day&limit=30" $HEADERS | python3 -c "
|
||||
import sys, json
|
||||
data = json.load(sys.stdin)
|
||||
closes = [float(b['c']) for b in data['bars']]
|
||||
changes = [closes[i]-closes[i-1] for i in range(1, len(closes))]
|
||||
gains = [max(c,0) for c in changes[-14:]]
|
||||
losses = [abs(min(c,0)) for c in changes[-14:]]
|
||||
avg_gain = sum(gains)/14
|
||||
avg_loss = sum(losses)/14
|
||||
rs = avg_gain/avg_loss if avg_loss > 0 else 999
|
||||
rsi = 100 - (100/(1+rs))
|
||||
print(f'RSI(14) = {rsi:.1f}')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Pre-Trade Checklist
|
||||
|
||||
Before every trade, verify ALL of the following:
|
||||
|
||||
```
|
||||
PRE-TRADE CHECKLIST
|
||||
====================
|
||||
[ ] 1. TREND: What is the higher-timeframe trend? (Daily chart 200 SMA)
|
||||
- Trading WITH the trend? (preferred)
|
||||
- Counter-trend? (requires stronger signal + tighter stops)
|
||||
|
||||
[ ] 2. SIGNAL: What specific setup triggered this trade?
|
||||
- Indicator signal (RSI, MACD, etc.)
|
||||
- Pattern (candlestick, chart pattern)
|
||||
- Catalyst (earnings, news, sector rotation)
|
||||
|
||||
[ ] 3. ENTRY: Exact entry price or condition
|
||||
- Limit order at specific level? Market order on breakout?
|
||||
|
||||
[ ] 4. STOP LOSS: Exact stop price
|
||||
- Based on ATR (2-3x ATR from entry)
|
||||
- Below key support (long) or above key resistance (short)
|
||||
- NEVER wider than 2% of portfolio
|
||||
|
||||
[ ] 5. TARGET: Exact take-profit price
|
||||
- Risk/Reward at least 1.5:1 (preferably 2:1+)
|
||||
- At logical resistance (long) or support (short)
|
||||
|
||||
[ ] 6. POSITION SIZE: Calculated from risk management rules
|
||||
- Risk amount = Portfolio * 1-2%
|
||||
- Shares = Risk amount / (Entry - Stop)
|
||||
- Total position < 10% of portfolio
|
||||
|
||||
[ ] 7. CORRELATION CHECK: Does this overlap with existing positions?
|
||||
- Not adding to concentrated sector exposure
|
||||
- Total portfolio heat (sum of open risk) < 6%
|
||||
|
||||
[ ] 8. CATALYST CHECK: Any upcoming events that could gap through stops?
|
||||
- Earnings date? Fed meeting? CPI release?
|
||||
- If yes: reduce size or wait until after event
|
||||
|
||||
[ ] 9. MARKET CONTEXT: Is the overall market favorable?
|
||||
- Fear & Greed index level
|
||||
- VIX level (>30 = caution, <15 = complacency risk)
|
||||
- Market trend (SPY vs 200 SMA)
|
||||
|
||||
[ ] 10. CONFIDENCE: Rate 1-10 honestly
|
||||
- Below 6? Skip the trade
|
||||
- Record confidence for calibration tracking
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Trade Journal Template
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "T001",
|
||||
"date_opened": "2025-01-15",
|
||||
"date_closed": null,
|
||||
"symbol": "AAPL",
|
||||
"side": "long",
|
||||
"entry_price": 150.00,
|
||||
"stop_loss": 145.00,
|
||||
"target": 162.00,
|
||||
"position_size": 40,
|
||||
"risk_amount": 200.00,
|
||||
"risk_reward": 2.4,
|
||||
"setup": "Bullish engulfing at 50 EMA + RSI divergence",
|
||||
"confidence": 7,
|
||||
"market_context": "SPY above 200 SMA, VIX at 18, F&G neutral (52)",
|
||||
"pre_trade_thesis": "AAPL pulled back to 50 EMA support, RSI showing bullish divergence, earnings in 3 weeks should provide catalyst. Sector (tech) is leading.",
|
||||
"result": {
|
||||
"exit_price": null,
|
||||
"exit_reason": null,
|
||||
"pnl": null,
|
||||
"pnl_percent": null,
|
||||
"held_days": null,
|
||||
"lessons": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Store trade journals using `memory_store` for tracking and calibration review.
|
||||
Reference in new issue
Block a user