File size: 13,327 Bytes
3ac9172
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
b8b8f04
3ac9172
 
830e3f4
19a8045
830e3f4
 
 
b8b8f04
19a8045
b8b8f04
 
 
 
 
830e3f4
 
19a8045
830e3f4
 
 
 
 
9f701c8
830e3f4
 
 
 
 
 
 
 
19a8045
830e3f4
9f701c8
830e3f4
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
 
 
 
 
 
 
 
 
 
19a8045
830e3f4
19a8045
 
830e3f4
 
 
 
 
 
 
 
 
19a8045
 
 
 
830e3f4
 
 
 
 
 
 
8dd914e
 
19a8045
 
 
830e3f4
8dd914e
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b3da36
 
19a8045
 
 
b440fb9
19a8045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d84ff1
19a8045
 
 
3ac9172
 
 
830e3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9172
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<template>
  <div class="live">
    <!-- Toolbar: assets + mode -->
    <header class="toolbar">
      <div class="toolbar__left">
        <AssetTabs v-model="asset" :ordered-assets="orderedAssets" />
      </div>
      <div class="toolbar__right">
        <div class="mode">
          <button class="mode__btn" :class="{ 'is-active': mode==='usd' }" @click="mode='usd'">$</button>
          <button class="mode__btn" :class="{ 'is-active': mode==='pct' }" @click="mode='pct'">%</button>
        </div>
      </div>
    </header>

    <!-- Chart -->
    <section class="panel panel--chart">
      <CompareChartE
        v-if="winnersForChart.length"
        :selected="winnersForChart"
        :visible="true"
        :mode="mode"
      />
      <div v-else class="empty">
        No data for <strong>{{ asset }}</strong> yet. Check Supabase runs or try another asset.
      </div>
    </section>

    <!-- Cards: Buy & Hold + top 4 agents (computed with perf helpers) -->
    <section class="panel panel--cards" v-if="cards.length">
      <div class="cards5">
        <div
          v-for="c in cards"
          :key="c.key"
          class="card"
          :class="{ 'card--bh': c.kind==='bh', 'card--winner': c.isWinner }"
        >
          <!-- header: logo | title | balance -->
          <div class="card__header">
            <div class="card__logo">
              <img v-if="c.logo" :src="c.logo" alt="" />
              <div v-else class="card__logo-fallback"></div>
              <span v-if="c.isWinner" class="card__badge" aria-label="Top performer">πŸ‘‘</span>
            </div>

            <div class="card__title" :title="c.title">{{ c.title }}</div>
            <div class="card__balance">{{ fmtUSD(c.balance) }}</div>
          </div>

          <!-- meta row -->
          <div class="card__meta">
            <div class="card__sub ellipsize" :title="c.subtitle">{{ c.subtitle }}</div>

            <template v-if="c.kind==='agent' && c.gapUsd != null">
              <div class="pill" :class="{ neg: c.gapUsd < 0 && !c.isWinner, pos: c.gapUsd >= 0 || c.isWinner }">
                <span v-if="mode==='usd'">{{ signedMoney(c.gapUsd) }}</span>
                <span v-else>{{ signedPct(c.gapPct) }}</span>
              </div>
            </template>

            <template v-else>
              <div class="pill pill--neutral">Buy&nbsp;&amp;&nbsp;Hold</div>
            </template>
          </div>

          <!-- date row -->
          <div class="card__footer">
            <div class="card__sub">EOD {{ c.date ? new Date(c.date).toLocaleDateString() : '–' }}</div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch, shallowRef } from 'vue'
import AssetTabs from '../components/AssetTabs.vue'
import CompareChartE from '../components/CompareChartE.vue'
import { dataService } from '../lib/dataService'

/* β€”β€” same helpers as the chart β€”β€” */
import { getAllDecisions } from '../lib/dataCache'
import { readAllRawDecisions } from '../lib/idb'
import { filterRowsToNyseTradingDays } from '../lib/marketCalendar'
import { STRATEGIES } from '../lib/strategies'
import { computeBuyHoldEquity, computeStrategyEquity } from '../lib/perf'

/* ---------- config ---------- */
const orderedAssets = ['BTC','ETH','MSFT','BMRN','TSLA'] // MRNA removed
const EXCLUDED_AGENT_NAMES = new Set(['vanilla', 'vinilla']) // case-insensitive

// optional logos
const AGENT_LOGOS = {
  // 'DeepFundAgent': new URL('../assets/images/agents/deepfund.png', import.meta.url).href,
}
const ASSET_ICONS = {
  BTC: new URL('../assets/images/assets_images/BTC.png', import.meta.url).href,
  ETH: new URL('../assets/images/assets_images/ETH.png', import.meta.url).href,
  MSFT: new URL('../assets/images/assets_images/MSFT.png', import.meta.url).href,
  BMRN: new URL('../assets/images/assets_images/BMRN.png', import.meta.url).href,
  TSLA: new URL('../assets/images/assets_images/TSLA.png', import.meta.url).href,
}

