trader-hand-skill

rightnow-ai/openfang

Экспертные знания для автономной рыночной аналитики и трейдинга: теханализ, риск-менеджмент, Alpaca API, финансовые источники данных.

Звёзды18 263
Авторrightnow-ai
Установок116

Установка

SKILL.md

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:

SignalDescriptionStrength
Bearish divergencePrice makes new high, RSI makes lower highStrong reversal warning
Bullish divergencePrice makes new low, RSI makes higher lowStrong reversal warning
Bullish failure swingRSI drops below 30, bounces, pulls back above 30, breaks prior RSI highVery strong buy
Bearish failure swingRSI rises above 70, drops, bounces below 70, breaks prior RSI lowVery strong sell
Range shiftRSI oscillates 40-80 in uptrend, 20-60 in downtrendTrend 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:

SignalConditionStrength
Bullish crossoverMACD crosses above Signal LineModerate buy
Bearish crossoverMACD crosses below Signal LineModerate sell
Zero-line bullish crossMACD crosses above zeroTrend change to bullish
Zero-line bearish crossMACD crosses below zeroTrend change to bearish
Histogram expansionBars growing tallerMomentum accelerating
Histogram contractionBars shrinkingMomentum weakening, reversal may come
Bullish divergencePrice new low, MACD higher lowStrong reversal signal
Bearish divergencePrice new high, MACD lower highStrong 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:

SignalConditionMeaning
SqueezeBandwidth at 6-month lowVolatility contraction, big move imminent
Squeeze breakout upPrice breaks above upper band after squeezeStrong bullish breakout
Squeeze breakout downPrice breaks below lower band after squeezeStrong bearish breakout
Walking the upper bandPrice hugs upper band with middle band risingStrong uptrend — do NOT short
Walking the lower bandPrice hugs lower band with middle band fallingStrong downtrend — do NOT buy
Mean reversion touchPrice touches outer band, %B reversesPotential reversion to middle band
W-bottomPrice hits lower band twice, second low has higher %BBullish reversal pattern
M-topPrice hits upper band twice, second high has lower %BBearish 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:

CrossNameMeaningReliability
50 MA > 200 MAGolden CrossBullish trend reversalHigh (lag ~2 weeks)
50 MA < 200 MADeath CrossBearish trend reversalHigh (lag ~2 weeks)
9 EMA > 21 EMAFast bullish crossShort-term momentum shiftModerate
Price > 200 SMAAbove long-term trendBullish regimeVery High
Price < 200 SMABelow long-term trendBearish regimeVery 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 CaseFormulaExample
Stop-loss placementEntry - 2 * ATREntry $100, ATR $2.50 -> Stop at $95.00
Take-profit targetEntry + 3 * ATREntry $100, ATR $2.50 -> Target $107.50
Position sizingRisk$ / ATR$200 risk / $2.50 ATR = 80 shares
Volatility filterATR > thresholdOnly trade when ATR > daily average (avoid dead markets)
Trailing stopHighest close - 3 * ATRLocks 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 ActionVolumeInterpretation
Price upVolume upStrong bullish — legitimate move
Price upVolume downWeak rally — likely to reverse
Price downVolume upStrong bearish — capitulation or breakdown
Price downVolume downWeak decline — may be nearing bottom
BreakoutVolume > 150% of 20-day avgConfirmed breakout — take the trade
BreakoutVolume < averageFailed breakout likely — wait or fade
Volume climaxExtreme 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

PatternSignalBodyWicksContext Required
DojiIndecisionOpen = Close (or nearly)Long both sidesAt S/R level = reversal
HammerBullish reversalSmall, at top of candleLower wick > 2x bodyMust appear at bottom of downtrend
Inverted HammerBullish reversalSmall, at bottom of candleUpper wick > 2x bodyAt bottom of downtrend, needs confirmation
Shooting StarBearish reversalSmall, at bottom of candleUpper wick > 2x bodyMust appear at top of uptrend
Hanging ManBearish reversalSmall, at top of candleLower wick > 2x bodyAt top of uptrend (same shape as Hammer)
Marubozu (Bullish)Strong continuationFull green body, no wicksNoneStrong buying pressure
Marubozu (Bearish)Strong continuationFull red body, no wicksNoneStrong selling pressure
Spinning TopIndecisionSmall body centeredEqual wicks both sidesTrend may be losing steam
Dragonfly DojiBullish reversalOpen = Close = HighLong lower wick onlyAt support = strong reversal signal
Gravestone DojiBearish reversalOpen = Close = LowLong upper wick onlyAt resistance = strong reversal signal

