본문으로 건너뛰기
cccskills
무료GitHub에 공개

ib-trailing-stop

Server-side trailing stop management for stocks and naked LEAPS in IB. Places native TRAIL orders that auto-ratchet the stop as price climbs. Dry-run by default. Requires TWS or IB Gateway running locally.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구Interactive Brokers
설치 방법 보기

포함된 파일(2)

  • SKILL.md6.4 KB
  • scripts/trailing_stop.py3.0 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

IB Trailing Stop Manager

Places IB native TRAIL orders against stocks and naked LEAPS in the portfolio. IB auto-adjusts the stop trigger as the price climbs and locks it as price falls.

PMCC positions are intentionally excluded — use ib-stop-loss for those (a standalone trailing stop on the PMCC long leg would break the hedge at trigger).

Default mode is dry-run — no orders are placed unless --execute is in the request.

IB Connection

TWS or IB Gateway must be running locally with API enabled:

  • Paper trading — port 7497
  • Live trading — port 7496
  • IB_PORT env var — default port when --port is omitted (e.g. IB_PORT=4001 for a Gateway container). Precedence: --port flag > IB_PORT > built-in default. Set it in the shell or a .env file.

Port fallback: If the configured port fails, automatically retry on the other port. If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account. If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

Instructions

Step 1: Run the script

Dry-run (default — no orders placed):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --symbols JOBY --trail-pct 20

Execute (cancel orphan TS_ orders + place new TS_ TRAIL orders):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --symbols JOBY --trail-pct 20 --execute

Execute forced (cancel + replace existing TS_ orders with current parameters):

uv run python .claude/skills/ib-trailing-stop/scripts/trailing_stop.py --execute --forced

Step 2: Format the report

Format JSON output as a markdown report with three sections:

Section 1: Existing TRAIL Orders

Show all_trail_orders.module (TS_ orders) and all_trail_orders.manual (manually placed). If orphan_orders is non-empty, warn that these were cancelled (execute mode) or need manual cancellation (dry-run).

Section 2: Positions

For each entry in positions, show a table:

FieldValue
SymbolJOBY — stock (1000 shares)
Spot$7.50
Reference$7.50 (max of current $7.50, avg cost $5.00)
Trail params20% (initial stop $6.00) → action: place_new
Existing trailnone

For LEAPS rows, also show the option leg (strike/expiry) and current option mark.

action values:

  • place_new — no existing TS_ order; one will be created in execute mode
  • preserve_existing — TS_ already in place; left alone (IB has been tracking the high)
  • overwrite — --forced is on; existing TS_ will be cancelled and replaced

Section 3: Order Results (execute mode only)

Per-position result with order_id and order_ref.

Step 3: Report to user

  • State dry-run vs execute mode prominently.
  • Lead with positions that have action: place_new (these are about to get a new TRAIL).
  • Call out preserve_existing separately so user knows nothing changed.
  • Show existing trail details (current trail_stop_price) so user knows where IB has trailed to.

Arguments

FlagDefaultDescription
--port7497IB Gateway/TWS port
--accountallSpecific account ID
--symbolsallAnalyze only these symbols
--trail-pct20Trail amount as percentage of reference
--trail-amt—Trail amount in dollars (mutually exclusive with --trail-pct)
--price-modemidOption pricing: mid or last (LEAPS only)
--executeoffCancel orphans + place TS_ TRAIL orders
--forcedoffCancel and replace existing TS_ orders (requires --execute)

JSON Output Structure

{
  "generated_at": "2026-05-29 10:00 ET",
  "data_delay": "real-time",
  "dry_run": true,
  "forced": false,
  "trail_pct": 20.0,
  "trail_amt": null,
  "accounts": ["U1234567"],
  "symbols_filter": ["JOBY"],
  "all_trail_orders": {"module": [], "manual": []},
  "orphan_orders": [],
  "positions": [
    {
      "symbol": "JOBY",
      "type": "stock",
      "account": "U1234567",
      "qty": 1000,
      "underlying_price": 7.50,
      "stock": {
        "avg_cost": 5.00,
        "current_price": 7.50
      },
      "trail_stop": {
        "trail_pct": 20.0,
        "trail_amt": null,
        "reference": 7.50,
        "initial_stop_price": 6.00,
        "action": "place_new",
        "existing_trail": null
      }
    }
  ]
}

Key Behaviors

  • Reference price = max(current_price, avg_cost) — locks in profit when above cost, never starts below entry.
  • Forced mode uses current_price as the reference (can place an initial stop below entry, useful when re-arming after a drawdown).
  • Existing TS_ orders are preserved by default because IB has been ratcheting the trail since placement — replacing would reset that tracked high. Use --forced to deliberately reset.
  • Scope: stocks + naked LEAPS only. PMCC positions are excluded; use ib-stop-loss for those.

Order Identification

  • TS_{SYM}_{STRIKE}_{EXPIRY}_{RIGHT} — naked LEAPS TRAIL orders (right is C or P so calls and puts on the same strike/expiry don't collide)
  • TS_{SYM}_STK — stock TRAIL orders

Architecture

All analytics live in src/trading_skills/broker/trailing_stop.py:

Analytics (no IBKR — testable in isolation):

  • calc_trail_reference — max(current_price, avg_cost) normally; current_price if forced
  • calc_initial_trail_stop_price — reference × (1 − trail_pct/100) or reference − trail_amt
  • identify_trailable_positions — stocks + naked LEAPS; PMCC excluded
  • build_trail_analysis — full per-position output dict
  • detect_orphan_trail_orders — TS_ TRAIL orders for gone positions
  • summarize_all_trail_orders — splits IB TRAIL orders into module vs manual

Data layer (IBKR):

  • get_trailing_stop_data — main entry point
  • _cancel_orphan_orders — cancel stale TS_ orders
  • _place_simple_trail_order — native TRAIL order on stock or option
  • _execute_position_trail — dispatch per position type

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Get upcoming earnings dates with timing (before/after market) and EPS estimates. Use when user asks about earnings dates, earnings calendar, when a company reports, or upcoming earnings.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

Get fundamental financial data including financials, earnings, and key metrics. Use when user asks about financials, earnings, revenue, profit, balance sheet, income statement, or company fundamentals.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

greeks

무료

Calculate option Greeks (delta, gamma, theta, vega) and implied volatility for specific options. Use when user asks about Greeks, delta, gamma, theta, vega, IV, or option sensitivity analysis.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

ib_0dte

무료

Find and place the best 0DTE (zero-days-to-expiration) credit spreads from Interactive Brokers. Default execution route is the EMA9/EMA21 + VIX/VXN regime strategy (ema_vix_0dte.py), which auto-selects bull_put or bear_call from a bare EMA cross and skips the trade when the vol index is elevated (VXN ≥ 35 for NDX/QQQ, VIX ≥ 20 otherwise). Optional --rr-gate and --time-gate add red→red and bar-timing confirmation. Supports cash-settled indices (SPX, NDX, RUT, VIX) and any optionable stock/ETF. Manual spread type override is available via zero_dte.py. Requires TWS or IB Gateway running locally.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

Get account summary from Interactive Brokers including cash balance, buying power, and account value. Use when user asks about their account, balance, buying power, or available cash. Requires TWS or IB Gateway running locally.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

ib-collar

무료

Generate tactical collar strategy reports for protecting PMCC positions through earnings or high-risk events. Requires TWS or IB Gateway running locally.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

staskh/trading_skills3792026년 10월 16일 업데이트

staskh의 스킬 모두 보기

이 스킬의 문제 신고