/* match the chart’s cutoff so numbers align exactly */
const ASSET_CUTOFF = { BTC: '2025-08-01' }

/* ---------- state ---------- */
const mode = ref('usd') // 'usd' | 'pct'
const asset = ref('BTC')
const rowsRef = ref([])

let allDecisions = [] // decisions cache used for perf

/* ---------- bootstrap ---------- */
onMounted(async () => {
  try {
    if (!dataService.loaded && !dataService.loading) {
      await dataService.load(false)
    }
  } catch (e) {
    console.error('LiveView: dataService.load failed', e)
  }
  rowsRef.value = Array.isArray(dataService.tableRows) ? dataService.tableRows : []
  if (!orderedAssets.includes(asset.value)) asset.value = orderedAssets[0]

  // pull decisions used by chart
  allDecisions = getAllDecisions() || []
  if (!allDecisions.length) {
    try {
      const cached = await readAllRawDecisions()
      if (cached?.length) allDecisions = cached
    } catch {}
  }
  await nextTick()
})

/* ---------- helpers ---------- */
function score(row) {
  return typeof row.balance === 'number' ? row.balance : -Infinity
}
const fmtUSD = (n) => (n ?? 0).toLocaleString(undefined, { style: 'currency', currency: 'USD', maximumFractionDigits: 2 })
const signedMoney = (n) => `${n >= 0 ? '+' : 'βˆ’'}${fmtUSD(Math.abs(n))}`
const signedPct = (p) => `${(p >= 0 ? '+' : 'βˆ’')}${Math.abs(p * 100).toFixed(2)}%`

/* Selected-asset rows (exclude vanilla/vinilla) */
const filteredRows = computed(() =>
  (rowsRef.value || []).filter(r => {
    if (r.asset !== asset.value) return false
    const name = (r?.agent_name || '').toLowerCase()
    return !EXCLUDED_AGENT_NAMES.has(name)
  })
)

/* Best model per agent (by balance) β€” from leaderboard rows for winners list */
const winners = computed(() => {
  const byAgent = new Map()
  for (const r of filteredRows.value) {
    const k = r.agent_name
    const cur = byAgent.get(k)
    if (!cur || score(r) > score(cur)) byAgent.set(k, r)
  }
  return [...byAgent.values()]
})

/* Chart selections mirror winners */
const winnersForChart = computed(() =>
  winners.value.map(w => ({
    agent_name:  w.agent_name,
    asset:       w.asset,
    model:       w.model,
    strategy:    w.strategy,
    decision_ids: Array.isArray(w.decision_ids) ? w.decision_ids : undefined
  }))
)

/* ---------- PERF: compute B&H + strategy like the chart (ASYNC & SERIALIZED) ---------- */

/** async: build ordered decision seq for a selection (await calendar filter) */
async function buildSeq(sel) {
  const { agent_name: agent, asset, model } = sel
  const ids = Array.isArray(sel.decision_ids) ? sel.decision_ids : []
  let seq = ids.length
    ? allDecisions.filter(r => ids.includes(r.id))
    : allDecisions.filter(r => r.agent_name === agent && r.asset === asset && r.model === model)

  seq.sort((a, b) => (a.date > b.date ? 1 : -1))

  const isCrypto = asset === 'BTC' || asset === 'ETH'
  let filtered = seq
  if (!isCrypto) {
    filtered = await filterRowsToNyseTradingDays(seq) // ← await was missing before
  }

  const cutoff = ASSET_CUTOFF[asset]
  if (cutoff) {
    const t0 = new Date(cutoff + 'T00:00:00Z')
    filtered = filtered.filter(r => new Date(r.date + 'T00:00:00Z') >= t0)
  }
  return filtered
}

/** async: compute final equity & aligned B&H for a selection */
async function computeEquities(sel) {
  const seq = await buildSeq(sel)
  if (!seq.length) return null

  const cfg =
    (STRATEGIES || []).find(s => s.id === sel.strategy) ||
    { strategy: 'long_only', tradingMode: 'aggressive', fee: 0.0005 }

  const stratY = computeStrategyEquity(seq, 100000, cfg.fee, cfg.strategy, cfg.tradingMode) || []
  const bhY    = computeBuyHoldEquity(seq, 100000) || []

  const lastIdx = Math.min(stratY.length, bhY.length) - 1
  if (lastIdx < 0) return null

  return {
    date: seq[lastIdx].date,
    stratLast: stratY[lastIdx],
    bhLast: bhY[lastIdx],
  }
}

/* cards are computed via a serialized async watcher (avoid re-entrancy) */
const cards = shallowRef([])
let computing = false