Multi-Candle Patterns

PatternSignalDescriptionReliability
Bullish EngulfingReversal upLarge green candle fully engulfs prior red candleHigh at support
Bearish EngulfingReversal downLarge red candle fully engulfs prior green candleHigh at resistance
Morning StarBullish reversalRed candle, small body/doji with gap, large green candleVery High
Evening StarBearish reversalGreen candle, small body/doji with gap, large red candleVery High
Three White SoldiersStrong bullishThree consecutive large green candles, each closing higherVery High
Three Black CrowsStrong bearishThree consecutive large red candles, each closing lowerVery High
Bullish HaramiPotential reversalLarge red, then small green contained within red's bodyModerate (needs confirmation)
Bearish HaramiPotential reversalLarge green, then small red contained within green's bodyModerate (needs confirmation)
Tweezer BottomBullish reversalTwo candles with matching lows at supportHigh
Tweezer TopBearish reversalTwo candles with matching highs at resistanceHigh
Piercing LineBullish reversalRed candle, then green opens below red's low and closes above 50% of red's bodyModerate-High
Dark Cloud CoverBearish reversalGreen candle, then red opens above green's high and closes below 50% of green's bodyModerate-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

# 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

# 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

# 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

# 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:

ParameterValuesNotes
sidebuy, sell
typemarket, limit, stop, stop_limit, trailing_stop
time_in_forceday, gtc, ioc, fokday = cancel at close, gtc = good til canceled
order_classsimple, bracket, oco, otobracket = entry + stop + target
qtyString numberWhole shares for stocks
notionalString dollar amountAlternative to qty (fractional shares)

Manage Orders

# 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

# 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)

# 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

# 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

# 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)

SourceURL PatternData Available
Yahoo Financefinance.yahoo.com/quote/AAPLRealtime quotes, charts, financials, analyst ratings
Google Financegoogle.com/finance/quote/AAPL:NASDAQQuotes, news, related stocks, earnings
CoinGeckocoingecko.com/en/coins/bitcoinCrypto prices, market cap, volume, 24h change
CoinMarketCapcoinmarketcap.com/currencies/bitcoin/Crypto prices, rankings, dominance, supply
MarketWatchmarketwatch.com/investing/stock/AAPLQuotes, news, analysis, options data
Finvizfinviz.com/quote.ashx?t=AAPLTechnical + fundamental screener, charts
TradingViewtradingview.com/symbols/NASDAQ-AAPL/Charts, technicals, community ideas

Fundamental Data

SourceURL PatternData Available
Macrotrendsmacrotrends.net/stocks/charts/AAPL/apple/pe-ratioP/E, revenue, margins, historical
Simply Wall StWeb search: "AAPL simply wall st"Visual fundamental analysis, fair value
SEC EDGARsec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=AAPL&type=10-KOfficial 10-K, 10-Q, 8-K filings
Earnings Whispersearningswhispers.com/stocks/AAPLEarnings estimates, surprise history, calendar
Stock Analysisstockanalysis.com/stocks/AAPL/financials/Clean financial statements, ratios
WisesheetsWeb search: "AAPL income statement"Financial data in spreadsheet format

Sentiment & Alternative Data

SourceURLData Available
CNN Fear & Greedmoney.cnn.com/data/fear-and-greed/Market sentiment index 0-100 (Extreme Fear to Extreme Greed)
CBOE VIXWeb search: "VIX index today"Volatility index (>30 = fear, <15 = complacency)
Finviz Mapfinviz.com/map.ashxMarket heatmap by sector/size
StockTwitsstocktwits.com/symbol/AAPLSocial sentiment (bullish/bearish ratio)
Put/Call RatioWeb search: "CBOE put call ratio today"Options sentiment (>1.0 = bearish, <0.7 = bullish)
Short Interestfinviz.com/quote.ashx?t=AAPL -> Short FloatPercent of float sold short
Insider Tradingopeninsider.com/screenerCEO/CFO buy/sell patterns

