Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
ff746e3
1
Parent(s): 993c277
feat(journal,ai): point-in-time quant telemetry capture, post-mortem failure taxonomy & institutional audit dossier
Browse files- backend/database/db.py +50 -7
- backend/database/models.py +3 -0
- backend/routers/ai.py +14 -0
- backend/routers/journal.py +160 -27
- frontend/src/api/journal.ts +5 -2
- frontend/src/pages/TradeJournal.tsx +317 -7
- frontend/src/types/index.ts +3 -0
- tests/test_journal.py +121 -0
backend/database/db.py
CHANGED
|
@@ -66,6 +66,11 @@ def _format_row(row: dict | None) -> dict | None:
|
|
| 66 |
d["signal_data"] = json.loads(d["signal_data"])
|
| 67 |
except Exception:
|
| 68 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
if isinstance(d.get("signal_data"), dict):
|
| 70 |
if "streak" not in d["signal_data"] or d["signal_data"].get("streak") is None:
|
| 71 |
d["signal_data"]["streak"] = int(d.get("streak_count") or 0)
|
|
@@ -101,6 +106,16 @@ def init_db() -> None:
|
|
| 101 |
cur.execute(CREATE_JOURNAL_INDEX)
|
| 102 |
conn.commit()
|
| 103 |
logger.info("Created trade_journal and damian_memory tables.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
try:
|
| 105 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);")
|
| 106 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);")
|
|
@@ -129,6 +144,9 @@ def init_db() -> None:
|
|
| 129 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
|
| 130 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
|
| 131 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
|
|
|
|
|
|
|
|
|
|
| 132 |
""")
|
| 133 |
except Exception as e:
|
| 134 |
logger.warning("Postgres schema add column note: %s", e)
|
|
@@ -640,8 +658,15 @@ def db_get_journal_entries(status: str | None = None, limit: int = 50, offset: i
|
|
| 640 |
return [_format_row(r) for r in rows if r]
|
| 641 |
|
| 642 |
|
| 643 |
-
def db_update_journal_status(
|
| 644 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
st = status.upper().strip()
|
| 646 |
with get_connection() as conn:
|
| 647 |
with conn.cursor() as cur:
|
|
@@ -649,7 +674,9 @@ def db_update_journal_status(journal_id: int, status: str, note: str | None = No
|
|
| 649 |
cur.execute(
|
| 650 |
"""
|
| 651 |
UPDATE trade_journal
|
| 652 |
-
SET status = 'PENDING', outcome_note = NULL, outcome_at = NULL,
|
|
|
|
|
|
|
| 653 |
WHERE id = %s
|
| 654 |
RETURNING *;
|
| 655 |
""",
|
|
@@ -659,11 +686,12 @@ def db_update_journal_status(journal_id: int, status: str, note: str | None = No
|
|
| 659 |
cur.execute(
|
| 660 |
"""
|
| 661 |
UPDATE trade_journal
|
| 662 |
-
SET status = %s, outcome_note = %s, outcome_at = NOW()
|
|
|
|
| 663 |
WHERE id = %s
|
| 664 |
RETURNING *;
|
| 665 |
""",
|
| 666 |
-
(st, note, journal_id),
|
| 667 |
)
|
| 668 |
row = cur.fetchone()
|
| 669 |
return _format_row(row)
|
|
@@ -781,8 +809,23 @@ async def async_create_journal_entry(data: dict) -> dict:
|
|
| 781 |
async def async_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]:
|
| 782 |
return await asyncio.to_thread(db_get_journal_entries, status, limit, offset)
|
| 783 |
|
| 784 |
-
async def async_update_journal_status(
|
| 785 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
|
| 787 |
async def async_delete_journal_entry(journal_id: int) -> bool:
|
| 788 |
return await asyncio.to_thread(db_delete_journal_entry, journal_id)
|
|
|
|
| 66 |
d["signal_data"] = json.loads(d["signal_data"])
|
| 67 |
except Exception:
|
| 68 |
pass
|
| 69 |
+
if "snapshot_data" in d and isinstance(d["snapshot_data"], str):
|
| 70 |
+
try:
|
| 71 |
+
d["snapshot_data"] = json.loads(d["snapshot_data"])
|
| 72 |
+
except Exception:
|
| 73 |
+
pass
|
| 74 |
if isinstance(d.get("signal_data"), dict):
|
| 75 |
if "streak" not in d["signal_data"] or d["signal_data"].get("streak") is None:
|
| 76 |
d["signal_data"]["streak"] = int(d.get("streak_count") or 0)
|
|
|
|
| 106 |
cur.execute(CREATE_JOURNAL_INDEX)
|
| 107 |
conn.commit()
|
| 108 |
logger.info("Created trade_journal and damian_memory tables.")
|
| 109 |
+
else:
|
| 110 |
+
try:
|
| 111 |
+
cur.execute("""
|
| 112 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT;
|
| 113 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION;
|
| 114 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER;
|
| 115 |
+
""")
|
| 116 |
+
conn.commit()
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.warning("Postgres schema add column to trade_journal note: %s", e)
|
| 119 |
try:
|
| 120 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);")
|
| 121 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);")
|
|
|
|
| 144 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
|
| 145 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
|
| 146 |
ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
|
| 147 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT;
|
| 148 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION;
|
| 149 |
+
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER;
|
| 150 |
""")
|
| 151 |
except Exception as e:
|
| 152 |
logger.warning("Postgres schema add column note: %s", e)
|
|
|
|
| 658 |
return [_format_row(r) for r in rows if r]
|
| 659 |
|
| 660 |
|
| 661 |
+
def db_update_journal_status(
|
| 662 |
+
journal_id: int,
|
| 663 |
+
status: str,
|
| 664 |
+
note: str | None = None,
|
| 665 |
+
failure_tag: str | None = None,
|
| 666 |
+
exit_price: float | None = None,
|
| 667 |
+
holding_duration_seconds: int | None = None,
|
| 668 |
+
) -> dict | None:
|
| 669 |
+
"""Update trade outcome status (HIT_TP, HIT_SL, CANCELLED, PENDING) with rich post-mortem metadata."""
|
| 670 |
st = status.upper().strip()
|
| 671 |
with get_connection() as conn:
|
| 672 |
with conn.cursor() as cur:
|
|
|
|
| 674 |
cur.execute(
|
| 675 |
"""
|
| 676 |
UPDATE trade_journal
|
| 677 |
+
SET status = 'PENDING', outcome_note = NULL, outcome_at = NULL,
|
| 678 |
+
failure_tag = NULL, exit_price = NULL, holding_duration_seconds = NULL,
|
| 679 |
+
audited = FALSE
|
| 680 |
WHERE id = %s
|
| 681 |
RETURNING *;
|
| 682 |
""",
|
|
|
|
| 686 |
cur.execute(
|
| 687 |
"""
|
| 688 |
UPDATE trade_journal
|
| 689 |
+
SET status = %s, outcome_note = %s, outcome_at = NOW(),
|
| 690 |
+
failure_tag = %s, exit_price = %s, holding_duration_seconds = %s
|
| 691 |
WHERE id = %s
|
| 692 |
RETURNING *;
|
| 693 |
""",
|
| 694 |
+
(st, note, failure_tag, exit_price, holding_duration_seconds, journal_id),
|
| 695 |
)
|
| 696 |
row = cur.fetchone()
|
| 697 |
return _format_row(row)
|
|
|
|
| 809 |
async def async_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]:
|
| 810 |
return await asyncio.to_thread(db_get_journal_entries, status, limit, offset)
|
| 811 |
|
| 812 |
+
async def async_update_journal_status(
|
| 813 |
+
journal_id: int,
|
| 814 |
+
status: str,
|
| 815 |
+
note: str | None = None,
|
| 816 |
+
failure_tag: str | None = None,
|
| 817 |
+
exit_price: float | None = None,
|
| 818 |
+
holding_duration_seconds: int | None = None,
|
| 819 |
+
) -> dict | None:
|
| 820 |
+
return await asyncio.to_thread(
|
| 821 |
+
db_update_journal_status,
|
| 822 |
+
journal_id,
|
| 823 |
+
status,
|
| 824 |
+
note,
|
| 825 |
+
failure_tag,
|
| 826 |
+
exit_price,
|
| 827 |
+
holding_duration_seconds,
|
| 828 |
+
)
|
| 829 |
|
| 830 |
async def async_delete_journal_entry(journal_id: int) -> bool:
|
| 831 |
return await asyncio.to_thread(db_delete_journal_entry, journal_id)
|
backend/database/models.py
CHANGED
|
@@ -84,6 +84,9 @@ CREATE TABLE IF NOT EXISTS trade_journal (
|
|
| 84 |
status TEXT DEFAULT 'PENDING',
|
| 85 |
outcome_note TEXT,
|
| 86 |
outcome_at TIMESTAMPTZ,
|
|
|
|
|
|
|
|
|
|
| 87 |
snapshot_data JSONB,
|
| 88 |
audited BOOLEAN DEFAULT FALSE,
|
| 89 |
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
|
|
|
| 84 |
status TEXT DEFAULT 'PENDING',
|
| 85 |
outcome_note TEXT,
|
| 86 |
outcome_at TIMESTAMPTZ,
|
| 87 |
+
failure_tag TEXT,
|
| 88 |
+
exit_price DOUBLE PRECISION,
|
| 89 |
+
holding_duration_seconds INTEGER,
|
| 90 |
snapshot_data JSONB,
|
| 91 |
audited BOOLEAN DEFAULT FALSE,
|
| 92 |
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
backend/routers/ai.py
CHANGED
|
@@ -599,6 +599,7 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 599 |
"binance_fr": binance_fr,
|
| 600 |
"bybit_fr": bybit_fr,
|
| 601 |
"okx_fr": okx_fr,
|
|
|
|
| 602 |
"hyperliquid_fr": hl_fr,
|
| 603 |
"hyperliquid_oi_usd": hl.get("open_interest", 0.0),
|
| 604 |
"spot_cvd": spot_cvd,
|
|
@@ -607,9 +608,14 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 607 |
"upper_magnet": upper_mag,
|
| 608 |
"lower_magnet": lower_mag,
|
| 609 |
"squeeze_intensity": squeeze_intensity,
|
|
|
|
| 610 |
"resting_pressure": resting_pressure,
|
|
|
|
|
|
|
|
|
|
| 611 |
"conviction": conviction,
|
| 612 |
"direction": direction,
|
|
|
|
| 613 |
"streak": streak_count,
|
| 614 |
"confluence_pct": confluence_pct,
|
| 615 |
"high_24h": extremes.get("high_24h"),
|
|
@@ -618,14 +624,22 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 618 |
"dist_to_high_pct": extremes.get("dist_to_high_pct"),
|
| 619 |
"dist_to_low_pct": extremes.get("dist_to_low_pct"),
|
| 620 |
"range_position_pct": extremes.get("range_position_pct"),
|
|
|
|
| 621 |
"lead_lag_spread_bps": lead_lag.get("max_spread_bps"),
|
| 622 |
"leading_exchange": lead_lag.get("leading_exchange"),
|
| 623 |
"funding_countdown": settlement.get("countdown_str"),
|
| 624 |
"is_settlement_imminent": settlement.get("is_settlement_imminent"),
|
| 625 |
"taker_buy_pct": whale_flow.get("taker_buy_pct"),
|
|
|
|
| 626 |
"whale_buy_count": whale_flow.get("whale_buy_count"),
|
| 627 |
"whale_sell_count": whale_flow.get("whale_sell_count"),
|
|
|
|
|
|
|
| 628 |
"breakout_radar": breakout,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
}
|
| 630 |
|
| 631 |
return prompt, data_summary
|
|
|
|
| 599 |
"binance_fr": binance_fr,
|
| 600 |
"bybit_fr": bybit_fr,
|
| 601 |
"okx_fr": okx_fr,
|
| 602 |
+
"bitget_fr": bitget_fr,
|
| 603 |
"hyperliquid_fr": hl_fr,
|
| 604 |
"hyperliquid_oi_usd": hl.get("open_interest", 0.0),
|
| 605 |
"spot_cvd": spot_cvd,
|
|
|
|
| 608 |
"upper_magnet": upper_mag,
|
| 609 |
"lower_magnet": lower_mag,
|
| 610 |
"squeeze_intensity": squeeze_intensity,
|
| 611 |
+
"compression_ratio": round(compression_ratio, 2) if isinstance(compression_ratio, (int, float)) else 1.0,
|
| 612 |
"resting_pressure": resting_pressure,
|
| 613 |
+
"bid_depth_usd": bid_depth,
|
| 614 |
+
"ask_depth_usd": ask_depth,
|
| 615 |
+
"depth_ratio": round(depth_ratio, 2) if isinstance(depth_ratio, (int, float)) else 1.0,
|
| 616 |
"conviction": conviction,
|
| 617 |
"direction": direction,
|
| 618 |
+
"active_timeframe": active_tf,
|
| 619 |
"streak": streak_count,
|
| 620 |
"confluence_pct": confluence_pct,
|
| 621 |
"high_24h": extremes.get("high_24h"),
|
|
|
|
| 624 |
"dist_to_high_pct": extremes.get("dist_to_high_pct"),
|
| 625 |
"dist_to_low_pct": extremes.get("dist_to_low_pct"),
|
| 626 |
"range_position_pct": extremes.get("range_position_pct"),
|
| 627 |
+
"range_zone_label": extremes.get("zone_label"),
|
| 628 |
"lead_lag_spread_bps": lead_lag.get("max_spread_bps"),
|
| 629 |
"leading_exchange": lead_lag.get("leading_exchange"),
|
| 630 |
"funding_countdown": settlement.get("countdown_str"),
|
| 631 |
"is_settlement_imminent": settlement.get("is_settlement_imminent"),
|
| 632 |
"taker_buy_pct": whale_flow.get("taker_buy_pct"),
|
| 633 |
+
"taker_ratio": whale_flow.get("taker_ratio"),
|
| 634 |
"whale_buy_count": whale_flow.get("whale_buy_count"),
|
| 635 |
"whale_sell_count": whale_flow.get("whale_sell_count"),
|
| 636 |
+
"whale_buy_vol_usd": whale_flow.get("whale_buy_vol_usd"),
|
| 637 |
+
"whale_sell_vol_usd": whale_flow.get("whale_sell_vol_usd"),
|
| 638 |
"breakout_radar": breakout,
|
| 639 |
+
"market_structure": struct_map,
|
| 640 |
+
"global_regime": regime_text,
|
| 641 |
+
"fake_status": fake_status_str,
|
| 642 |
+
"warnings": signal.get("warnings") or [],
|
| 643 |
}
|
| 644 |
|
| 645 |
return prompt, data_summary
|
backend/routers/journal.py
CHANGED
|
@@ -10,7 +10,7 @@ from typing import Any
|
|
| 10 |
|
| 11 |
import httpx
|
| 12 |
from fastapi import APIRouter, HTTPException, Request
|
| 13 |
-
from pydantic import BaseModel
|
| 14 |
|
| 15 |
from database.db import (
|
| 16 |
async_create_journal_entry,
|
|
@@ -29,6 +29,17 @@ logger = logging.getLogger(__name__)
|
|
| 29 |
router = APIRouter(prefix="/api/journal", tags=["journal"])
|
| 30 |
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
class LogTradeRequest(BaseModel):
|
| 33 |
symbol: str
|
| 34 |
bias: str
|
|
@@ -47,6 +58,29 @@ class LogTradeRequest(BaseModel):
|
|
| 47 |
class UpdateTradeStatusRequest(BaseModel):
|
| 48 |
status: str # "HIT_TP" | "HIT_SL" | "CANCELLED" | "PENDING"
|
| 49 |
note: str | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
class SynthesizeAuditRequest(BaseModel):
|
|
@@ -98,7 +132,14 @@ async def update_trade_status(journal_id: int, body: UpdateTradeStatusRequest):
|
|
| 98 |
detail=f"Status tidak valid. Pilih salah satu dari: {', '.join(valid_statuses)}",
|
| 99 |
)
|
| 100 |
|
| 101 |
-
updated = await async_update_journal_status(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
if not updated:
|
| 103 |
raise HTTPException(status_code=404, detail=f"Trade Journal #{journal_id} tidak ditemukan.")
|
| 104 |
|
|
@@ -132,6 +173,97 @@ async def get_damian_memory():
|
|
| 132 |
return {"memories": memories}
|
| 133 |
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
@router.post("/audit")
|
| 136 |
async def synthesize_damian_memory(body: SynthesizeAuditRequest, request: Request):
|
| 137 |
"""
|
|
@@ -170,46 +302,47 @@ async def synthesize_damian_memory(body: SynthesizeAuditRequest, request: Reques
|
|
| 170 |
|
| 171 |
clean_api_key = api_key.strip().strip('"\'')
|
| 172 |
|
| 173 |
-
# 3. Format the audit dossier from failed trades
|
| 174 |
trade_bullets = []
|
| 175 |
trade_ids = []
|
|
|
|
| 176 |
for idx, t in enumerate(failed_trades, 1):
|
| 177 |
trade_ids.append(t["id"])
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
entry = t.get("entry_zone", "N/A")
|
| 181 |
-
sl = t.get("stop_loss", "N/A")
|
| 182 |
-
note = t.get("outcome_note") or "Tidak ada catatan manual"
|
| 183 |
-
snap = t.get("snapshot_data") or {}
|
| 184 |
-
cvd = snap.get("spot_cvd", "N/A")
|
| 185 |
-
fut_cvd = snap.get("futures_cvd", "N/A")
|
| 186 |
-
fr = snap.get("avg_fr_8h_pct", "N/A")
|
| 187 |
-
magnets = f"{snap.get('upper_magnet', 'N/A')} / {snap.get('lower_magnet', 'N/A')}"
|
| 188 |
-
|
| 189 |
-
trade_bullets.append(
|
| 190 |
-
f"{idx}. [{sym}] Bias: {bias} | Entry: {entry} | SL: {sl}\n"
|
| 191 |
-
f" Kondisi Pasar: Spot CVD: {cvd} vs Fut CVD: {fut_cvd} | Funding 8H: {fr}% | Magnets: {magnets}\n"
|
| 192 |
-
f" Catatan Trader: {note}"
|
| 193 |
-
)
|
| 194 |
|
| 195 |
dossier_text = "\n\n".join(trade_bullets)
|
| 196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
audit_prompt = f"""Role: Chief Risk Officer & Quantitative Trading Audit Committee.
|
| 198 |
-
Berikut adalah {len(failed_trades)} riwayat trade kripto derivatif yang mengalami STOP LOSS (gagal) pada sistem sinyal kuantitatif kami
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
=== 📋 DOSSIER
|
| 201 |
{dossier_text}
|
| 202 |
|
| 203 |
-
=== 🎯 TUGAS & INSTRUKSI AUDIT KUANTITATIF ===
|
| 204 |
-
1. Lakukan Root Cause Analysis (RCA)
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
3. Gaya Bahasa: Bahasa Indonesia yang tajam, bernada Quantitative Desk Protocol, padat dan bebas basa-basi pembuka/penutup.
|
| 207 |
|
| 208 |
Format Output Wajib:
|
| 209 |
### 🛡️ ATURAN PENGAMAN & MEMORI EVALUASI DAMIAN (BATCH #{len(failed_trades)} SL)
|
| 210 |
-
1. **[Nama Pantangan 1]**: [Penjelasan aturan kuantitatif yang harus dicegah]
|
| 211 |
-
2. **[Nama Pantangan 2]**: [Penjelasan aturan kuantitatif yang harus dicegah]
|
| 212 |
-
3. **[Nama Pantangan 3]**: [Penjelasan aturan kuantitatif yang harus dicegah]
|
| 213 |
(opsional 4): **[Nama Pantangan 4]**: [...]
|
| 214 |
"""
|
| 215 |
|
|
|
|
| 10 |
|
| 11 |
import httpx
|
| 12 |
from fastapi import APIRouter, HTTPException, Request
|
| 13 |
+
from pydantic import BaseModel, field_validator
|
| 14 |
|
| 15 |
from database.db import (
|
| 16 |
async_create_journal_entry,
|
|
|
|
| 29 |
router = APIRouter(prefix="/api/journal", tags=["journal"])
|
| 30 |
|
| 31 |
|
| 32 |
+
def _safe_float_fmt(val: Any, fmt: str = ",.4f", prefix: str = "", suffix: str = "") -> str:
|
| 33 |
+
"""Safely format numeric values into string representations without raising ValueError."""
|
| 34 |
+
if val is None or val == "":
|
| 35 |
+
return "N/A"
|
| 36 |
+
try:
|
| 37 |
+
f_val = float(val)
|
| 38 |
+
return f"{prefix}{f_val:{fmt}}{suffix}"
|
| 39 |
+
except (ValueError, TypeError):
|
| 40 |
+
return f"{prefix}{val}{suffix}"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
class LogTradeRequest(BaseModel):
|
| 44 |
symbol: str
|
| 45 |
bias: str
|
|
|
|
| 58 |
class UpdateTradeStatusRequest(BaseModel):
|
| 59 |
status: str # "HIT_TP" | "HIT_SL" | "CANCELLED" | "PENDING"
|
| 60 |
note: str | None = None
|
| 61 |
+
failure_tag: str | None = None
|
| 62 |
+
exit_price: float | None = None
|
| 63 |
+
holding_duration_seconds: int | None = None
|
| 64 |
+
|
| 65 |
+
@field_validator("exit_price", mode="before")
|
| 66 |
+
@classmethod
|
| 67 |
+
def parse_exit_price(cls, v: Any) -> float | None:
|
| 68 |
+
if v == "" or v is None:
|
| 69 |
+
return None
|
| 70 |
+
try:
|
| 71 |
+
return float(v)
|
| 72 |
+
except (ValueError, TypeError):
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
@field_validator("holding_duration_seconds", mode="before")
|
| 76 |
+
@classmethod
|
| 77 |
+
def parse_holding_duration(cls, v: Any) -> int | None:
|
| 78 |
+
if v == "" or v is None:
|
| 79 |
+
return None
|
| 80 |
+
try:
|
| 81 |
+
return int(v)
|
| 82 |
+
except (ValueError, TypeError):
|
| 83 |
+
return None
|
| 84 |
|
| 85 |
|
| 86 |
class SynthesizeAuditRequest(BaseModel):
|
|
|
|
| 132 |
detail=f"Status tidak valid. Pilih salah satu dari: {', '.join(valid_statuses)}",
|
| 133 |
)
|
| 134 |
|
| 135 |
+
updated = await async_update_journal_status(
|
| 136 |
+
journal_id=journal_id,
|
| 137 |
+
status=st,
|
| 138 |
+
note=body.note,
|
| 139 |
+
failure_tag=body.failure_tag,
|
| 140 |
+
exit_price=body.exit_price,
|
| 141 |
+
holding_duration_seconds=body.holding_duration_seconds,
|
| 142 |
+
)
|
| 143 |
if not updated:
|
| 144 |
raise HTTPException(status_code=404, detail=f"Trade Journal #{journal_id} tidak ditemukan.")
|
| 145 |
|
|
|
|
| 173 |
return {"memories": memories}
|
| 174 |
|
| 175 |
|
| 176 |
+
def _format_failed_trade_dossier(idx: int, t: dict) -> str:
|
| 177 |
+
"""Format an individual failed trade into a rich institutional post-mortem dossier."""
|
| 178 |
+
sym = t.get("symbol", "UNKNOWN")
|
| 179 |
+
bias = t.get("bias", "N/A")
|
| 180 |
+
entry = t.get("entry_zone", "N/A")
|
| 181 |
+
sl = t.get("stop_loss", "N/A")
|
| 182 |
+
tp = t.get("take_profit", "N/A")
|
| 183 |
+
rr = t.get("risk_reward", "N/A")
|
| 184 |
+
lev = t.get("leverage", "N/A")
|
| 185 |
+
invalidation = t.get("invalidation", "N/A")
|
| 186 |
+
note = t.get("outcome_note") or "Tidak ada catatan manual"
|
| 187 |
+
tag = t.get("failure_tag") or "UNSPECIFIED"
|
| 188 |
+
exit_px = t.get("exit_price")
|
| 189 |
+
exit_px_str = _safe_float_fmt(exit_px, ",.4f", "$") if exit_px is not None else "N/A (Tersentuh di level SL)"
|
| 190 |
+
|
| 191 |
+
# Holding duration
|
| 192 |
+
duration_sec = t.get("holding_duration_seconds")
|
| 193 |
+
if duration_sec is not None:
|
| 194 |
+
try:
|
| 195 |
+
dur_int = int(duration_sec)
|
| 196 |
+
hrs = dur_int // 3600
|
| 197 |
+
mins = (dur_int % 3600) // 60
|
| 198 |
+
dur_str = f"{hrs}j {mins}m" if hrs > 0 else f"{mins} menit ({dur_int}s)"
|
| 199 |
+
except (ValueError, TypeError):
|
| 200 |
+
dur_str = str(duration_sec)
|
| 201 |
+
else:
|
| 202 |
+
dur_str = "Tidak tercatat"
|
| 203 |
+
|
| 204 |
+
snap = t.get("snapshot_data") or {}
|
| 205 |
+
mark_px = snap.get("mark_price_str") or _safe_float_fmt(snap.get("mark_price"), ",.4f", "$")
|
| 206 |
+
cvd_label = snap.get("cvd_verdict") or "N/A"
|
| 207 |
+
spot_cvd = snap.get("spot_cvd", "N/A")
|
| 208 |
+
fut_cvd = snap.get("futures_cvd", "N/A")
|
| 209 |
+
fr = _safe_float_fmt(snap.get("avg_fr_8h_pct"), "+.4f", "", "%")
|
| 210 |
+
apr = _safe_float_fmt(snap.get("annualized_apr_pct"), "+.2f", "", "% APR")
|
| 211 |
+
magnets = f"Upper: {snap.get('upper_magnet', 'N/A')} | Lower: {snap.get('lower_magnet', 'N/A')}"
|
| 212 |
+
squeeze = snap.get("squeeze_intensity", "NORMAL")
|
| 213 |
+
compression = _safe_float_fmt(snap.get("compression_ratio"), ".2f")
|
| 214 |
+
resting = snap.get("resting_pressure", "Neutral")
|
| 215 |
+
depth_ratio = _safe_float_fmt(snap.get("depth_ratio"), ".2f", suffix="x")
|
| 216 |
+
range_pos = _safe_float_fmt(snap.get("range_position_pct"), ".1f", suffix="%")
|
| 217 |
+
range_zone = snap.get("range_zone_label", "Equilibrium")
|
| 218 |
+
lead_ex = snap.get("leading_exchange", "N/A")
|
| 219 |
+
lead_bps = _safe_float_fmt(snap.get("lead_lag_spread_bps"), ".1f")
|
| 220 |
+
conviction = snap.get("conviction", "N/A")
|
| 221 |
+
confluence = snap.get("confluence_pct", "N/A")
|
| 222 |
+
|
| 223 |
+
# MTF Structure
|
| 224 |
+
struct = snap.get("market_structure") or {}
|
| 225 |
+
if isinstance(struct, dict):
|
| 226 |
+
mtf_str = f"1D: {str(struct.get('1d', 'N/A')).upper()} | 4H: {str(struct.get('4h', 'N/A')).upper()} | 1H: {str(struct.get('1h', 'N/A')).upper()} | 15M: {str(struct.get('15m', 'N/A')).upper()}"
|
| 227 |
+
else:
|
| 228 |
+
mtf_str = str(struct)
|
| 229 |
+
|
| 230 |
+
# Whale block trades & taker flow
|
| 231 |
+
taker_buy = _safe_float_fmt(snap.get("taker_buy_pct"), ".1f", suffix="%")
|
| 232 |
+
taker_ratio = _safe_float_fmt(snap.get("taker_ratio"), ".2f", suffix="x")
|
| 233 |
+
whale_info = f"Taker Buy: {taker_buy} (Ratio: {taker_ratio}) | Whales: {snap.get('whale_buy_count', 0)} Buy vs {snap.get('whale_sell_count', 0)} Sell"
|
| 234 |
+
|
| 235 |
+
# Active warnings
|
| 236 |
+
raw_warnings = snap.get("warnings")
|
| 237 |
+
if isinstance(raw_warnings, list):
|
| 238 |
+
warn_str = ", ".join(str(w) for w in raw_warnings) if raw_warnings else "Tidak ada"
|
| 239 |
+
elif raw_warnings:
|
| 240 |
+
warn_str = str(raw_warnings)
|
| 241 |
+
else:
|
| 242 |
+
warn_str = "Tidak ada"
|
| 243 |
+
|
| 244 |
+
return f"""━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 245 |
+
📌 #{idx}. [{sym}] SETUP: {bias} (Conviction: {conviction}/10 | Confluence: {confluence}%)
|
| 246 |
+
• Level Rekomendasi: Entry: {entry} | SL: {sl} | TP: {tp} | R:R: {rr} | Lev: {lev}
|
| 247 |
+
• Aturan Invalidasi: {invalidation}
|
| 248 |
+
• KONDISI MIKROSTRUKTUR SAAT ENTRY DIREKOMENDASIKAN:
|
| 249 |
+
- Mark Price: {mark_px} | Posisi 24H: {range_pos} ({range_zone})
|
| 250 |
+
- Struktur Tren MTF: {mtf_str}
|
| 251 |
+
- Aliran Order Flow CVD: Spot: {spot_cvd} vs Futures: {fut_cvd} -> Status: {cvd_label}
|
| 252 |
+
- Konsensus Funding Rate: 8H {fr} (Annualized {apr})
|
| 253 |
+
- Orderbook Skew (Top 20): Tekanan {resting} (Rasio Kedalaman: {depth_ratio})
|
| 254 |
+
- Volatilitas & Squeeze: {squeeze} (Compression Ratio: {compression})
|
| 255 |
+
- Arbitrase Lead-Lag: {lead_ex} memimpin ({lead_bps} bps)
|
| 256 |
+
- Whale Taker Flow: {whale_info}
|
| 257 |
+
- Magnet Likuidasi: {magnets}
|
| 258 |
+
- Warning Terdeteksi Saat Entry: {warn_str}
|
| 259 |
+
• HASIL EKSEKUSI & POST-MORTEM STOP LOSS:
|
| 260 |
+
- Status: HIT STOP LOSS
|
| 261 |
+
- Kategori Diagnosis Trader: {tag}
|
| 262 |
+
- Durasi Posisi Bertahan: {dur_str}
|
| 263 |
+
- Perkiraan Harga Exit: {exit_px_str}
|
| 264 |
+
- Catatan Evaluasi Trader: {note}"""
|
| 265 |
+
|
| 266 |
+
|
| 267 |
@router.post("/audit")
|
| 268 |
async def synthesize_damian_memory(body: SynthesizeAuditRequest, request: Request):
|
| 269 |
"""
|
|
|
|
| 302 |
|
| 303 |
clean_api_key = api_key.strip().strip('"\'')
|
| 304 |
|
| 305 |
+
# 3. Format the comprehensive institutional audit dossier from failed trades
|
| 306 |
trade_bullets = []
|
| 307 |
trade_ids = []
|
| 308 |
+
tags = []
|
| 309 |
for idx, t in enumerate(failed_trades, 1):
|
| 310 |
trade_ids.append(t["id"])
|
| 311 |
+
tags.append(t.get("failure_tag") or "UNSPECIFIED")
|
| 312 |
+
trade_bullets.append(_format_failed_trade_dossier(idx, t))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
dossier_text = "\n\n".join(trade_bullets)
|
| 315 |
|
| 316 |
+
# Compute tag frequencies
|
| 317 |
+
from collections import Counter
|
| 318 |
+
tag_counts = Counter(tags)
|
| 319 |
+
tag_summary = ", ".join([f"{k}: {v}x" for k, v in tag_counts.items()])
|
| 320 |
+
|
| 321 |
audit_prompt = f"""Role: Chief Risk Officer & Quantitative Trading Audit Committee.
|
| 322 |
+
Berikut adalah {len(failed_trades)} riwayat trade kripto derivatif yang mengalami STOP LOSS (gagal) pada sistem sinyal kuantitatif kami.
|
| 323 |
+
Setiap trade menyertakan TELEMETRI MIKROSTRUKTUR LENGKAP PADA DETIK DIREKOMENDASIKAN (CVD, MTF, Funding APR, Orderbook Skew, Squeeze, Whales) vs HASIL DIAGNOSIS POST-MORTEM EKSEKUSI:
|
| 324 |
+
|
| 325 |
+
=== 📊 RINGKASAN DIAGNOSIS KEGAGALAN (TRADER POST-MORTEM) ===
|
| 326 |
+
Distribusi Pola Kegagalan: {tag_summary}
|
| 327 |
|
| 328 |
+
=== 📋 DOSSIER LENGKAP {len(failed_trades)} TRADE STOP LOSS TERAKHIR ===
|
| 329 |
{dossier_text}
|
| 330 |
|
| 331 |
+
=== 🎯 TUGAS & INSTRUKSI AUDIT KUANTITATIF (ROOT CAUSE ANALYSIS) ===
|
| 332 |
+
1. Lakukan Root Cause Analysis (RCA) Komparatif:
|
| 333 |
+
- Korelasikan pola kegagalan (Failure Tag) dengan telemetri entry:
|
| 334 |
+
• Kasus WICK_HUNT: Selidiki penempatan Stop Loss terhadap 24H High/Low, support mikro, dan jarak ke settlement funding rate.
|
| 335 |
+
• Kasus FALSE_BREAKOUT: Selidiki apakah buy dilakukan saat 24H Range Posisi > 75% atau saat Futures CVD naik tapi Spot CVD buang barang (Leverage Trap).
|
| 336 |
+
• Kasus BTC_DUMP / MACRO: Selidiki apakah posisi melawan Rezim Pasar Global saat itu.
|
| 337 |
+
• Kasus TREND_REVERSAL: Selidiki apakah tren LTF (15m/1h) bertabrakan dengan tren HTF (4h/1d).
|
| 338 |
+
2. Rumuskan persis 3-4 ATURAN PENGAMAN EMAS (GOLDEN SAFEGUARDS) yang ringkas, tegas, berbasis data empiris di atas, dan WAJIB dipatuhi Damian pada analisa berikutnya agar tidak mengulangi kesalahan serupa.
|
| 339 |
3. Gaya Bahasa: Bahasa Indonesia yang tajam, bernada Quantitative Desk Protocol, padat dan bebas basa-basi pembuka/penutup.
|
| 340 |
|
| 341 |
Format Output Wajib:
|
| 342 |
### 🛡️ ATURAN PENGAMAN & MEMORI EVALUASI DAMIAN (BATCH #{len(failed_trades)} SL)
|
| 343 |
+
1. **[Nama Pantangan 1]**: [Penjelasan aturan kuantitatif yang harus dicegah berdasarkan bukti telemetri di atas]
|
| 344 |
+
2. **[Nama Pantangan 2]**: [Penjelasan aturan kuantitatif yang harus dicegah berdasarkan bukti telemetri di atas]
|
| 345 |
+
3. **[Nama Pantangan 3]**: [Penjelasan aturan kuantitatif yang harus dicegah berdasarkan bukti telemetri di atas]
|
| 346 |
(opsional 4): **[Nama Pantangan 4]**: [...]
|
| 347 |
"""
|
| 348 |
|
frontend/src/api/journal.ts
CHANGED
|
@@ -44,11 +44,14 @@ export const journalApi = {
|
|
| 44 |
updateStatus: async (
|
| 45 |
id: number,
|
| 46 |
status: 'HIT_TP' | 'HIT_SL' | 'CANCELLED' | 'PENDING',
|
| 47 |
-
note?: string
|
|
|
|
|
|
|
|
|
|
| 48 |
): Promise<{ success: boolean; entry: TradeJournalEntry; stats: JournalStats }> => {
|
| 49 |
const { data } = await apiClient.patch<{ success: boolean; entry: TradeJournalEntry; stats: JournalStats }>(
|
| 50 |
`/api/journal/${id}/status`,
|
| 51 |
-
{ status, note }
|
| 52 |
);
|
| 53 |
return data;
|
| 54 |
},
|
|
|
|
| 44 |
updateStatus: async (
|
| 45 |
id: number,
|
| 46 |
status: 'HIT_TP' | 'HIT_SL' | 'CANCELLED' | 'PENDING',
|
| 47 |
+
note?: string,
|
| 48 |
+
failure_tag?: string,
|
| 49 |
+
exit_price?: number,
|
| 50 |
+
holding_duration_seconds?: number
|
| 51 |
): Promise<{ success: boolean; entry: TradeJournalEntry; stats: JournalStats }> => {
|
| 52 |
const { data } = await apiClient.patch<{ success: boolean; entry: TradeJournalEntry; stats: JournalStats }>(
|
| 53 |
`/api/journal/${id}/status`,
|
| 54 |
+
{ status, note, failure_tag, exit_price, holding_duration_seconds }
|
| 55 |
);
|
| 56 |
return data;
|
| 57 |
},
|
frontend/src/pages/TradeJournal.tsx
CHANGED
|
@@ -11,6 +11,12 @@ import {
|
|
| 11 |
Brain,
|
| 12 |
Search,
|
| 13 |
Bot,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
} from 'lucide-react';
|
| 15 |
import { Button } from '../components/ui/Button';
|
| 16 |
import { Modal } from '../components/ui/Modal';
|
|
@@ -24,6 +30,15 @@ interface TradeJournalProps {
|
|
| 24 |
onNavigateToAI?: (symbol: string) => void;
|
| 25 |
}
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
| 28 |
const [entries, setEntries] = useState<TradeJournalEntry[]>([]);
|
| 29 |
const [stats, setStats] = useState<JournalStats>({
|
|
@@ -47,8 +62,13 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 47 |
targetStatus: 'HIT_TP' | 'HIT_SL' | 'CANCELLED';
|
| 48 |
} | null>(null);
|
| 49 |
const [outcomeNote, setOutcomeNote] = useState('');
|
|
|
|
|
|
|
| 50 |
const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
|
| 51 |
|
|
|
|
|
|
|
|
|
|
| 52 |
// Delete modal state
|
| 53 |
const [deleteModalData, setDeleteModalData] = useState<TradeJournalEntry | null>(null);
|
| 54 |
const [isDeleting, setIsDeleting] = useState(false);
|
|
@@ -98,22 +118,54 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 98 |
});
|
| 99 |
}, [entries, searchQuery, filterStatus]);
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
const handleOpenConfirm = (
|
| 102 |
entry: TradeJournalEntry,
|
| 103 |
targetStatus: 'HIT_TP' | 'HIT_SL' | 'CANCELLED'
|
| 104 |
) => {
|
| 105 |
setConfirmModalData({ entry, targetStatus });
|
| 106 |
-
setOutcomeNote('');
|
|
|
|
|
|
|
| 107 |
};
|
| 108 |
|
| 109 |
const handleExecuteStatusUpdate = async () => {
|
| 110 |
if (!confirmModalData) return;
|
| 111 |
setIsUpdatingStatus(true);
|
| 112 |
try {
|
|
|
|
|
|
|
|
|
|
| 113 |
const res = await journalApi.updateStatus(
|
| 114 |
confirmModalData.entry.id,
|
| 115 |
confirmModalData.targetStatus,
|
| 116 |
-
outcomeNote.trim() || undefined
|
|
|
|
|
|
|
|
|
|
| 117 |
);
|
| 118 |
|
| 119 |
// Update local state
|
|
@@ -124,7 +176,7 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 124 |
|
| 125 |
const statusLabels = {
|
| 126 |
HIT_TP: '🟢 Berhasil HIT TP! Selamat atas cuan Anda!',
|
| 127 |
-
HIT_SL: '🔴 Terkena Stop Loss.
|
| 128 |
CANCELLED: '⚪ Sinyal dibatalkan / Breakeven.',
|
| 129 |
};
|
| 130 |
toast(statusLabels[confirmModalData.targetStatus], 'info');
|
|
@@ -452,6 +504,30 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 452 |
{item.bias}
|
| 453 |
</span>
|
| 454 |
{getStatusBadge(item.status)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
{item.audited && (
|
| 456 |
<span className="text-[9px] font-mono px-1.5 py-0.2 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">
|
| 457 |
Diaudit
|
|
@@ -525,6 +601,182 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 525 |
</p>
|
| 526 |
)}
|
| 527 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
{/* Interactive Status Confirmation Action Bar */}
|
| 529 |
<div className="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-border/50">
|
| 530 |
<span className="text-[11px] text-text-muted font-medium">
|
|
@@ -601,10 +853,10 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 601 |
isOpen={Boolean(confirmModalData)}
|
| 602 |
onClose={() => setConfirmModalData(null)}
|
| 603 |
title={`Konfirmasi Hasil Trade: ${confirmModalData.entry.symbol}`}
|
| 604 |
-
size=
|
| 605 |
>
|
| 606 |
<div className="space-y-3.5">
|
| 607 |
-
<div className="p-3 rounded-lg bg-bg-elevated border border-border text-xs space-y-1">
|
| 608 |
<div className="flex items-center justify-between">
|
| 609 |
<span className="text-text-muted">Pair & Bias:</span>
|
| 610 |
<span className="font-bold text-text-primary">
|
|
@@ -625,16 +877,74 @@ export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
|
| 625 |
{confirmModalData.targetStatus}
|
| 626 |
</span>
|
| 627 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
</div>
|
| 629 |
|
| 630 |
<div>
|
| 631 |
<label className="block text-xs font-semibold text-text-secondary mb-1">
|
| 632 |
-
Catatan Pribadi (Opsional)
|
| 633 |
</label>
|
| 634 |
<textarea
|
| 635 |
value={outcomeNote}
|
| 636 |
onChange={(e) => setOutcomeNote(e.target.value)}
|
| 637 |
-
placeholder="Contoh: Kena
|
| 638 |
rows={2}
|
| 639 |
className="w-full p-2.5 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500"
|
| 640 |
/>
|
|
|
|
| 11 |
Brain,
|
| 12 |
Search,
|
| 13 |
Bot,
|
| 14 |
+
ChevronDown,
|
| 15 |
+
ChevronUp,
|
| 16 |
+
Activity,
|
| 17 |
+
Clock,
|
| 18 |
+
BarChart2,
|
| 19 |
+
AlertTriangle,
|
| 20 |
} from 'lucide-react';
|
| 21 |
import { Button } from '../components/ui/Button';
|
| 22 |
import { Modal } from '../components/ui/Modal';
|
|
|
|
| 30 |
onNavigateToAI?: (symbol: string) => void;
|
| 31 |
}
|
| 32 |
|
| 33 |
+
const FAILURE_TAGS = [
|
| 34 |
+
{ id: 'WICK_HUNT', label: '⚡ Jarum Wick Hunt', desc: 'SL tersapu jarum tipis lalu harga langsung mantul balik' },
|
| 35 |
+
{ id: 'FALSE_BREAKOUT', label: '🛑 False Breakout', desc: 'Terjebak beli di pucuk resisten atau sell di dasar support' },
|
| 36 |
+
{ id: 'BTC_DUMP', label: '📉 Market / BTC Drag', desc: 'Terseret kejatuhan pasar global / dump mendadak Bitcoin' },
|
| 37 |
+
{ id: 'TREND_REVERSAL', label: '🔄 Trend Reversal (HTF)', desc: 'Struktur tren HTF (1H/4H) patah berbalik arah melawan posisi' },
|
| 38 |
+
{ id: 'PREMATURE_ENTRY', label: '⚠️ Entry Prematur', desc: 'Masuk sebelum candle konfirmasi / pullback selesai terbentuk' },
|
| 39 |
+
{ id: 'OTHER', label: '📝 Alasan Lainnya', desc: 'Penyebab teknis atau faktor pasar lainnya' },
|
| 40 |
+
];
|
| 41 |
+
|
| 42 |
export function TradeJournal({ onNavigateToAI }: TradeJournalProps) {
|
| 43 |
const [entries, setEntries] = useState<TradeJournalEntry[]>([]);
|
| 44 |
const [stats, setStats] = useState<JournalStats>({
|
|
|
|
| 62 |
targetStatus: 'HIT_TP' | 'HIT_SL' | 'CANCELLED';
|
| 63 |
} | null>(null);
|
| 64 |
const [outcomeNote, setOutcomeNote] = useState('');
|
| 65 |
+
const [failureTag, setFailureTag] = useState<string>('WICK_HUNT');
|
| 66 |
+
const [exitPrice, setExitPrice] = useState<string>('');
|
| 67 |
const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
|
| 68 |
|
| 69 |
+
// Expandable telemetry drawers per card
|
| 70 |
+
const [expandedTelemetry, setExpandedTelemetry] = useState<Record<number, boolean>>({});
|
| 71 |
+
|
| 72 |
// Delete modal state
|
| 73 |
const [deleteModalData, setDeleteModalData] = useState<TradeJournalEntry | null>(null);
|
| 74 |
const [isDeleting, setIsDeleting] = useState(false);
|
|
|
|
| 118 |
});
|
| 119 |
}, [entries, searchQuery, filterStatus]);
|
| 120 |
|
| 121 |
+
const calculateHoldingDuration = (createdAtStr: string): { seconds: number; formatted: string } => {
|
| 122 |
+
try {
|
| 123 |
+
const created = new Date(createdAtStr).getTime();
|
| 124 |
+
const now = Date.now();
|
| 125 |
+
const diffSec = Math.max(0, Math.floor((now - created) / 1000));
|
| 126 |
+
const hrs = Math.floor(diffSec / 3600);
|
| 127 |
+
const mins = Math.floor((diffSec % 3600) / 60);
|
| 128 |
+
let formatted = `${mins} menit`;
|
| 129 |
+
if (hrs > 0) {
|
| 130 |
+
formatted = `${hrs} jam ${mins} menit`;
|
| 131 |
+
}
|
| 132 |
+
return { seconds: diffSec, formatted };
|
| 133 |
+
} catch {
|
| 134 |
+
return { seconds: 0, formatted: 'N/A' };
|
| 135 |
+
}
|
| 136 |
+
};
|
| 137 |
+
|
| 138 |
+
const toggleTelemetry = (id: number) => {
|
| 139 |
+
setExpandedTelemetry((prev) => ({
|
| 140 |
+
...prev,
|
| 141 |
+
[id]: !prev[id],
|
| 142 |
+
}));
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
const handleOpenConfirm = (
|
| 146 |
entry: TradeJournalEntry,
|
| 147 |
targetStatus: 'HIT_TP' | 'HIT_SL' | 'CANCELLED'
|
| 148 |
) => {
|
| 149 |
setConfirmModalData({ entry, targetStatus });
|
| 150 |
+
setOutcomeNote(entry.outcome_note || '');
|
| 151 |
+
setFailureTag(entry.failure_tag || (targetStatus === 'HIT_SL' ? 'WICK_HUNT' : ''));
|
| 152 |
+
setExitPrice(entry.exit_price ? String(entry.exit_price) : '');
|
| 153 |
};
|
| 154 |
|
| 155 |
const handleExecuteStatusUpdate = async () => {
|
| 156 |
if (!confirmModalData) return;
|
| 157 |
setIsUpdatingStatus(true);
|
| 158 |
try {
|
| 159 |
+
const duration = calculateHoldingDuration(confirmModalData.entry.created_at);
|
| 160 |
+
const parsedExitPx = exitPrice.trim() ? parseFloat(exitPrice.trim()) : undefined;
|
| 161 |
+
|
| 162 |
const res = await journalApi.updateStatus(
|
| 163 |
confirmModalData.entry.id,
|
| 164 |
confirmModalData.targetStatus,
|
| 165 |
+
outcomeNote.trim() || undefined,
|
| 166 |
+
confirmModalData.targetStatus === 'HIT_SL' ? failureTag || 'OTHER' : undefined,
|
| 167 |
+
parsedExitPx && !isNaN(parsedExitPx) ? parsedExitPx : undefined,
|
| 168 |
+
duration.seconds > 0 ? duration.seconds : undefined
|
| 169 |
);
|
| 170 |
|
| 171 |
// Update local state
|
|
|
|
| 176 |
|
| 177 |
const statusLabels = {
|
| 178 |
HIT_TP: '🟢 Berhasil HIT TP! Selamat atas cuan Anda!',
|
| 179 |
+
HIT_SL: '🔴 Terkena Stop Loss. Diagnosa & telemetri dicatat untuk evaluasi Damian.',
|
| 180 |
CANCELLED: '⚪ Sinyal dibatalkan / Breakeven.',
|
| 181 |
};
|
| 182 |
toast(statusLabels[confirmModalData.targetStatus], 'info');
|
|
|
|
| 504 |
{item.bias}
|
| 505 |
</span>
|
| 506 |
{getStatusBadge(item.status)}
|
| 507 |
+
{item.failure_tag && (
|
| 508 |
+
<span className="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-rose-950/60 border border-rose-500/40 text-rose-300 flex items-center gap-1">
|
| 509 |
+
{item.failure_tag === 'WICK_HUNT' && '⚡ Jarum Wick Hunt'}
|
| 510 |
+
{item.failure_tag === 'FALSE_BREAKOUT' && '🛑 False Breakout'}
|
| 511 |
+
{item.failure_tag === 'BTC_DUMP' && '📉 Market / BTC Drag'}
|
| 512 |
+
{item.failure_tag === 'TREND_REVERSAL' && '🔄 Trend Reversal'}
|
| 513 |
+
{item.failure_tag === 'PREMATURE_ENTRY' && '⚠️ Entry Prematur'}
|
| 514 |
+
{item.failure_tag === 'OTHER' && '📝 Alasan Lainnya'}
|
| 515 |
+
{!['WICK_HUNT', 'FALSE_BREAKOUT', 'BTC_DUMP', 'TREND_REVERSAL', 'PREMATURE_ENTRY', 'OTHER'].includes(item.failure_tag) && item.failure_tag}
|
| 516 |
+
</span>
|
| 517 |
+
)}
|
| 518 |
+
{item.holding_duration_seconds && item.holding_duration_seconds > 0 && (
|
| 519 |
+
<span className="text-[10px] font-mono text-purple-300/90 flex items-center gap-1 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20">
|
| 520 |
+
<Clock size={10} className="text-purple-400" />
|
| 521 |
+
{Math.floor(item.holding_duration_seconds / 3600) > 0
|
| 522 |
+
? `${Math.floor(item.holding_duration_seconds / 3600)}j ${Math.floor((item.holding_duration_seconds % 3600) / 60)}m`
|
| 523 |
+
: `${Math.floor(item.holding_duration_seconds / 60)}m`}
|
| 524 |
+
</span>
|
| 525 |
+
)}
|
| 526 |
+
{item.exit_price && (
|
| 527 |
+
<span className="text-[10px] font-mono text-emerald-300/90 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20">
|
| 528 |
+
Exit: ${item.exit_price.toLocaleString()}
|
| 529 |
+
</span>
|
| 530 |
+
)}
|
| 531 |
{item.audited && (
|
| 532 |
<span className="text-[9px] font-mono px-1.5 py-0.2 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">
|
| 533 |
Diaudit
|
|
|
|
| 601 |
</p>
|
| 602 |
)}
|
| 603 |
|
| 604 |
+
{/* ── Expandable Telemetry Drawer: Data Pasar Saat Rekomendasi ── */}
|
| 605 |
+
{item.snapshot_data && (
|
| 606 |
+
<div className="pt-1">
|
| 607 |
+
<button
|
| 608 |
+
type="button"
|
| 609 |
+
onClick={() => toggleTelemetry(item.id)}
|
| 610 |
+
className="w-full flex items-center justify-between px-3 py-2 rounded-lg bg-purple-950/20 hover:bg-purple-950/40 border border-purple-500/20 hover:border-purple-500/40 text-xs font-mono text-purple-300 transition-all shadow-sm"
|
| 611 |
+
>
|
| 612 |
+
<span className="flex items-center gap-1.5 font-bold">
|
| 613 |
+
<Activity size={13} className="text-purple-400" />
|
| 614 |
+
<span>Data Pasar Saat Rekomendasi (Telemetri Kuantitatif)</span>
|
| 615 |
+
</span>
|
| 616 |
+
<span className="flex items-center gap-1 text-[11px] text-text-muted">
|
| 617 |
+
{expandedTelemetry[item.id] ? 'Sembunyikan' : 'Buka Sidik Jari Pasar'}
|
| 618 |
+
{expandedTelemetry[item.id] ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
| 619 |
+
</span>
|
| 620 |
+
</button>
|
| 621 |
+
|
| 622 |
+
{expandedTelemetry[item.id] && (
|
| 623 |
+
<div className="mt-2 p-3.5 rounded-xl bg-bg-elevated/70 border border-purple-500/20 space-y-3 animate-fade-in text-xs font-mono">
|
| 624 |
+
<div className="flex items-center justify-between border-b border-border/50 pb-2">
|
| 625 |
+
<span className="text-[10px] uppercase font-bold tracking-wider text-purple-300 flex items-center gap-1">
|
| 626 |
+
<BarChart2 size={12} className="text-purple-400" />
|
| 627 |
+
Sidik Jari Pasar Mikrostruktur Pada Saat Entry
|
| 628 |
+
</span>
|
| 629 |
+
<span className="text-[10px] text-text-muted">
|
| 630 |
+
Model: {item.model_used || 'Damian Quant Engine'}
|
| 631 |
+
</span>
|
| 632 |
+
</div>
|
| 633 |
+
|
| 634 |
+
{/* 8-Grid Telemetry Matrix */}
|
| 635 |
+
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 text-[11px]">
|
| 636 |
+
{/* 1. Mark Price & 24H Range */}
|
| 637 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 638 |
+
<span className="text-[9px] text-text-muted block">MARK PRICE & 24H POS</span>
|
| 639 |
+
<div className="font-bold text-text-primary">
|
| 640 |
+
{item.snapshot_data.mark_price_str || (item.snapshot_data.mark_price ? `$${item.snapshot_data.mark_price}` : 'N/A')}
|
| 641 |
+
</div>
|
| 642 |
+
<div className="text-[10px] text-purple-300">
|
| 643 |
+
Posisi: {item.snapshot_data.range_position_pct ?? '50'}% ({item.snapshot_data.range_zone_label || 'Equilibrium'})
|
| 644 |
+
</div>
|
| 645 |
+
</div>
|
| 646 |
+
|
| 647 |
+
{/* 2. Order Flow CVD */}
|
| 648 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 649 |
+
<span className="text-[9px] text-text-muted block">ORDER FLOW CVD</span>
|
| 650 |
+
<div className="font-bold text-text-primary">
|
| 651 |
+
{item.snapshot_data.cvd_verdict || 'Netral'}
|
| 652 |
+
</div>
|
| 653 |
+
<div className="text-[10px] text-text-secondary truncate">
|
| 654 |
+
Spot: {item.snapshot_data.spot_cvd || '0'} | Fut: {item.snapshot_data.futures_cvd || '0'}
|
| 655 |
+
</div>
|
| 656 |
+
</div>
|
| 657 |
+
|
| 658 |
+
{/* 3. Funding & APR */}
|
| 659 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 660 |
+
<span className="text-[9px] text-text-muted block">FUNDING RATE 8H & APR</span>
|
| 661 |
+
<div className={`font-bold ${
|
| 662 |
+
(item.snapshot_data.avg_fr_8h_pct || 0) < 0 ? 'text-emerald-400' : 'text-rose-400'
|
| 663 |
+
}`}>
|
| 664 |
+
{item.snapshot_data.avg_fr_8h_pct !== undefined ? `${item.snapshot_data.avg_fr_8h_pct}%` : 'N/A'}{' '}
|
| 665 |
+
<span className="text-[9px] font-normal text-text-muted">
|
| 666 |
+
({item.snapshot_data.annualized_apr_pct !== undefined ? `${item.snapshot_data.annualized_apr_pct}% APR` : ''})
|
| 667 |
+
</span>
|
| 668 |
+
</div>
|
| 669 |
+
<div className="text-[10px] text-text-muted">
|
| 670 |
+
Settlement: {item.snapshot_data.funding_countdown || 'N/A'}
|
| 671 |
+
</div>
|
| 672 |
+
</div>
|
| 673 |
+
|
| 674 |
+
{/* 4. Orderbook Skew */}
|
| 675 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 676 |
+
<span className="text-[9px] text-text-muted block">ORDERBOOK SKEW (TOP 20)</span>
|
| 677 |
+
<div className="font-bold text-text-primary">
|
| 678 |
+
{item.snapshot_data.resting_pressure || 'Neutral'}{' '}
|
| 679 |
+
<span className="text-[9px] font-normal text-text-muted">
|
| 680 |
+
({item.snapshot_data.depth_ratio ? `${item.snapshot_data.depth_ratio}x` : '1.0x'})
|
| 681 |
+
</span>
|
| 682 |
+
</div>
|
| 683 |
+
<div className="text-[10px] text-text-muted truncate">
|
| 684 |
+
Bids ${Number(item.snapshot_data.bid_depth_usd || 0).toLocaleString()} vs Asks ${Number(item.snapshot_data.ask_depth_usd || 0).toLocaleString()}
|
| 685 |
+
</div>
|
| 686 |
+
</div>
|
| 687 |
+
|
| 688 |
+
{/* 5. MTF Trend Matrix */}
|
| 689 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 690 |
+
<span className="text-[9px] text-text-muted block">STRUKTUR MULTI-TIMEFRAME</span>
|
| 691 |
+
<div className="flex items-center gap-1 flex-wrap pt-0.5">
|
| 692 |
+
{['15m', '1h', '4h', '1d'].map((tf) => {
|
| 693 |
+
const tr = item.snapshot_data?.market_structure?.[tf] || 'neutral';
|
| 694 |
+
const isBull = tr.toLowerCase().includes('bull') || tr.toLowerCase().includes('uptrend');
|
| 695 |
+
const isBear = tr.toLowerCase().includes('bear') || tr.toLowerCase().includes('downtrend');
|
| 696 |
+
return (
|
| 697 |
+
<span
|
| 698 |
+
key={tf}
|
| 699 |
+
className={`px-1 py-0.2 rounded text-[9px] font-bold ${
|
| 700 |
+
isBull
|
| 701 |
+
? 'bg-emerald-500/20 text-emerald-300'
|
| 702 |
+
: isBear
|
| 703 |
+
? 'bg-rose-500/20 text-rose-300'
|
| 704 |
+
: 'bg-gray-500/20 text-gray-300'
|
| 705 |
+
}`}
|
| 706 |
+
>
|
| 707 |
+
{tf.toUpperCase()}:{tr.substring(0, 4).toUpperCase()}
|
| 708 |
+
</span>
|
| 709 |
+
);
|
| 710 |
+
})}
|
| 711 |
+
</div>
|
| 712 |
+
</div>
|
| 713 |
+
|
| 714 |
+
{/* 6. Volatility & Squeeze Radar */}
|
| 715 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 716 |
+
<span className="text-[9px] text-text-muted block">SQUEEZE & BREAKOUT RADAR</span>
|
| 717 |
+
<div className="font-bold text-purple-300">
|
| 718 |
+
{item.snapshot_data.squeeze_intensity || 'NORMAL'}{' '}
|
| 719 |
+
<span className="text-[9px] font-normal text-text-muted">
|
| 720 |
+
({item.snapshot_data.compression_ratio ? `CR: ${item.snapshot_data.compression_ratio}` : ''})
|
| 721 |
+
</span>
|
| 722 |
+
</div>
|
| 723 |
+
<div className="text-[10px] text-text-muted truncate">
|
| 724 |
+
Radar: {item.snapshot_data.breakout_radar?.radar_label || 'NORMAL'}
|
| 725 |
+
</div>
|
| 726 |
+
</div>
|
| 727 |
+
|
| 728 |
+
{/* 7. Whales & Lead-Lag */}
|
| 729 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 730 |
+
<span className="text-[9px] text-text-muted block">WHALES & LEAD-LAG</span>
|
| 731 |
+
<div className="font-bold text-text-primary">
|
| 732 |
+
Taker Buy: {item.snapshot_data.taker_buy_pct ?? 50}%
|
| 733 |
+
</div>
|
| 734 |
+
<div className="text-[10px] text-text-muted truncate">
|
| 735 |
+
Pemimpin: {item.snapshot_data.leading_exchange || 'N/A'}{' '}
|
| 736 |
+
{item.snapshot_data.lead_lag_spread_bps ? `(+${item.snapshot_data.lead_lag_spread_bps} bps)` : ''}
|
| 737 |
+
</div>
|
| 738 |
+
</div>
|
| 739 |
+
|
| 740 |
+
{/* 8. Confluence & Invalidation */}
|
| 741 |
+
<div className="p-2 rounded-lg bg-bg-card border border-border space-y-0.5">
|
| 742 |
+
<span className="text-[9px] text-text-muted block">KEYAKINAN & REZIM PASAR</span>
|
| 743 |
+
<div className="font-bold text-purple-200">
|
| 744 |
+
Conviction: {item.snapshot_data.conviction ?? 'N/A'}/10{' '}
|
| 745 |
+
<span className="text-[9px] font-normal text-text-muted">
|
| 746 |
+
({item.snapshot_data.confluence_pct ?? 'N/A'}%)
|
| 747 |
+
</span>
|
| 748 |
+
</div>
|
| 749 |
+
<div className="text-[10px] text-text-muted truncate">
|
| 750 |
+
Rezim: {item.snapshot_data.global_regime || 'NEUTRAL'}
|
| 751 |
+
</div>
|
| 752 |
+
</div>
|
| 753 |
+
</div>
|
| 754 |
+
|
| 755 |
+
{/* Invalidation Rule */}
|
| 756 |
+
{item.invalidation && (
|
| 757 |
+
<div className="p-2 rounded-lg bg-rose-500/10 border border-rose-500/20 text-[10px] text-rose-200 flex items-start gap-1.5">
|
| 758 |
+
<ShieldAlert size={12} className="text-rose-400 shrink-0 mt-0.5" />
|
| 759 |
+
<div>
|
| 760 |
+
<strong className="text-rose-300">Syarat Pembatalan (Invalidation Rule):</strong> {item.invalidation}
|
| 761 |
+
</div>
|
| 762 |
+
</div>
|
| 763 |
+
)}
|
| 764 |
+
|
| 765 |
+
{/* Active Warnings if any */}
|
| 766 |
+
{item.snapshot_data.warnings && item.snapshot_data.warnings.length > 0 && (
|
| 767 |
+
<div className="p-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-[10px] text-amber-200 flex items-start gap-1.5">
|
| 768 |
+
<AlertTriangle size={12} className="text-amber-400 shrink-0 mt-0.5" />
|
| 769 |
+
<div>
|
| 770 |
+
<strong className="text-amber-300">Peringatan Terdeteksi Saat Entry:</strong>{' '}
|
| 771 |
+
{item.snapshot_data.warnings.join(' • ')}
|
| 772 |
+
</div>
|
| 773 |
+
</div>
|
| 774 |
+
)}
|
| 775 |
+
</div>
|
| 776 |
+
)}
|
| 777 |
+
</div>
|
| 778 |
+
)}
|
| 779 |
+
|
| 780 |
{/* Interactive Status Confirmation Action Bar */}
|
| 781 |
<div className="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-border/50">
|
| 782 |
<span className="text-[11px] text-text-muted font-medium">
|
|
|
|
| 853 |
isOpen={Boolean(confirmModalData)}
|
| 854 |
onClose={() => setConfirmModalData(null)}
|
| 855 |
title={`Konfirmasi Hasil Trade: ${confirmModalData.entry.symbol}`}
|
| 856 |
+
size={confirmModalData.targetStatus === 'HIT_SL' ? 'md' : 'sm'}
|
| 857 |
>
|
| 858 |
<div className="space-y-3.5">
|
| 859 |
+
<div className="p-3 rounded-lg bg-bg-elevated border border-border text-xs space-y-1.5">
|
| 860 |
<div className="flex items-center justify-between">
|
| 861 |
<span className="text-text-muted">Pair & Bias:</span>
|
| 862 |
<span className="font-bold text-text-primary">
|
|
|
|
| 877 |
{confirmModalData.targetStatus}
|
| 878 |
</span>
|
| 879 |
</div>
|
| 880 |
+
<div className="flex items-center justify-between">
|
| 881 |
+
<span className="text-text-muted">Durasi Posisi Bertahan:</span>
|
| 882 |
+
<span className="font-bold font-mono text-purple-300 flex items-center gap-1">
|
| 883 |
+
<Clock size={11} className="text-purple-400" />
|
| 884 |
+
{calculateHoldingDuration(confirmModalData.entry.created_at).formatted}
|
| 885 |
+
</span>
|
| 886 |
+
</div>
|
| 887 |
+
</div>
|
| 888 |
+
|
| 889 |
+
{/* Failure Category Quick Selection (Critical for Damian RCA) */}
|
| 890 |
+
{confirmModalData.targetStatus === 'HIT_SL' && (
|
| 891 |
+
<div className="space-y-1.5">
|
| 892 |
+
<label className="block text-xs font-semibold text-rose-300">
|
| 893 |
+
⚡ Diagnosis Penyebab Stop Loss (Wajib untuk Pembelajaran Damian):
|
| 894 |
+
</label>
|
| 895 |
+
<div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
|
| 896 |
+
{FAILURE_TAGS.map((ft) => (
|
| 897 |
+
<button
|
| 898 |
+
key={ft.id}
|
| 899 |
+
type="button"
|
| 900 |
+
onClick={() => setFailureTag(ft.id)}
|
| 901 |
+
className={`p-2 rounded-lg text-left border transition-all ${
|
| 902 |
+
failureTag === ft.id
|
| 903 |
+
? 'bg-rose-500/20 border-rose-500 text-rose-200 font-bold shadow-sm'
|
| 904 |
+
: 'bg-bg-elevated/60 border-border/80 text-text-secondary hover:text-text-primary hover:border-border-hover'
|
| 905 |
+
}`}
|
| 906 |
+
>
|
| 907 |
+
<span className="block font-mono text-[11px] font-bold">{ft.label}</span>
|
| 908 |
+
<span className="text-[9px] text-text-muted block mt-0.5 line-clamp-1">{ft.desc}</span>
|
| 909 |
+
</button>
|
| 910 |
+
))}
|
| 911 |
+
</div>
|
| 912 |
+
</div>
|
| 913 |
+
)}
|
| 914 |
+
|
| 915 |
+
{/* Exit Price Input */}
|
| 916 |
+
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
| 917 |
+
<div>
|
| 918 |
+
<label className="block text-xs font-semibold text-text-secondary mb-1">
|
| 919 |
+
Harga Exit ({confirmModalData.targetStatus === 'HIT_SL' ? 'SL Hit' : 'TP Hit'}) — Opsional
|
| 920 |
+
</label>
|
| 921 |
+
<input
|
| 922 |
+
type="number"
|
| 923 |
+
step="any"
|
| 924 |
+
value={exitPrice}
|
| 925 |
+
onChange={(e) => setExitPrice(e.target.value)}
|
| 926 |
+
placeholder={confirmModalData.targetStatus === 'HIT_SL' ? 'e.g. 0.0868' : 'e.g. 0.1026'}
|
| 927 |
+
className="w-full px-2.5 py-1.5 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"
|
| 928 |
+
/>
|
| 929 |
+
</div>
|
| 930 |
+
<div>
|
| 931 |
+
<label className="block text-xs font-semibold text-text-secondary mb-1">
|
| 932 |
+
Level Invalidation Terpasang
|
| 933 |
+
</label>
|
| 934 |
+
<div className="px-2.5 py-1.5 rounded-lg bg-bg-elevated/50 border border-border text-xs text-text-muted font-mono truncate h-[34px] flex items-center">
|
| 935 |
+
{confirmModalData.entry.stop_loss || 'N/A'}
|
| 936 |
+
</div>
|
| 937 |
+
</div>
|
| 938 |
</div>
|
| 939 |
|
| 940 |
<div>
|
| 941 |
<label className="block text-xs font-semibold text-text-secondary mb-1">
|
| 942 |
+
Catatan Evaluasi Pribadi / Catatan Post-Mortem (Opsional)
|
| 943 |
</label>
|
| 944 |
<textarea
|
| 945 |
value={outcomeNote}
|
| 946 |
onChange={(e) => setOutcomeNote(e.target.value)}
|
| 947 |
+
placeholder="Contoh: Kena wick hunt pas settlement bursa jam 19:00, candle 1H langsung mantul kembali ke atas..."
|
| 948 |
rows={2}
|
| 949 |
className="w-full p-2.5 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500"
|
| 950 |
/>
|
frontend/src/types/index.ts
CHANGED
|
@@ -307,6 +307,9 @@ export interface TradeJournalEntry {
|
|
| 307 |
status: 'PENDING' | 'HIT_TP' | 'HIT_SL' | 'CANCELLED';
|
| 308 |
outcome_note?: string;
|
| 309 |
outcome_at?: string;
|
|
|
|
|
|
|
|
|
|
| 310 |
snapshot_data?: any;
|
| 311 |
audited: boolean;
|
| 312 |
created_at: string;
|
|
|
|
| 307 |
status: 'PENDING' | 'HIT_TP' | 'HIT_SL' | 'CANCELLED';
|
| 308 |
outcome_note?: string;
|
| 309 |
outcome_at?: string;
|
| 310 |
+
failure_tag?: string;
|
| 311 |
+
exit_price?: number;
|
| 312 |
+
holding_duration_seconds?: number;
|
| 313 |
snapshot_data?: any;
|
| 314 |
audited: boolean;
|
| 315 |
created_at: string;
|
tests/test_journal.py
CHANGED
|
@@ -49,3 +49,124 @@ def test_format_damian_memory_prompt():
|
|
| 49 |
assert len(mem_summaries) == 2
|
| 50 |
assert "Batch #1" in mem_summaries[0]
|
| 51 |
assert "Batch #2" in mem_summaries[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
assert len(mem_summaries) == 2
|
| 50 |
assert "Batch #1" in mem_summaries[0]
|
| 51 |
assert "Batch #2" in mem_summaries[1]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_format_failed_trade_dossier_rich_telemetry():
|
| 55 |
+
from routers.journal import _format_failed_trade_dossier
|
| 56 |
+
|
| 57 |
+
mock_failed_trade = {
|
| 58 |
+
"id": 42,
|
| 59 |
+
"symbol": "NILUSDT",
|
| 60 |
+
"bias": "STRONG LONG",
|
| 61 |
+
"entry_zone": "$0.0928-$0.0953",
|
| 62 |
+
"stop_loss": "$0.0870",
|
| 63 |
+
"take_profit": "TP1: $0.1026 | TP2: $0.1140",
|
| 64 |
+
"risk_reward": "1:2.4",
|
| 65 |
+
"leverage": "3x isolated",
|
| 66 |
+
"invalidation": "Batal jika candle 1H ditutup di bawah $0.0870",
|
| 67 |
+
"outcome_note": "Kena wick hunt pas settlement bursa jam 19:00",
|
| 68 |
+
"failure_tag": "WICK_HUNT",
|
| 69 |
+
"exit_price": 0.0868,
|
| 70 |
+
"holding_duration_seconds": 6300, # 1h 45m
|
| 71 |
+
"snapshot_data": {
|
| 72 |
+
"mark_price_str": "$0.0945",
|
| 73 |
+
"range_position_pct": 28.5,
|
| 74 |
+
"range_zone_label": "Value Area Low",
|
| 75 |
+
"spot_cvd": "+450,000",
|
| 76 |
+
"futures_cvd": "-120,000",
|
| 77 |
+
"cvd_verdict": "Spot Absorption Dominant",
|
| 78 |
+
"avg_fr_8h_pct": -0.0520,
|
| 79 |
+
"annualized_apr_pct": -56.94,
|
| 80 |
+
"triangulation_spread_pct": 0.12,
|
| 81 |
+
"resting_pressure": "Bid Dominant",
|
| 82 |
+
"depth_ratio": 1.85,
|
| 83 |
+
"bid_depth_usd": 2_100_000,
|
| 84 |
+
"ask_depth_usd": 1_135_000,
|
| 85 |
+
"squeeze_intensity": "READY_TO_BURST",
|
| 86 |
+
"compression_ratio": 0.48,
|
| 87 |
+
"breakout_radar": {"radar_label": "READY_TO_BURST (BULLISH)"},
|
| 88 |
+
"leading_exchange": "Bybit",
|
| 89 |
+
"lead_lag_spread_bps": 6.2,
|
| 90 |
+
"taker_buy_pct": 64.2,
|
| 91 |
+
"taker_ratio": 1.79,
|
| 92 |
+
"whale_buy_count": 8,
|
| 93 |
+
"whale_sell_count": 2,
|
| 94 |
+
"upper_magnet": "$0.1030",
|
| 95 |
+
"lower_magnet": "$0.0865",
|
| 96 |
+
"conviction": 8,
|
| 97 |
+
"confluence_pct": 82,
|
| 98 |
+
"market_structure": {
|
| 99 |
+
"15m": "bullish",
|
| 100 |
+
"1h": "bullish",
|
| 101 |
+
"4h": "bearish_pullback",
|
| 102 |
+
"1d": "neutral",
|
| 103 |
+
},
|
| 104 |
+
"warnings": ["Funding settlement countdown: 35 menit"],
|
| 105 |
+
},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
dossier = _format_failed_trade_dossier(1, mock_failed_trade)
|
| 109 |
+
|
| 110 |
+
# Assert all rich telemetry is present in the formatted string for Damian
|
| 111 |
+
assert "[NILUSDT] SETUP: STRONG LONG" in dossier
|
| 112 |
+
assert "Conviction: 8/10 | Confluence: 82%" in dossier
|
| 113 |
+
assert "Entry: $0.0928-$0.0953 | SL: $0.0870" in dossier
|
| 114 |
+
assert "Batal jika candle 1H ditutup di bawah $0.0870" in dossier
|
| 115 |
+
assert "Mark Price: $0.0945" in dossier
|
| 116 |
+
assert "Posisi 24H: 28.5% (Value Area Low)" in dossier
|
| 117 |
+
assert "1D: NEUTRAL | 4H: BEARISH_PULLBACK | 1H: BULLISH | 15M: BULLISH" in dossier
|
| 118 |
+
assert "Spot: +450,000 vs Futures: -120,000 -> Status: Spot Absorption Dominant" in dossier
|
| 119 |
+
assert "8H -0.0520% (Annualized -56.94% APR)" in dossier
|
| 120 |
+
assert "Tekanan Bid Dominant (Rasio Kedalaman: 1.85x)" in dossier
|
| 121 |
+
assert "READY_TO_BURST (Compression Ratio: 0.48)" in dossier
|
| 122 |
+
assert "Bybit memimpin (6.2 bps)" in dossier
|
| 123 |
+
assert "Kategori Diagnosis Trader: WICK_HUNT" in dossier
|
| 124 |
+
assert "Durasi Posisi Bertahan: 1j 45m" in dossier
|
| 125 |
+
assert "Perkiraan Harga Exit: $0.0868" in dossier
|
| 126 |
+
assert "Funding settlement countdown: 35 menit" in dossier
|
| 127 |
+
assert "Kena wick hunt pas settlement bursa jam 19:00" in dossier
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_update_trade_status_request_empty_strings():
|
| 131 |
+
from routers.journal import UpdateTradeStatusRequest
|
| 132 |
+
|
| 133 |
+
# Test that empty strings parse to None without raising ValidationError
|
| 134 |
+
req = UpdateTradeStatusRequest(
|
| 135 |
+
status="HIT_SL",
|
| 136 |
+
note="",
|
| 137 |
+
failure_tag="WICK_HUNT",
|
| 138 |
+
exit_price="",
|
| 139 |
+
holding_duration_seconds="",
|
| 140 |
+
)
|
| 141 |
+
assert req.exit_price is None
|
| 142 |
+
assert req.holding_duration_seconds is None
|
| 143 |
+
assert req.status == "HIT_SL"
|
| 144 |
+
|
| 145 |
+
# Test that valid numbers parse correctly
|
| 146 |
+
req2 = UpdateTradeStatusRequest(
|
| 147 |
+
status="HIT_TP",
|
| 148 |
+
exit_price="0.0950",
|
| 149 |
+
holding_duration_seconds="3600",
|
| 150 |
+
)
|
| 151 |
+
assert req2.exit_price == 0.095
|
| 152 |
+
assert req2.holding_duration_seconds == 3600
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_format_failed_trade_dossier_empty_snapshot_no_crash():
|
| 156 |
+
from routers.journal import _format_failed_trade_dossier
|
| 157 |
+
|
| 158 |
+
bare_trade = {
|
| 159 |
+
"id": 1,
|
| 160 |
+
"symbol": "BTCUSDT",
|
| 161 |
+
"bias": "LONG",
|
| 162 |
+
"snapshot_data": None,
|
| 163 |
+
"exit_price": None,
|
| 164 |
+
"holding_duration_seconds": None,
|
| 165 |
+
"outcome_note": None,
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
dossier = _format_failed_trade_dossier(1, bare_trade)
|
| 169 |
+
assert "[BTCUSDT] SETUP: LONG" in dossier
|
| 170 |
+
assert "Perkiraan Harga Exit: N/A (Tersentuh di level SL)" in dossier
|
| 171 |
+
assert "Durasi Posisi Bertahan: Tidak tercatat" in dossier
|
| 172 |
+
assert "Mark Price: N/A" in dossier
|