watch(
  () => [asset.value, winnersForChart.value], // deps
  async () => {
    if (!allDecisions.length) { cards.value = []; return }
    if (computing) return
    computing = true
    try {
      const sels = winnersForChart.value || []
      if (!sels.length) { cards.value = []; return }

      // run all perf computations in parallel
      const perfs = (await Promise.all(
        sels.map(async sel => ({ sel, perf: await computeEquities(sel) }))
      )).filter(x => x.perf)

      if (!perfs.length) { cards.value = []; return }

      // B&H card: use first selection's BH (same asset & cutoff as chart)
      const assetCode = perfs[0].sel.asset
      const bhCard = {
        key: `bh|${assetCode}`,
        kind: 'bh',
        title: 'Buy & Hold',
        subtitle: assetCode,
        balance: perfs[0].perf.bhLast,
        date: perfs[0].perf.date,
        logo: ASSET_ICONS[assetCode] || null,
        isWinner: false
      }

      // Agent cards and winner flag
      const agentCards = perfs.map(({ sel, perf }) => {
        const gapUsd = perf.stratLast - perf.bhLast
        const gapPct = perf.bhLast > 0 ? (perf.stratLast / perf.bhLast - 1) : 0
        return {
          key: `agent|${sel.agent_name}|${sel.model}`,
          kind: 'agent',
          title: sel.agent_name,
          subtitle: sel.model,
          balance: perf.stratLast,
          date: perf.date,
          logo: AGENT_LOGOS[sel.agent_name] || null,
          gapUsd, gapPct,
          isWinner: false
        }
      })

      const maxBal = Math.max(...agentCards.map(c => c.balance ?? -Infinity))
      agentCards.forEach(c => { c.isWinner = c.balance === maxBal })

      // Top 4 agents + BH
      cards.value = [bhCard, ...agentCards.sort((a,b) => b.balance - a.balance).slice(0,4)]
    } catch (e) {
      console.error('LiveView: compute cards failed', e)
      cards.value = []
    } finally {
      computing = false
    }
  },
  { immediate: true, deep: true }
)
</script>

<style scoped>
.live { max-width: 1280px; margin: 0 auto; padding: 12px 20px 28px; }

/* toolbar */
.toolbar { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 8px 0 10px; background: #fff; }
.toolbar__left { min-width: 0; }
.toolbar__right { display: flex; align-items: center; gap: 10px; }

/* $/% toggle */
.mode { display: inline-flex; gap: 8px; }
.mode__btn { height: 32px; min-width: 40px; padding: 0 12px; border-radius: 10px; border: 1px solid #D6DAE1; background: #fff; font-weight: 700; color: #0F172A; transition: all .12s ease; }
.mode__btn:hover { transform: translateY(-1px); }
.mode__btn.is-active { background: #0F172A; color: #fff; border-color: #0F172A; }

/* panels */
.panel { background: #fff; border: 1px solid #EDF0F4; border-radius: 14px; }
.panel--chart { padding: 10px 10px 2px; }
.panel--cards { padding: 12px; }

/* empty */
.empty { padding: 14px; border: 1px dashed #D6DAE1; border-radius: 12px; color: #6B7280; font-size: .92rem; }

/* 5 cards in a row */
.cards5 { display: grid; gap: 12px; grid-template-columns: repeat(5, minmax(0, 1fr)); }
@media (max-width: 1200px) { .cards5 { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 720px)  { .cards5 { grid-template-columns: 1fr; } }

/* card */
.card { display: grid; grid-template-rows: auto auto auto; gap: 8px; padding: 12px 14px; border: 1px solid #EEF1F6; border-radius: 14px; background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.04); position: relative; }
.card--bh { outline: 2px dashed rgba(15,23,42,.08); }
.card--winner { border-color: #16a34a; box-shadow: 0 0 0 3px rgba(22,163,74,.12); }

/* header layout: logo | title | balance */
.card__header { display: grid; grid-template-columns: 52px minmax(0,1fr) auto; align-items: start; gap: 12px; }

/* logo */
.card__logo { width: 44px; height: 44px; border-radius: 999px; background: #F3F4F6; display: grid; place-items: center; overflow: hidden; position: relative; }
.card__logo img { width: 100%; height: 100%; object-fit: contain; }
.card__logo-fallback { width: 60%; height: 60%; border-radius: 999px; background: #E5E7EB; }
.card__badge { position: absolute; right: -6px; top: -6px; font-size: 16px; filter: drop-shadow(0 1px 1px rgba(0,0,0,.15)); }

/* title: clamp to 2 lines so balance never overlaps */
.card__title {
  min-width: 0; font-weight: 800; color: #0F172A;
  white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
  overflow: hidden; line-height: 1.15;
}

/* right-side balance never shrinks */
.card__balance { white-space: nowrap; font-weight: 900; color: #0F172A; font-size: 20px; }

/* meta row + footer */
.card__meta { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.card__sub { font-size: 12px; color: #5B6476; opacity: .85; }
.ellipsize { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card__footer { margin-top: -2px; }

/* pills */
.pill { padding: 4px 9px; border-radius: 999px; font-size: 12px; font-weight: 800; line-height: 1; white-space: nowrap; background: #EEF2F7; color: #0F172A; }
.pill.neg { background: #FEE2E2; color: #B91C1C; }
.pill.pos { background: #DCFCE7; color: #166534; }
.pill.pill--neutral { background: #EEF2F7; color: #0F172A; }
</style>