Macro Economic Data

SourceURLData Available
FREDfred.stlouisfed.orgInterest rates, CPI, employment, GDP, M2, yield curve
Treasury.govtreasury.gov/resource-center/data-chart-center/interest-rates/Daily Treasury yield curve
CME FedWatchWeb search: "CME FedWatch tool"Federal funds rate probabilities
BLSbls.gov/news.release/Employment situation, CPI, PPI
ISMWeb search: "ISM manufacturing PMI"PMI (>50 = expansion, <50 = contraction)
Conference BoardWeb search: "consumer confidence index"Consumer confidence, leading indicators
Earnings Calendarearningswhispers.com/calendarUpcoming earnings dates
Economic CalendarWeb search: "economic calendar this week"Scheduled data releases

Crypto-Specific Sources

SourceURLData Available
CoinGeckocoingecko.comPrices, market cap, volume, DeFi TVL
DefiLlamadefillama.comTotal Value Locked across all chains
Glassnode (free tier)Web search: "bitcoin on-chain metrics"On-chain analytics (NUPL, MVRV, exchange flows)
Bitcoin Fear & Greedalternative.me/crypto/fear-and-greed-index/Crypto-specific sentiment 0-100
Ultrasound Moneyultrasound.moneyETH 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

LevelMeaningEvidence RequiredTrading Action
20-30%Slight leanSingle weak signal, limited dataNo trade — insufficient edge
40-50%Toss-up with slight edgeConflicting signals, moderate evidenceNo trade — coin flip
55-65%Moderate convictionMultiple aligned signals, historical precedentSmall position, wide stops
70-80%Strong convictionStrong multi-factor alignment, catalyst identifiedStandard position size
85-95%Very high convictionOverwhelming evidence — be suspicious of yourselfFull 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. Перекалибруйте свою шкалу уверенности после каждых 50 разрешённых прогнозов

7. Психология торговли и когнитивные искажения

Искажения, за которыми нужно следить

ИскажениеОписаниеСмягчение
Искажение подтвержденияПоиск информации, подтверждающей вашу гипотезуВсегда сначала стройте противоположный аргумент (состязательная дискуссия)
ЯкорениеПереоценка первого увиденного числа (цена входа, цель аналитика)Начинайте анализ с базовых ставок и текущих данных, а не со старых цен
Искажение недавностиПереоценка недавних событий (обвал на прошлой неделе, ралли в прошлом месяце)Смотрите на более длительные таймфреймы — минимум графики за 6 месяцев и 1 год
Неприятие потерьСлишком долгое удержание убыточных позиций ("оно вернётся"), слишком быстрое закрытие прибыльныхИспользуйте механические стоп-лоссы и цели тейк-профита, установленные ДО входа
СамоуверенностьВера в то, что вы правы больше, чем это есть на самом делеОтслеживайте Brier scores, используйте доли Келли, никогда не рискуйте > 2% на сделку
Нарративное искажениеУбедительная история = хорошая сделка (часто ложно)Сосредоточьтесь на количественных данных, а не на историях. "Хорошая компания" != "хорошая сделка"
FOMOСтрах упустить возможность, погоня за входамиВходите только на запланированных уровнях. Рынок открыт 252 дня в году
Невозвратные затраты"Я потерял так много, что не могу продать сейчас"Каждый момент — это новое решение. Спросите: "Вошёл бы я в эту сделку СЕЙЧАС по текущей цене?"
Искажение ретроспективы"Я знал, что это произойдёт"Ведите журнал ДО сделок с конкретными прогнозами, а не после
Эффект диспозицииРанняя продажа прибыльных позиций, чтобы "зафиксировать прибыль", но удержание убыточныхДавайте прибыли расти (трейлинг-стопы), закрывайте убытки на запланированных стопах
Ошибка игрока"Оно падало 5 дней подряд, оно ОБЯЗАНО отскочить"Каждый день независим. Тренды сохраняются чаще, чем разворачиваются
Эффект владенияПереоценка позиций, которыми вы уже владеетеОценивайте позиции так, как если бы вы строили портфель с нуля сегодня

Правила дисциплины

  1. У каждой сделки есть письменный план ДО входа: цена входа, стоп-лосс, цель, размер позиции, гипотеза
  2. Запишите свои рассуждения ДО входа — если вы не можете сформулировать преимущество, не торгуйте
  3. Устанавливайте стоп-лоссы во время размещения ордера, а не "в голове"
  4. Просматривайте свой журнал еженедельно — ищите закономерности в прибылях И убытках
  5. Делайте перерывы после крупных выигрышей (риск самоуверенности) И крупных потерь (эмоциональный риск)
  6. Никогда не усредняйте убыточную позицию, если только исходная гипотеза явно не предусматривала этого
  7. Никогда не отодвигайте стоп-лосс дальше от точки входа (только сужайте, никогда не расширяйте)
  8. Рынок будет здесь и завтра — упущенная сделка не является убытком, но слитый счёт — является

8. Построение портфеля

Рекомендации по распределению активов

СтильАкцииКриптовалютаФиксированный доход / Денежные средстваМакс. одна позиция
Консервативный50-60%0-5%35-50%5%
Умеренный60-75%5-15%10-35%8%
Агрессивный70-85%10-25%5-20%10%
Спекулятивный50-70%20-40%5-10%15% (со строгими стопами)

Диверсификация по секторам

Максимум 30% в любом отдельном секторе:

  • Технологии, Здравоохранение, Финансы, Потребительский дискреционный, Потребительский базовый
  • Энергетика, Промышленность, Коммунальные услуги, Недвижимость, Материалы, Коммуникационные услуги

Учёт корреляций

Высококоррелированные позиции усиливают риск. Проверяйте корреляции перед добавлением:

ПараТипичная корреляцияРиск
AAPL + MSFT + GOOGL0.7-0.9Концентрированные крупные технологические компании
BTC + ETH + SOL0.8-0.95Концентрированная криптовалюта (движется вместе)
SPY + QQQ0.9+Почти идентичная экспозиция
Акции + Облигации-0.2 to 0.3Действительно диверсифицирует
Золото + Акции-0.1 to 0.2Хедж в кризис
VIX + SPY-0.8Обратная — VIX как хедж

Правила ребалансировки

  • Календарь: Ребалансируйте ежеквартально (первый торговый день квартала)
  • Порог: Ребалансируйте, когда любое распределение отклоняется > 5% от целевого
  • С учётом налогов: Предпочитайте ребалансировку через новые взносы, а не продажу (налогооблагаемые счета)

9. Кроссплатформенные команды

Windows (PowerShell / Git 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

python3 -c "import json; ..."
# curl, jq typically available by default
# Use jq for JSON processing:
curl -s URL | jq '.equity'

Обработка JSON без jq

# 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
====================
[ ] 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_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
  }
}

Храните торговые журналы с помощью memory_store для отслеживания и проверки калибровки.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: trader-hand-skill](https://darkplay.ru/ai/skills/rightnow-ai-openfang-trader-hand-skill)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
andrej-karpathy-skillsmultica-ai · Правила поведения для снижения типичных ошибок LLM при программировании: думай перед…
1 комп.
Agent Evaluatoraffaan-m · Оценивает результат агента по рубрике качества из 5 критериев (точность, полнота…
225 587 ★
Go Revieweraffaan-m · Ревьюер кода Go: идиоматичность, конкурентность, обработка ошибок и производительность.
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★
Opensource Packageraffaan-m · Готовит open-source упаковку: CLAUDE.md, README, LICENSE, CONTRIBUTING и шаблоны.
225 587 ★
Opensource Sanitizeraffaan-m · Проверяет open-source форк на утечки секретов, PII и опасные файлы перед релизом.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8