diff --git a/cumulative.go b/cumulative.go index 2029fe1..18c64f1 100644 --- a/cumulative.go +++ b/cumulative.go @@ -22,6 +22,21 @@ type exChange struct { change float64 } +// shortExName maps full exchange names to short prefixes for JSON keys. +func shortExName(name string) string { + switch name { + case ExBitget: + return "bg" + case ExHyperLiquid: + return "hl" + case ExBinance: + return "bn" + case ExOKX: + return "okx" + } + return name +} + // CmEvent records a cumulative move state transition, persisted to DB. type CmEvent struct { Coin string `json:"coin"` @@ -50,7 +65,7 @@ type cmSnapshot struct { } // CumulativeTracker monitors multi-exchange cumulative price changes. -// Takes 1-second snapshots, computes 1m/5m changes, detects consensus surges. +// Takes 1-second snapshots, computes 1m/5m/1h changes, detects consensus surges. type CumulativeTracker struct { mu sync.RWMutex coins map[string][]cmSnapshot // coin → ring buffer of snapshots @@ -68,6 +83,7 @@ type CumulativeTracker struct { minExchanges int // need at least this many exchanges with data (default: 3) surgePct1m float64 // 1m change% threshold to trigger (default: 0.5%) surgePct5m float64 // 5m change% threshold to trigger (default: 1.0%) + surgePct1h float64 // 1h change% threshold to trigger (default: 2.0%) // Event history (in-memory ring buffer) events [maxTrendEvents]CmEvent @@ -86,10 +102,11 @@ func NewCumulativeTracker() *CumulativeTracker { counts: make(map[string]int), states: make(map[string]CmState), prevState: make(map[string]CmState), - maxSnapshots: 300, // 5min at 1s + maxSnapshots: 3600, // 1h at 1s minExchanges: 3, surgePct1m: 0.5, // 0.5% in 1min surgePct5m: 1.0, // 1.0% in 5min + surgePct1h: 2.0, // 2.0% in 1h } } @@ -99,27 +116,40 @@ func (ct *CumulativeTracker) Record(coin string, prices map[string]float64) { ct.mu.Lock() defer ct.mu.Unlock() - snap := cmSnapshot{ - time: time.Now().UnixMilli(), - prices: prices, - } + now := time.Now().UnixMilli() - // Initialize buffer if needed + // Initialize buffer if needed — pre-fill entire ring buffer with this price + // so 1m/5m/1h windows show 0% immediately instead of waiting for data. if ct.coins[coin] == nil { ct.coins[coin] = make([]cmSnapshot, ct.maxSnapshots) ct.heads[coin] = 0 - ct.counts[coin] = 0 + ct.counts[coin] = ct.maxSnapshots // mark as full ct.states[coin] = CmNeutral ct.prevState[coin] = CmNeutral + + startTime := now - int64(ct.maxSnapshots-1)*1000 + for i := 0; i < ct.maxSnapshots; i++ { + ct.coins[coin][i] = cmSnapshot{ + time: startTime + int64(i)*1000, + prices: prices, + } + } + return } + // Deduplicate: skip if last snapshot is less than 1 second old buf := ct.coins[coin] head := ct.heads[coin] - buf[head] = snap - ct.heads[coin] = (head + 1) % ct.maxSnapshots - if ct.counts[coin] < ct.maxSnapshots { - ct.counts[coin]++ + prevIdx := (head - 1 + ct.maxSnapshots) % ct.maxSnapshots + if buf[prevIdx].time > now-1000 { + return } + + buf[head] = cmSnapshot{ + time: now, + prices: prices, + } + ct.heads[coin] = (head + 1) % ct.maxSnapshots } // GetCurrent returns current cumulative change info for all coins, sorted by score desc. @@ -146,12 +176,13 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { continue } - // Find snapshots from ~60s ago and ~300s ago + // Find snapshots from ~60s ago, ~300s ago, and ~3600s ago now := current.time oneMinAgo := now - 60000 fiveMinAgo := now - 300000 - var snap1m, snap5m *cmSnapshot - var found1m, found5m bool + oneHourAgo := now - 3600000 + var snap1m, snap5m, snap1h *cmSnapshot + var found1m, found5m, found1h bool // Walk backwards from current to find closest snapshots for i := 0; i < count && i < ct.maxSnapshots; i++ { @@ -168,14 +199,18 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { snap5m = s found5m = true } + if !found1h && s.time <= oneHourAgo { + snap1h = s + found1h = true + } } if !found1m { // Use oldest available as 1m approximation continue } - // Compute 1m changes per exchange - var changes1m, changes5m []exChange + // Compute 1m/5m/1h changes per exchange + var changes1m, changes5m, changes1h []exChange for ex, curP := range current.prices { if curP <= 0 { @@ -191,6 +226,12 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { changes5m = append(changes5m, exChange{name: ex, change: chg}) } } + if found1h && snap1h != nil { + if oldP, ok := snap1h.prices[ex]; ok && oldP > 0 { + chg := (curP - oldP) / oldP * 100 + changes1h = append(changes1h, exChange{name: ex, change: chg}) + } + } } if len(changes1m) < ct.minExchanges { @@ -198,9 +239,10 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { } // Compute averages and agreement - var sum1m, sum5m float64 + var sum1m, sum5m, sum1h float64 agreeUp1m, agreeDown1m := 0, 0 agreeUp5m, agreeDown5m := 0, 0 + agreeUp1h, agreeDown1h := 0, 0 for _, c := range changes1m { sum1m += c.change @@ -220,11 +262,24 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { } } + for _, c := range changes1h { + sum1h += c.change + if c.change > 0.01 { + agreeUp1h++ + } else if c.change < -0.01 { + agreeDown1h++ + } + } + avg1m := sum1m / float64(len(changes1m)) var avg5m float64 if len(changes5m) >= ct.minExchanges { avg5m = sum5m / float64(len(changes5m)) } + var avg1h float64 + if len(changes1h) >= ct.minExchanges { + avg1h = sum1h / float64(len(changes1h)) + } // Determine direction and agreement majorityDir := "up" @@ -242,19 +297,25 @@ func (ct *CumulativeTracker) GetCurrent() []map[string]interface{} { "coin": coin, "avg_1m": math.Round(avg1m*10000) / 10000, "avg_5m": math.Round(avg5m*10000) / 10000, + "avg_1h": math.Round(avg1h*10000) / 10000, "score": math.Round(score*100) / 100, "direction": majorityDir, "ex_agree": majority, "ex_total": len(changes1m), } - // Individual exchange changes + // Individual exchange changes (using short names: bg, hl, bn, okx) for _, c := range changes1m { - entry[c.name+"_1m"] = math.Round(c.change*10000) / 10000 + entry[shortExName(c.name)+"_1m"] = math.Round(c.change*10000) / 10000 } if len(changes5m) >= ct.minExchanges { for _, c := range changes5m { - entry[c.name+"_5m"] = math.Round(c.change*10000) / 10000 + entry[shortExName(c.name)+"_5m"] = math.Round(c.change*10000) / 10000 + } + } + if len(changes1h) >= ct.minExchanges { + for _, c := range changes1h { + entry[shortExName(c.name)+"_1h"] = math.Round(c.change*10000) / 10000 } } diff --git a/dashboard.go b/dashboard.go index 27953f3..b85c38c 100644 --- a/dashboard.go +++ b/dashboard.go @@ -208,9 +208,12 @@ type Dashboard struct { // Cumulative tracker (1m/5m multi-exchange consensus) cumulativeTracker *CumulativeTracker + + // Trend filter (K-line based quiet + EMA filter) + trendFilter *TrendFilter } -func NewDashboard(store *PriceStore, trader *Trader, database *db.DB, addr string, cfg *Config, momentumTracker *MomentumTracker, trendDetector *TrendDetector, cumulativeTracker *CumulativeTracker) *Dashboard { +func NewDashboard(store *PriceStore, trader *Trader, database *db.DB, addr string, cfg *Config, momentumTracker *MomentumTracker, trendDetector *TrendDetector, cumulativeTracker *CumulativeTracker, trendFilter *TrendFilter) *Dashboard { d := &Dashboard{ hub: NewSSEHub(), history: newPriceHistory(), @@ -224,6 +227,7 @@ func NewDashboard(store *PriceStore, trader *Trader, database *db.DB, addr strin momentumTracker: momentumTracker, trendDetector: trendDetector, cumulativeTracker: cumulativeTracker, + trendFilter: trendFilter, } // Wire trend event persistence to SQLite @@ -235,6 +239,13 @@ func NewDashboard(store *PriceStore, trader *Trader, database *db.DB, addr strin } } + // Wire trend filter signal broadcast via SSE + if trendFilter != nil { + trendFilter.OnNewSignal = func(sig TrendSignal) { + d.hub.Broadcast("trend_signal", sig) + } + } + // Wire cumulative event persistence to SQLite if cumulativeTracker != nil && database != nil { cumulativeTracker.OnEvent = func(ev CmEvent) { @@ -276,6 +287,7 @@ func (d *Dashboard) Run() { mux.HandleFunc("GET /api/connections", d.handleConnStatus) // P3-5 mux.HandleFunc("GET /api/trend-history", d.handleTrendHistory) mux.HandleFunc("GET /api/cm-history", d.handleCmHistory) + mux.HandleFunc("GET /api/trend-signals", d.handleTrendSignals) mux.HandleFunc("GET /events", d.handleSSE) mux.HandleFunc("POST /api/stop", d.handleStop) mux.HandleFunc("POST /api/start", d.handleStart) @@ -597,6 +609,15 @@ func (d *Dashboard) broadcastLoop() { d.hub.Broadcast("cumulative", cmData) } } + + // 8. Trend filter (K-line based quiet + EMA) + if d.trendFilter != nil { + d.trendFilter.Tick() + filterData := d.trendFilter.Snapshot(0) + if len(filterData) > 0 { + d.hub.Broadcast("trend_filter", filterData) + } + } } } @@ -764,6 +785,17 @@ func (d *Dashboard) handleCmHistory(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]interface{}{"events": events}) } +func (d *Dashboard) handleTrendSignals(w http.ResponseWriter, r *http.Request) { + var signals []TrendSignal + if d.trendFilter != nil { + signals = d.trendFilter.GetSignals(100) + } + if signals == nil { + signals = []TrendSignal{} + } + writeJSON(w, map[string]interface{}{"signals": signals}) +} + func (d *Dashboard) handleTrades(w http.ResponseWriter, r *http.Request) { if d.db == nil { writeJSON(w, map[string]interface{}{"trades": []interface{}{}, "total": 0}) diff --git a/db/db.go b/db/db.go index ef60939..16a37ed 100644 --- a/db/db.go +++ b/db/db.go @@ -150,6 +150,24 @@ func (d *DB) migrate() error { ); CREATE INDEX IF NOT EXISTS idx_cm_events_coin ON cm_events(coin); CREATE INDEX IF NOT EXISTS idx_cm_events_created ON cm_events(created_at); + + CREATE TABLE IF NOT EXISTS trend_signals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + coin TEXT NOT NULL, + type TEXT NOT NULL, + signal_score REAL, + price REAL, + ema_52 REAL, + ema_slope REAL, + volume_ratio REAL, + range_24h REAL, + vol_baseline REAL, + price_above_ema INTEGER, + state TEXT, + created_at DATETIME NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_trend_signals_coin ON trend_signals(coin); + CREATE INDEX IF NOT EXISTS idx_trend_signals_created ON trend_signals(created_at); ` _, err := d.Exec(schema) if err != nil { diff --git a/db/trend_signal.go b/db/trend_signal.go new file mode 100644 index 0000000..7487afc --- /dev/null +++ b/db/trend_signal.go @@ -0,0 +1,64 @@ +package db + +import "time" + +// TrendSignalRecord mirrors the trend_signals table row. +type TrendSignalRecord struct { + ID int64 + Coin string + Type string // "enter" or "exit" + SignalScore *float64 + Price *float64 + EMA52 *float64 + EMASlope *float64 + VolumeRatio *float64 + Range24h *float64 + VolBaseline *float64 + PriceAboveEMA bool + State *string + CreatedAt time.Time +} + +// SaveTrendSignal inserts a new trend signal record. +func (d *DB) SaveTrendSignal(s *TrendSignalRecord) (int64, error) { + pa := 0 + if s.PriceAboveEMA { + pa = 1 + } + res, err := d.Exec(`INSERT INTO trend_signals + (coin, type, signal_score, price, ema_52, ema_slope, volume_ratio, + range_24h, vol_baseline, price_above_ema, state, created_at) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`, + s.Coin, s.Type, s.SignalScore, s.Price, s.EMA52, s.EMASlope, s.VolumeRatio, + s.Range24h, s.VolBaseline, pa, s.State, s.CreatedAt, + ) + if err != nil { + return 0, err + } + return res.LastInsertId() +} + +// GetTrendSignals returns the most recent N trend signal records. +func (d *DB) GetTrendSignals(limit int) ([]TrendSignalRecord, error) { + rows, err := d.Query(`SELECT id, coin, type, signal_score, price, ema_52, ema_slope, + volume_ratio, range_24h, vol_baseline, price_above_ema, state, created_at + FROM trend_signals ORDER BY id DESC LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + + var signals []TrendSignalRecord + for rows.Next() { + var s TrendSignalRecord + var pa int + if err := rows.Scan(&s.ID, &s.Coin, &s.Type, &s.SignalScore, &s.Price, + &s.EMA52, &s.EMASlope, &s.VolumeRatio, &s.Range24h, &s.VolBaseline, + &pa, &s.State, &s.CreatedAt); err != nil { + return nil, err + } + s.PriceAboveEMA = pa == 1 + signals = append(signals, s) + } + return signals, rows.Err() +} diff --git a/frontend/dist/assets/index-B9OruCsy.js b/frontend/dist/assets/index-B9OruCsy.js new file mode 100644 index 0000000..7135033 --- /dev/null +++ b/frontend/dist/assets/index-B9OruCsy.js @@ -0,0 +1,40 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();function dc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jo={exports:{}},ul={},qo={exports:{}},D={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var rr=Symbol.for("react.element"),fc=Symbol.for("react.portal"),hc=Symbol.for("react.fragment"),pc=Symbol.for("react.strict_mode"),mc=Symbol.for("react.profiler"),gc=Symbol.for("react.provider"),xc=Symbol.for("react.context"),vc=Symbol.for("react.forward_ref"),yc=Symbol.for("react.suspense"),jc=Symbol.for("react.memo"),wc=Symbol.for("react.lazy"),Bs=Symbol.iterator;function Sc(e){return e===null||typeof e!="object"?null:(e=Bs&&e[Bs]||e["@@iterator"],typeof e=="function"?e:null)}var bo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},eu=Object.assign,tu={};function mn(e,t,n){this.props=e,this.context=t,this.refs=tu,this.updater=n||bo}mn.prototype.isReactComponent={};mn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};mn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function nu(){}nu.prototype=mn.prototype;function Ki(e,t,n){this.props=e,this.context=t,this.refs=tu,this.updater=n||bo}var Xi=Ki.prototype=new nu;Xi.constructor=Ki;eu(Xi,mn.prototype);Xi.isPureReactComponent=!0;var Hs=Array.isArray,ru=Object.prototype.hasOwnProperty,Gi={current:null},lu={key:!0,ref:!0,__self:!0,__source:!0};function iu(e,t,n){var r,l={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)ru.call(t,r)&&!lu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1>>1,J=k[A];if(0>>1;Al(vn,T))Yel(L,vn)?(k[A]=L,k[Ye]=T,A=Ye):(k[A]=vn,k[Ge]=T,A=Ge);else if(Yel(L,T))k[A]=L,k[Ye]=T,A=Ye;else break e}}return P}function l(k,P){var T=k.sortIndex-P.sortIndex;return T!==0?T:k.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,u=o.now();e.unstable_now=function(){return o.now()-u}}var c=[],a=[],f=1,d=null,g=3,v=!1,x=!1,w=!1,R=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,h=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(k){for(var P=n(a);P!==null;){if(P.callback===null)r(a);else if(P.startTime<=k)r(a),P.sortIndex=P.expirationTime,t(c,P);else break;P=n(a)}}function y(k){if(w=!1,m(k),!x)if(n(c)!==null)x=!0,de(S);else{var P=n(a);P!==null&&fe(y,P.startTime-k)}}function S(k,P){x=!1,w&&(w=!1,p(E),E=-1),v=!0;var T=g;try{for(m(P),d=n(c);d!==null&&(!(d.expirationTime>P)||k&&!re());){var A=d.callback;if(typeof A=="function"){d.callback=null,g=d.priorityLevel;var J=A(d.expirationTime<=P);P=e.unstable_now(),typeof J=="function"?d.callback=J:d===n(c)&&r(c),m(P)}else r(c);d=n(c)}if(d!==null)var Bt=!0;else{var Ge=n(a);Ge!==null&&fe(y,Ge.startTime-P),Bt=!1}return Bt}finally{d=null,g=T,v=!1}}var _=!1,C=null,E=-1,$=5,F=-1;function re(){return!(e.unstable_now()-F<$)}function Pe(){if(C!==null){var k=e.unstable_now();F=k;var P=!0;try{P=C(!0,k)}finally{P?He():(_=!1,C=null)}}else _=!1}var He;if(typeof h=="function")He=function(){h(Pe)};else if(typeof MessageChannel<"u"){var Ct=new MessageChannel,M=Ct.port2;Ct.port1.onmessage=Pe,He=function(){M.postMessage(null)}}else He=function(){R(Pe,0)};function de(k){C=k,_||(_=!0,He())}function fe(k,P){E=R(function(){k(e.unstable_now())},P)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(k){k.callback=null},e.unstable_continueExecution=function(){x||v||(x=!0,de(S))},e.unstable_forceFrameRate=function(k){0>k||125A?(k.sortIndex=T,t(a,k),n(c)===null&&k===n(a)&&(w?(p(E),E=-1):w=!0,fe(y,T-A))):(k.sortIndex=J,t(c,k),x||v||(x=!0,de(S))),k},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(k){var P=g;return function(){var T=g;g=P;try{return k.apply(this,arguments)}finally{g=T}}}})(cu);au.exports=cu;var Oc=au.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Rc=z,Ne=Oc;function j(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ql=Object.prototype.hasOwnProperty,Mc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Vs={},Qs={};function Ic(e){return ql.call(Qs,e)?!0:ql.call(Vs,e)?!1:Mc.test(e)?Qs[e]=!0:(Vs[e]=!0,!1)}function $c(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Uc(e,t,n,r){if(t===null||typeof t>"u"||$c(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ge(e,t,n,r,l,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var se={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){se[e]=new ge(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];se[t]=new ge(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){se[e]=new ge(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){se[e]=new ge(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){se[e]=new ge(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){se[e]=new ge(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){se[e]=new ge(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){se[e]=new ge(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){se[e]=new ge(e,5,!1,e.toLowerCase(),null,!1,!1)});var Zi=/[\-:]([a-z])/g;function Ji(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Zi,Ji);se[t]=new ge(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Zi,Ji);se[t]=new ge(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Zi,Ji);se[t]=new ge(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){se[e]=new ge(e,1,!1,e.toLowerCase(),null,!1,!1)});se.xlinkHref=new ge("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){se[e]=new ge(e,1,!1,e.toLowerCase(),null,!0,!0)});function qi(e,t,n,r){var l=se.hasOwnProperty(t)?se[t]:null;(l!==null?l.type!==0:r||!(2u||l[o]!==i[u]){var c=` +`+l[o].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=o&&0<=u);break}}}finally{El=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?En(e):""}function Ac(e){switch(e.tag){case 5:return En(e.type);case 16:return En("Lazy");case 13:return En("Suspense");case 19:return En("SuspenseList");case 0:case 2:case 15:return e=Pl(e.type,!1),e;case 11:return e=Pl(e.type.render,!1),e;case 1:return e=Pl(e.type,!0),e;default:return""}}function ni(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Vt:return"Fragment";case Wt:return"Portal";case bl:return"Profiler";case bi:return"StrictMode";case ei:return"Suspense";case ti:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case hu:return(e.displayName||"Context")+".Consumer";case fu:return(e._context.displayName||"Context")+".Provider";case es:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ts:return t=e.displayName||null,t!==null?t:ni(e.type)||"Memo";case ot:t=e._payload,e=e._init;try{return ni(e(t))}catch{}}return null}function Bc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ni(t);case 8:return t===bi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function mu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Hc(e){var t=mu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function dr(e){e._valueTracker||(e._valueTracker=Hc(e))}function gu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=mu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function $r(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function ri(e,t){var n=t.checked;return G({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xs(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function xu(e,t){t=t.checked,t!=null&&qi(e,"checked",t,!1)}function li(e,t){xu(e,t);var n=wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ii(e,t.type,n):t.hasOwnProperty("defaultValue")&&ii(e,t.type,wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Gs(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ii(e,t,n){(t!=="number"||$r(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Pn=Array.isArray;function tn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=fr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Fn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Wc=["Webkit","ms","Moz","O"];Object.keys(Fn).forEach(function(e){Wc.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Fn[t]=Fn[e]})});function wu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Fn.hasOwnProperty(e)&&Fn[e]?(""+t).trim():t+"px"}function Su(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=wu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Vc=G({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ui(e,t){if(t){if(Vc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(j(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(j(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(j(61))}if(t.style!=null&&typeof t.style!="object")throw Error(j(62))}}function ai(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ci=null;function ns(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var di=null,nn=null,rn=null;function Js(e){if(e=sr(e)){if(typeof di!="function")throw Error(j(280));var t=e.stateNode;t&&(t=hl(t),di(e.stateNode,e.type,t))}}function ku(e){nn?rn?rn.push(e):rn=[e]:nn=e}function _u(){if(nn){var e=nn,t=rn;if(rn=nn=null,Js(e),t)for(e=0;e>>=0,e===0?32:31-(td(e)/nd|0)|0}var hr=64,pr=4194304;function zn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Hr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var u=o&~l;u!==0?r=zn(u):(i&=o,i!==0&&(r=zn(i)))}else o=n&~l,o!==0?r=zn(o):i!==0&&(r=zn(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function lr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ue(t),e[t]=n}function sd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Dn),so=" ",oo=!1;function Vu(e,t){switch(e){case"keyup":return Od.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Qu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Qt=!1;function Md(e,t){switch(e){case"compositionend":return Qu(t);case"keypress":return t.which!==32?null:(oo=!0,so);case"textInput":return e=t.data,e===so&&oo?null:e;default:return null}}function Id(e,t){if(Qt)return e==="compositionend"||!cs&&Vu(e,t)?(e=Hu(),zr=os=dt=null,Qt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=fo(n)}}function Yu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Yu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Zu(){for(var e=window,t=$r();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=$r(e.document)}return t}function ds(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Kd(e){var t=Zu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Yu(n.ownerDocument.documentElement,n)){if(r!==null&&ds(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=ho(n,i);var o=ho(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Kt=null,xi=null,Rn=null,vi=!1;function po(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;vi||Kt==null||Kt!==$r(r)||(r=Kt,"selectionStart"in r&&ds(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Rn&&Xn(Rn,r)||(Rn=r,r=Qr(xi,"onSelect"),0Yt||(e.current=_i[Yt],_i[Yt]=null,Yt--)}function U(e,t){Yt++,_i[Yt]=e.current,e.current=t}var St={},ce=_t(St),ye=_t(!1),Ot=St;function an(e,t){var n=e.type.contextTypes;if(!n)return St;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function je(e){return e=e.childContextTypes,e!=null}function Xr(){W(ye),W(ce)}function wo(e,t,n){if(ce.current!==St)throw Error(j(168));U(ce,t),U(ye,n)}function ia(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(j(108,Bc(e)||"Unknown",l));return G({},n,r)}function Gr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||St,Ot=ce.current,U(ce,e),U(ye,ye.current),!0}function So(e,t,n){var r=e.stateNode;if(!r)throw Error(j(169));n?(e=ia(e,t,Ot),r.__reactInternalMemoizedMergedChildContext=e,W(ye),W(ce),U(ce,e)):W(ye),U(ye,n)}var Je=null,pl=!1,Hl=!1;function sa(e){Je===null?Je=[e]:Je.push(e)}function lf(e){pl=!0,sa(e)}function Nt(){if(!Hl&&Je!==null){Hl=!0;var e=0,t=I;try{var n=Je;for(I=1;e>=o,l-=o,qe=1<<32-Ue(t)+l|n<E?($=C,C=null):$=C.sibling;var F=g(p,C,m[E],y);if(F===null){C===null&&(C=$);break}e&&C&&F.alternate===null&&t(p,C),h=i(F,h,E),_===null?S=F:_.sibling=F,_=F,C=$}if(E===m.length)return n(p,C),Q&&Et(p,E),S;if(C===null){for(;EE?($=C,C=null):$=C.sibling;var re=g(p,C,F.value,y);if(re===null){C===null&&(C=$);break}e&&C&&re.alternate===null&&t(p,C),h=i(re,h,E),_===null?S=re:_.sibling=re,_=re,C=$}if(F.done)return n(p,C),Q&&Et(p,E),S;if(C===null){for(;!F.done;E++,F=m.next())F=d(p,F.value,y),F!==null&&(h=i(F,h,E),_===null?S=F:_.sibling=F,_=F);return Q&&Et(p,E),S}for(C=r(p,C);!F.done;E++,F=m.next())F=v(C,p,E,F.value,y),F!==null&&(e&&F.alternate!==null&&C.delete(F.key===null?E:F.key),h=i(F,h,E),_===null?S=F:_.sibling=F,_=F);return e&&C.forEach(function(Pe){return t(p,Pe)}),Q&&Et(p,E),S}function R(p,h,m,y){if(typeof m=="object"&&m!==null&&m.type===Vt&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case cr:e:{for(var S=m.key,_=h;_!==null;){if(_.key===S){if(S=m.type,S===Vt){if(_.tag===7){n(p,_.sibling),h=l(_,m.props.children),h.return=p,p=h;break e}}else if(_.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===ot&&No(S)===_.type){n(p,_.sibling),h=l(_,m.props),h.ref=_n(p,_,m),h.return=p,p=h;break e}n(p,_);break}else t(p,_);_=_.sibling}m.type===Vt?(h=Dt(m.props.children,p.mode,y,m.key),h.return=p,p=h):(y=Ir(m.type,m.key,m.props,null,p.mode,y),y.ref=_n(p,h,m),y.return=p,p=y)}return o(p);case Wt:e:{for(_=m.key;h!==null;){if(h.key===_)if(h.tag===4&&h.stateNode.containerInfo===m.containerInfo&&h.stateNode.implementation===m.implementation){n(p,h.sibling),h=l(h,m.children||[]),h.return=p,p=h;break e}else{n(p,h);break}else t(p,h);h=h.sibling}h=Zl(m,p.mode,y),h.return=p,p=h}return o(p);case ot:return _=m._init,R(p,h,_(m._payload),y)}if(Pn(m))return x(p,h,m,y);if(yn(m))return w(p,h,m,y);wr(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,h!==null&&h.tag===6?(n(p,h.sibling),h=l(h,m),h.return=p,p=h):(n(p,h),h=Yl(m,p.mode,y),h.return=p,p=h),o(p)):n(p,h)}return R}var dn=ca(!0),da=ca(!1),Jr=_t(null),qr=null,qt=null,ms=null;function gs(){ms=qt=qr=null}function xs(e){var t=Jr.current;W(Jr),e._currentValue=t}function Ei(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function sn(e,t){qr=e,ms=qt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ve=!0),e.firstContext=null)}function De(e){var t=e._currentValue;if(ms!==e)if(e={context:e,memoizedValue:t,next:null},qt===null){if(qr===null)throw Error(j(308));qt=e,qr.dependencies={lanes:0,firstContext:e}}else qt=qt.next=e;return t}var Tt=null;function vs(e){Tt===null?Tt=[e]:Tt.push(e)}function fa(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,vs(t)):(n.next=l.next,l.next=n),t.interleaved=n,rt(e,r)}function rt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var ut=!1;function ys(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ha(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function et(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function xt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,O&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,rt(e,n)}return l=r.interleaved,l===null?(t.next=t,vs(r)):(t.next=l.next,l.next=t),r.interleaved=t,rt(e,n)}function Fr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ls(e,n)}}function Co(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function br(e,t,n,r){var l=e.updateQueue;ut=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var c=u,a=c.next;c.next=null,o===null?i=a:o.next=a,o=c;var f=e.alternate;f!==null&&(f=f.updateQueue,u=f.lastBaseUpdate,u!==o&&(u===null?f.firstBaseUpdate=a:u.next=a,f.lastBaseUpdate=c))}if(i!==null){var d=l.baseState;o=0,f=a=c=null,u=i;do{var g=u.lane,v=u.eventTime;if((r&g)===g){f!==null&&(f=f.next={eventTime:v,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var x=e,w=u;switch(g=t,v=n,w.tag){case 1:if(x=w.payload,typeof x=="function"){d=x.call(v,d,g);break e}d=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=w.payload,g=typeof x=="function"?x.call(v,d,g):x,g==null)break e;d=G({},d,g);break e;case 2:ut=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,g=l.effects,g===null?l.effects=[u]:g.push(u))}else v={eventTime:v,lane:g,tag:u.tag,payload:u.payload,callback:u.callback,next:null},f===null?(a=f=v,c=d):f=f.next=v,o|=g;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;g=u,u=g.next,g.next=null,l.lastBaseUpdate=g,l.shared.pending=null}}while(!0);if(f===null&&(c=d),l.baseState=c,l.firstBaseUpdate=a,l.lastBaseUpdate=f,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);It|=o,e.lanes=o,e.memoizedState=d}}function Eo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Vl.transition;Vl.transition={};try{e(!1),t()}finally{I=n,Vl.transition=r}}function Ta(){return Oe().memoizedState}function af(e,t,n){var r=yt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Fa(e))La(t,n);else if(n=fa(e,t,n,r),n!==null){var l=pe();Ae(n,e,r,l),Da(n,t,r)}}function cf(e,t,n){var r=yt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Fa(e))La(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,u=i(o,n);if(l.hasEagerState=!0,l.eagerState=u,Be(u,o)){var c=t.interleaved;c===null?(l.next=l,vs(t)):(l.next=c.next,c.next=l),t.interleaved=l;return}}catch{}finally{}n=fa(e,t,l,r),n!==null&&(l=pe(),Ae(n,e,r,l),Da(n,t,r))}}function Fa(e){var t=e.alternate;return e===X||t!==null&&t===X}function La(e,t){Mn=tl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Da(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ls(e,n)}}var nl={readContext:De,useCallback:oe,useContext:oe,useEffect:oe,useImperativeHandle:oe,useInsertionEffect:oe,useLayoutEffect:oe,useMemo:oe,useReducer:oe,useRef:oe,useState:oe,useDebugValue:oe,useDeferredValue:oe,useTransition:oe,useMutableSource:oe,useSyncExternalStore:oe,useId:oe,unstable_isNewReconciler:!1},df={readContext:De,useCallback:function(e,t){return Ve().memoizedState=[e,t===void 0?null:t],e},useContext:De,useEffect:zo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Dr(4194308,4,Na.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Dr(4194308,4,e,t)},useInsertionEffect:function(e,t){return Dr(4,2,e,t)},useMemo:function(e,t){var n=Ve();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ve();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=af.bind(null,X,e),[r.memoizedState,e]},useRef:function(e){var t=Ve();return e={current:e},t.memoizedState=e},useState:Po,useDebugValue:Es,useDeferredValue:function(e){return Ve().memoizedState=e},useTransition:function(){var e=Po(!1),t=e[0];return e=uf.bind(null,e[1]),Ve().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=X,l=Ve();if(Q){if(n===void 0)throw Error(j(407));n=n()}else{if(n=t(),ne===null)throw Error(j(349));Mt&30||xa(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,zo(ya.bind(null,r,i,e),[e]),r.flags|=2048,tr(9,va.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ve(),t=ne.identifierPrefix;if(Q){var n=be,r=qe;n=(r&~(1<<32-Ue(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=bn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Qe]=t,e[Zn]=r,Wa(e,t,!1,!1),t.stateNode=e;e:{switch(o=ai(n,r),n){case"dialog":H("cancel",e),H("close",e),l=r;break;case"iframe":case"object":case"embed":H("load",e),l=r;break;case"video":case"audio":for(l=0;lpn&&(t.flags|=128,r=!0,Nn(i,!1),t.lanes=4194304)}else{if(!r)if(e=el(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Nn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!Q)return ue(t),null}else 2*Z()-i.renderingStartTime>pn&&n!==1073741824&&(t.flags|=128,r=!0,Nn(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Z(),t.sibling=null,n=K.current,U(K,r?n&1|2:n&1),t):(ue(t),null);case 22:case 23:return Ds(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Se&1073741824&&(ue(t),t.subtreeFlags&6&&(t.flags|=8192)):ue(t),null;case 24:return null;case 25:return null}throw Error(j(156,t.tag))}function yf(e,t){switch(hs(t),t.tag){case 1:return je(t.type)&&Xr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return fn(),W(ye),W(ce),Ss(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ws(t),null;case 13:if(W(K),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(j(340));cn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return W(K),null;case 4:return fn(),null;case 10:return xs(t.type._context),null;case 22:case 23:return Ds(),null;case 24:return null;default:return null}}var kr=!1,ae=!1,jf=typeof WeakSet=="function"?WeakSet:Set,N=null;function bt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Y(e,t,r)}else n.current=null}function Mi(e,t,n){try{n()}catch(r){Y(e,t,r)}}var Ao=!1;function wf(e,t){if(yi=Wr,e=Zu(),ds(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,u=-1,c=-1,a=0,f=0,d=e,g=null;t:for(;;){for(var v;d!==n||l!==0&&d.nodeType!==3||(u=o+l),d!==i||r!==0&&d.nodeType!==3||(c=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(v=d.firstChild)!==null;)g=d,d=v;for(;;){if(d===e)break t;if(g===n&&++a===l&&(u=o),g===i&&++f===r&&(c=o),(v=d.nextSibling)!==null)break;d=g,g=d.parentNode}d=v}n=u===-1||c===-1?null:{start:u,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ji={focusedElem:e,selectionRange:n},Wr=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var w=x.memoizedProps,R=x.memoizedState,p=t.stateNode,h=p.getSnapshotBeforeUpdate(t.elementType===t.type?w:Me(t.type,w),R);p.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(j(163))}}catch(y){Y(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return x=Ao,Ao=!1,x}function In(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Mi(t,n,i)}l=l.next}while(l!==r)}}function xl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ii(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ka(e){var t=e.alternate;t!==null&&(e.alternate=null,Ka(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Qe],delete t[Zn],delete t[ki],delete t[nf],delete t[rf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xa(e){return e.tag===5||e.tag===3||e.tag===4}function Bo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xa(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function $i(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Kr));else if(r!==4&&(e=e.child,e!==null))for($i(e,t,n),e=e.sibling;e!==null;)$i(e,t,n),e=e.sibling}function Ui(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ui(e,t,n),e=e.sibling;e!==null;)Ui(e,t,n),e=e.sibling}var le=null,Ie=!1;function st(e,t,n){for(n=n.child;n!==null;)Ga(e,t,n),n=n.sibling}function Ga(e,t,n){if(Ke&&typeof Ke.onCommitFiberUnmount=="function")try{Ke.onCommitFiberUnmount(al,n)}catch{}switch(n.tag){case 5:ae||bt(n,t);case 6:var r=le,l=Ie;le=null,st(e,t,n),le=r,Ie=l,le!==null&&(Ie?(e=le,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):le.removeChild(n.stateNode));break;case 18:le!==null&&(Ie?(e=le,n=n.stateNode,e.nodeType===8?Bl(e.parentNode,n):e.nodeType===1&&Bl(e,n),Qn(e)):Bl(le,n.stateNode));break;case 4:r=le,l=Ie,le=n.stateNode.containerInfo,Ie=!0,st(e,t,n),le=r,Ie=l;break;case 0:case 11:case 14:case 15:if(!ae&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Mi(n,t,o),l=l.next}while(l!==r)}st(e,t,n);break;case 1:if(!ae&&(bt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){Y(n,t,u)}st(e,t,n);break;case 21:st(e,t,n);break;case 22:n.mode&1?(ae=(r=ae)||n.memoizedState!==null,st(e,t,n),ae=r):st(e,t,n);break;default:st(e,t,n)}}function Ho(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new jf),t.forEach(function(r){var l=Tf.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Re(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=Z()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*kf(r/1960))-r,10e?16:e,ft===null)var r=!1;else{if(e=ft,ft=null,il=0,O&6)throw Error(j(331));var l=O;for(O|=4,N=e.current;N!==null;){var i=N,o=i.child;if(N.flags&16){var u=i.deletions;if(u!==null){for(var c=0;cZ()-Fs?Lt(e,0):Ts|=n),we(e,t)}function nc(e,t){t===0&&(e.mode&1?(t=pr,pr<<=1,!(pr&130023424)&&(pr=4194304)):t=1);var n=pe();e=rt(e,t),e!==null&&(lr(e,t,n),we(e,n))}function zf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),nc(e,n)}function Tf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(j(314))}r!==null&&r.delete(t),nc(e,n)}var rc;rc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ye.current)ve=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ve=!1,xf(e,t,n);ve=!!(e.flags&131072)}else ve=!1,Q&&t.flags&1048576&&oa(t,Zr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Or(e,t),e=t.pendingProps;var l=an(t,ce.current);sn(t,n),l=_s(null,t,r,e,l,n);var i=Ns();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,je(r)?(i=!0,Gr(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,ys(t),l.updater=gl,t.stateNode=l,l._reactInternals=t,zi(t,r,e,n),t=Li(null,t,r,!0,i,n)):(t.tag=0,Q&&i&&fs(t),he(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Or(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Lf(r),e=Me(r,e),l){case 0:t=Fi(null,t,r,e,n);break e;case 1:t=Io(null,t,r,e,n);break e;case 11:t=Ro(null,t,r,e,n);break e;case 14:t=Mo(null,t,r,Me(r.type,e),n);break e}throw Error(j(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Fi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Io(e,t,r,l,n);case 3:e:{if(Aa(t),e===null)throw Error(j(387));r=t.pendingProps,i=t.memoizedState,l=i.element,ha(e,t),br(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=hn(Error(j(423)),t),t=$o(e,t,r,n,l);break e}else if(r!==l){l=hn(Error(j(424)),t),t=$o(e,t,r,n,l);break e}else for(ke=gt(t.stateNode.containerInfo.firstChild),_e=t,Q=!0,$e=null,n=da(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(cn(),r===l){t=lt(e,t,n);break e}he(e,t,r,n)}t=t.child}return t;case 5:return pa(t),e===null&&Ci(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,wi(r,l)?o=null:i!==null&&wi(r,i)&&(t.flags|=32),Ua(e,t),he(e,t,o,n),t.child;case 6:return e===null&&Ci(t),null;case 13:return Ba(e,t,n);case 4:return js(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=dn(t,null,r,n):he(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Ro(e,t,r,l,n);case 7:return he(e,t,t.pendingProps,n),t.child;case 8:return he(e,t,t.pendingProps.children,n),t.child;case 12:return he(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,o=l.value,U(Jr,r._currentValue),r._currentValue=o,i!==null)if(Be(i.value,o)){if(i.children===l.children&&!ye.current){t=lt(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var u=i.dependencies;if(u!==null){o=i.child;for(var c=u.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=et(-1,n&-n),c.tag=2;var a=i.updateQueue;if(a!==null){a=a.shared;var f=a.pending;f===null?c.next=c:(c.next=f.next,f.next=c),a.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Ei(i.return,n,t),u.lanes|=n;break}c=c.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(j(341));o.lanes|=n,u=o.alternate,u!==null&&(u.lanes|=n),Ei(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}he(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,sn(t,n),l=De(l),r=r(l),t.flags|=1,he(e,t,r,n),t.child;case 14:return r=t.type,l=Me(r,t.pendingProps),l=Me(r.type,l),Mo(e,t,r,l,n);case 15:return Ia(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Or(e,t),t.tag=1,je(r)?(e=!0,Gr(t)):e=!1,sn(t,n),Oa(t,r,l),zi(t,r,l,n),Li(null,t,r,!0,e,n);case 19:return Ha(e,t,n);case 22:return $a(e,t,n)}throw Error(j(156,t.tag))};function lc(e,t){return Fu(e,t)}function Ff(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Fe(e,t,n,r){return new Ff(e,t,n,r)}function Rs(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Lf(e){if(typeof e=="function")return Rs(e)?1:0;if(e!=null){if(e=e.$$typeof,e===es)return 11;if(e===ts)return 14}return 2}function jt(e,t){var n=e.alternate;return n===null?(n=Fe(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Ir(e,t,n,r,l,i){var o=2;if(r=e,typeof e=="function")Rs(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Vt:return Dt(n.children,l,i,t);case bi:o=8,l|=8;break;case bl:return e=Fe(12,n,t,l|2),e.elementType=bl,e.lanes=i,e;case ei:return e=Fe(13,n,t,l),e.elementType=ei,e.lanes=i,e;case ti:return e=Fe(19,n,t,l),e.elementType=ti,e.lanes=i,e;case pu:return yl(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case fu:o=10;break e;case hu:o=9;break e;case es:o=11;break e;case ts:o=14;break e;case ot:o=16,r=null;break e}throw Error(j(130,e==null?e:typeof e,""))}return t=Fe(o,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function Dt(e,t,n,r){return e=Fe(7,e,r,t),e.lanes=n,e}function yl(e,t,n,r){return e=Fe(22,e,r,t),e.elementType=pu,e.lanes=n,e.stateNode={isHidden:!1},e}function Yl(e,t,n){return e=Fe(6,e,null,t),e.lanes=n,e}function Zl(e,t,n){return t=Fe(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Df(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Tl(0),this.expirationTimes=Tl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Tl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Ms(e,t,n,r,l,i,o,u,c){return e=new Df(e,t,n,u,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Fe(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ys(i),e}function Of(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(uc)}catch(e){console.error(e)}}uc(),uu.exports=Ce;var Uf=uu.exports,Zo=Uf;Jl.createRoot=Zo.createRoot,Jl.hydrateRoot=Zo.hydrateRoot;const ac=["HyperLiquid","Bitget","Binance","OKX"];function Vi(e){return e==null||e<=0?"-":e>=100?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Qi(e){return e==null?"":e>0?"text-green":e<0?"text-red":""}function Af(){const[e,t]=z.useState("--:--:--"),[n,r]=z.useState("● 未连接"),[l,i]=z.useState(!1),[o,u]=z.useState(""),[c,a]=z.useState([]),[f,d]=z.useState(""),[g,v]=z.useState([]),[x,w]=z.useState([]),[R,p]=z.useState([]),[h,m]=z.useState({}),[y,S]=z.useState([]),[_,C]=z.useState([]),[E,$]=z.useState([]),[F,re]=z.useState([]),[Pe,He]=z.useState([]),[Ct,M]=z.useState([]),[de,fe]=z.useState([]),k=z.useRef({});z.useEffect(()=>{const L=()=>t(new Date().toLocaleTimeString("zh-CN",{hour12:!1}));L();const V=setInterval(L,1e3);return()=>clearInterval(V)},[]),z.useEffect(()=>{let L=new EventSource("/events");return L.addEventListener("connected",()=>{r("● 已连接"),i(!0)}),L.onerror=()=>{r("● 已断开 (重连中...)"),i(!1),setTimeout(()=>{L=new EventSource("/events")},3e3)},L.onmessage=V=>{try{const B=JSON.parse(V.data);switch(B.event){case"prices":J(B.data);break;case"arb":v(B.data||[]);break;case"positions":w(B.data||[]);break;case"blacklist":p(B.data||[]);break;case"momentum":C(B.data||[]);break;case"trend":$(B.data||[]);break;case"cumulative":re(B.data||[]);break;case"trend_filter":M(B.data||[]);break;case"trend_signal":fe(ur=>[B.data,...ur].slice(0,100));break;case"stats":m(B.data||{}),B.data&&B.data.blacklist&&p(B.data.blacklist);break;case"trade_close":P();break}}catch{}},()=>L.close()},[]);const P=z.useCallback(async()=>{try{const V=await(await fetch("/api/trades")).json();S(V.trades||[])}catch{}},[]);z.useEffect(()=>{P();const L=setInterval(P,1e4);return()=>clearInterval(L)},[P]);const T=z.useCallback(async()=>{try{const V=await(await fetch("/api/cm-history")).json();He(V.events||[])}catch{}},[]);z.useEffect(()=>{T();const L=setInterval(T,5e3);return()=>clearInterval(L)},[T]);const A=z.useCallback(async()=>{try{const V=await(await fetch("/api/trend-signals")).json();V.signals&&fe(V.signals)}catch{}},[]);z.useEffect(()=>{A();const L=setInterval(A,5e3);return()=>clearInterval(L)},[A]);function J(L){if(!L||L.length===0)return;a(L),d(new Date().toLocaleTimeString("zh-CN",{hour12:!1}));const V=k.current;for(const B of L)for(const ur of ac){const _l=B.coin+"."+ur,As=B[ur]||0;V[_l]?V[_l].last=As:V[_l]={last:As}}}function Bt(){const L=new Set,V=[];if(!c)return V;for(const B of c)L.has(B.coin)||(L.add(B.coin),V.push(B.coin));return V}function Ge(L,V){var B;return(B=k.current[L+"."+V])==null?void 0:B.last}function vn(L,V){return L==null||V==null?"":V>L?"text-green":V`${i}:${o}`).join(" "));let l="";return e.exchange_funds&&(l=Object.entries(e.exchange_funds).map(([i,o])=>`${i}: $${o.balance.toFixed(2)}`).join(" | ")),s.jsxs("section",{className:"card",id:"stats-card",children:[s.jsx("h2",{children:"📊 统计数据"}),s.jsxs("div",{className:"stats-row",children:[s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"总交易"}),s.jsx("span",{id:"stat-total",children:e.total_trades||0})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"收敛"}),s.jsx("span",{className:"pct-green",children:e.converged||0})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"发散"}),s.jsx("span",{className:"pct-red",children:e.diverged||0})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"持平"}),s.jsx("span",{className:"pct-gray",children:e.flat||0})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"持仓"}),s.jsxs("span",{className:"pct-yellow",children:[e.open_positions||0," / ",s.jsx("span",{children:"5"})]})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"币种"}),s.jsx("span",{className:"pct-blue",children:e.coins||0})]}),s.jsxs("div",{className:"stat",id:"conn-stats",children:[s.jsx("label",{children:"连接"}),s.jsx("span",{id:"conn-detail",style:{fontSize:11},children:r})]})]}),l&&s.jsx("div",{className:"stats-row",style:{marginTop:2,fontSize:11,opacity:.85},children:s.jsxs("div",{className:"stat",style:{gridColumn:"1 / -1"},children:[s.jsx("label",{children:"资金"}),s.jsx("span",{style:{fontWeight:600},children:l})]})}),t&&s.jsxs("div",{className:"stats-row detail-stats",style:{marginTop:4,fontSize:12,opacity:.85},children:[s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"总PnL"}),s.jsx("span",{children:(t.total_pnl_usd!=null?"$"+t.total_pnl_usd.toFixed(2):"—")+(t.capital_pnl!=null?" ("+t.capital_pnl.toFixed(4)+"%)":"")})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"本金"}),s.jsx("span",{children:n!=null?"$"+n.toFixed(0):"—"})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"胜率"}),s.jsx("span",{children:t.win_rate!=null?t.win_rate.toFixed(1)+"%":"—"})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"最多盈利"}),s.jsx("span",{className:"text-green",children:t.max_profit!=null?t.max_profit.toFixed(4)+"%":"—"})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"最多亏损"}),s.jsx("span",{className:"text-red",children:t.max_loss!=null?t.max_loss.toFixed(4)+"%":"—"})]}),s.jsxs("div",{className:"stat",children:[s.jsx("label",{children:"平均持仓"}),s.jsx("span",{children:t.avg_dur||"—"})]})]})]})}function Hf({positions:e}){const[t,n]=z.useState(!1),[r,l]=z.useState(null),[i,o]=z.useState([]);function u(a){a&&(n(!0),l(null),o([]),fetch("/api/trade/"+a).then(f=>f.json()).then(f=>{l(f.trade),o(f.orders||[])}).catch(()=>{l({ID:a})}))}function c(){n(!1)}return z.useEffect(()=>{if(!t)return;function a(f){f.key==="Escape"&&c()}return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t]),s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"card",id:"positions-card",children:[s.jsx("h2",{children:"🔒 当前持仓"}),s.jsx("div",{className:"table-wrap",children:s.jsxs("table",{id:"positions-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"币种"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"规模"}),s.jsx("th",{children:"入价差"}),s.jsx("th",{children:"现价差"}),s.jsx("th",{children:"估盈亏"}),s.jsx("th",{children:"加仓"}),s.jsx("th",{children:"时长"})]})}),s.jsx("tbody",{id:"positions-body",children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"8",className:"loading",children:"无持仓"})}):[...e].sort((a,f)=>a.coin.localeCompare(f.coin)).map(a=>s.jsxs("tr",{className:"trade-row",onClick:()=>u(a.db_trade_id),children:[s.jsx("td",{children:s.jsx("strong",{children:a.coin})}),s.jsx("td",{children:a.direction}),s.jsxs("td",{className:"text-right",children:["$",(a.amount_usd||0).toFixed(0)]}),s.jsxs("td",{className:"text-right",children:[(a.entry_spread||0).toFixed(4),"%"]}),s.jsx("td",{className:"text-right",children:a.current_spread!=null?a.current_spread.toFixed(4)+"%":"-"}),s.jsx("td",{className:"text-right "+Qi(a.pnl_est),children:s.jsx("strong",{children:a.pnl_est!=null?"$"+a.pnl_est.toFixed(4):"-"})}),s.jsx("td",{className:"text-right",children:a.scales||0}),s.jsx("td",{children:a.duration||"-"})]},a.coin))})]})})]}),t&&s.jsx(cc,{trade:r,orders:i,onClose:c})]})}function Wf({blacklist:e}){return s.jsxs("section",{className:"card",id:"bl-card",children:[s.jsx("h2",{children:"⛔ 黑名单"}),s.jsx("div",{className:"stats-row",id:"bl-body",children:!e||e.length===0?s.jsx("span",{className:"text-dim",children:"暂无"}):e.map((t,n)=>{const r=t.remaining_sec||0,l=r>0?`${Math.floor(r/60)}m${r%60}s`:"";return s.jsxs("span",{className:"bl-item",title:`${t.coin}: ${l}`,children:["⛔ ",t.coin,l?` (${l})`:""]},n)})})]})}function Vf({coins:e,prices:t,getPrevPrice:n,priceClass:r,pricesAge:l}){return s.jsxs("section",{className:"card",id:"prices-card",children:[s.jsxs("h2",{children:["💰 实时价格 ",s.jsx("span",{className:"text-dim",style:{fontSize:11},children:l})]}),s.jsx("div",{className:"table-wrap",children:s.jsxs("table",{id:"price-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"币种"}),s.jsx("th",{children:"HyperLiquid"}),s.jsx("th",{children:"Bitget"}),s.jsx("th",{children:"Binance"}),s.jsx("th",{children:"OKX"}),s.jsx("th",{children:"毛价差"}),s.jsx("th",{children:"BG→HL净利"}),s.jsx("th",{children:"HL→BG净利"})]})}),s.jsx("tbody",{id:"price-body",children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"8",className:"loading",children:"等待数据..."})}):e.map(i=>{const o=t.find(x=>x.coin===i);if(!o)return s.jsxs("tr",{children:[s.jsx("td",{children:i}),s.jsx("td",{className:"text-dim",children:"-"}),s.jsx("td",{className:"text-dim",children:"-"}),s.jsx("td",{className:"text-dim",children:"-"}),s.jsx("td",{className:"text-dim",children:"-"}),s.jsx("td",{className:"text-dim",children:"-"})]},i);const u=ac.map(x=>{const w=o[x],R=n(i,x),p=R?r(R,w||0):"";return s.jsx("td",{className:p,children:Vi(w)},x)}),c=o.bg_hl_spread,a=c>.2?"text-green":c<-.2?"text-red":"",f=o.net_bg_to_hl,d=o.net_hl_to_bg,g=f!=null?Qi(f):"",v=d!=null?Qi(d):"";return s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("strong",{children:i})}),u,s.jsx("td",{className:a,children:c!=null?c.toFixed(4)+"%":"-"}),s.jsx("td",{className:g,children:f!=null?f.toFixed(2)+"%":"-"}),s.jsx("td",{className:v,children:d!=null?d.toFixed(2)+"%":"-"})]},i)})})]})})]})}function Qf({opps:e}){return s.jsxs("section",{className:"card",id:"arb-card",children:[s.jsx("h2",{children:"🎯 套利机会 (BG↔HL)"}),s.jsx("div",{className:"table-wrap",children:s.jsxs("table",{id:"arb-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"币种"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"买价"}),s.jsx("th",{children:"卖价"}),s.jsx("th",{children:"净利%"})]})}),s.jsx("tbody",{id:"arb-body",children:!e||e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"5",className:"text-dim",children:"暂无套利机会"})}):e.map((t,n)=>{const r=t.net_profit>.1?"text-green":t.net_profit>.05?"text-yellow":"";return s.jsxs("tr",{children:[s.jsx("td",{children:t.coin}),s.jsx("td",{children:t.direction}),s.jsx("td",{className:"text-right",children:Vi(t.buy_price)}),s.jsx("td",{className:"text-right",children:Vi(t.sell_price)}),s.jsx("td",{className:"text-right "+r,children:s.jsx("strong",{children:(t.net_profit||0).toFixed(4)})})]},n)})})]})})]})}function Kf({trades:e,onRefresh:t}){const[n,r]=z.useState(null),[l,i]=z.useState([]),[o,u]=z.useState(!1);function c(f){u(!0),r(null),i([]),fetch("/api/trade/"+f).then(d=>d.json()).then(d=>{r(d.trade),i(d.orders||[])}).catch(()=>{r({ID:f})})}function a(){u(!1)}return z.useEffect(()=>{if(!o)return;function f(d){d.key==="Escape"&&a()}return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[o]),s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"card card-wide",id:"trades-card",children:[s.jsx("h2",{children:"📋 历史交易"}),s.jsx("div",{className:"table-wrap",children:s.jsxs("table",{id:"trades-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"时间"}),s.jsx("th",{children:"币种"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"入价差"}),s.jsx("th",{children:"出价差"}),s.jsx("th",{children:"净利%"}),s.jsx("th",{children:"结果"}),s.jsx("th",{children:"原因"})]})}),s.jsx("tbody",{id:"trades-body",children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"8",className:"text-dim",children:"暂无交易记录"})}):e.slice(0,20).map(f=>{const d=f.NetPnl>0?"text-green":f.NetPnl<0?"text-red":"",g=f.Convergence==="价差收敛"?"text-green":f.Convergence==="价差发散"?"text-red":"text-yellow";return s.jsxs("tr",{className:"trade-row",onClick:()=>c(f.ID),children:[s.jsx("td",{className:"text-dim",children:f.ClosedAt?new Date(f.ClosedAt).toLocaleTimeString("zh-CN",{hour12:!1}):"-"}),s.jsx("td",{children:s.jsx("strong",{children:f.Coin})}),s.jsx("td",{children:f.Direction}),s.jsx("td",{className:"text-right",children:f.EntrySpread!=null?f.EntrySpread.toFixed(4):"-"}),s.jsx("td",{className:"text-right",children:f.ExitSpread!=null?f.ExitSpread.toFixed(4):"-"}),s.jsx("td",{className:"text-right "+d,children:s.jsx("strong",{children:f.NetPnl!=null?f.NetPnl.toFixed(4)+"%":"-"})}),s.jsx("td",{className:g,children:f.Convergence||"-"}),s.jsx("td",{children:f.ExitReason||"-"})]},f.ID)})})]})})]}),o&&s.jsx(cc,{trade:n,orders:l,onClose:a})]})}function cc({trade:e,orders:t,onClose:n}){function r(g){g.target===g.currentTarget&&n()}if(!e)return s.jsx("div",{className:"modal-overlay",onClick:r,children:s.jsxs("div",{className:"modal-content",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h2",{children:"📋 交易详情"}),s.jsx("button",{className:"modal-close",onClick:n,children:"✕"})]}),s.jsx("div",{id:"trade-detail-body",children:s.jsx("div",{className:"loading",children:"加载中..."})})]})});const l=new Date(e.OpenedAt),i=e.ClosedAt?new Date(e.ClosedAt):null,o=i?Math.round((i-l)/1e3)+"s":"-",u=e.NetPnl>0?"text-green":e.NetPnl<0?"text-red":"",c=[...t||[]].sort((g,v)=>{const x=(g.Exchange||"").localeCompare(v.Exchange||"");return x!==0?x:new Date(g.CreatedAt)-new Date(v.CreatedAt)}),a=e.AmountUSD&&e.LongPnl!=null?e.AmountUSD*e.LongPnl/100:null,f=e.AmountUSD&&e.ShortPnl!=null?e.AmountUSD*e.ShortPnl/100:null,d=e.AmountUSD&&e.NetPnl!=null?2*e.AmountUSD*e.NetPnl/100:null;return s.jsx("div",{className:"modal-overlay",onClick:r,children:s.jsxs("div",{className:"modal-content",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h2",{children:"📋 交易详情"}),s.jsx("button",{className:"modal-close",onClick:n,children:"✕"})]}),s.jsxs("div",{id:"trade-detail-body",children:[s.jsxs("div",{className:"detail-grid",children:[s.jsxs("div",{className:"detail-section",children:[s.jsx("h3",{children:"概览"}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"币种"}),s.jsxs("span",{className:"value",children:[s.jsx("strong",{children:e.Coin}),"/USDT"]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"方向"}),s.jsx("span",{className:"value",children:e.Direction||"-"})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"状态"}),s.jsx("span",{className:"value",children:e.Status==="closed"?"已平仓":e.Status})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"加仓次数"}),s.jsxs("span",{className:"value",children:[e.ScaleCount||0," 次"]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"总规模"}),s.jsxs("span",{className:"value",children:["$",(e.AmountUSD||0).toFixed(0)]})]})]}),s.jsxs("div",{className:"detail-section",children:[s.jsx("h3",{children:"时间"}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"开仓"}),s.jsx("span",{className:"value",children:l.toLocaleString("zh-CN",{hour12:!1})})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"平仓"}),s.jsx("span",{className:"value",children:i?i.toLocaleString("zh-CN",{hour12:!1}):"-"})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"持仓时长"}),s.jsx("span",{className:"value",children:o})]})]}),s.jsxs("div",{className:"detail-section",children:[s.jsx("h3",{children:"价差"}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"入场价差"}),s.jsx("span",{className:"value",children:e.EntrySpread!=null?e.EntrySpread.toFixed(4)+"%":"-"})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"出场价差"}),s.jsx("span",{className:"value",children:e.ExitSpread!=null?e.ExitSpread.toFixed(4)+"%":"-"})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"收敛情况"}),s.jsx("span",{className:"value "+(e.Convergence==="价差收敛"?"text-green":e.Convergence==="价差发散"?"text-red":""),children:e.Convergence||"-"})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"平仓原因"}),s.jsx("span",{className:"value",children:e.ExitReason||"-"})]})]}),s.jsxs("div",{className:"detail-section",children:[s.jsx("h3",{children:"手续费"}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"开仓费"}),s.jsxs("span",{className:"value",children:["$",(e.FeeEntry||0).toFixed(4)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"平仓费"}),s.jsxs("span",{className:"value",children:["$",(e.FeeExit||0).toFixed(4)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"总手续费"}),s.jsxs("span",{className:"value",children:["$",((e.FeeEntry||0)+(e.FeeExit||0)).toFixed(4)]})]})]}),s.jsxs("div",{className:"detail-section",children:[s.jsxs("h3",{children:["多仓 ",e.LongExchange||"-"]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"入场价"}),s.jsxs("span",{className:"value",children:["$",(e.LongEntry||0).toFixed(6)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"出场价"}),s.jsxs("span",{className:"value",children:["$",(e.LongExit||0).toFixed(6)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"盈亏"}),s.jsxs("span",{className:"value "+(e.LongPnl>0?"text-green":e.LongPnl<0?"text-red":""),children:[e.LongPnl!=null?e.LongPnl.toFixed(4)+"%":"-"," ",a!=null?s.jsxs("span",{style:{fontSize:11,opacity:.8},children:["($",a.toFixed(4),")"]}):null]})]})]}),s.jsxs("div",{className:"detail-section",children:[s.jsxs("h3",{children:["空仓 ",e.ShortExchange||"-"]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"入场价"}),s.jsxs("span",{className:"value",children:["$",(e.ShortEntry||0).toFixed(6)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"出场价"}),s.jsxs("span",{className:"value",children:["$",(e.ShortExit||0).toFixed(6)]})]}),s.jsxs("div",{className:"detail-row",children:[s.jsx("span",{className:"label",children:"盈亏"}),s.jsxs("span",{className:"value "+(e.ShortPnl>0?"text-green":e.ShortPnl<0?"text-red":""),children:[e.ShortPnl!=null?e.ShortPnl.toFixed(4)+"%":"-"," ",f!=null?s.jsxs("span",{style:{fontSize:11,opacity:.8},children:["($",f.toFixed(4),")"]}):null]})]})]}),s.jsxs("div",{className:"detail-section detail-section-full",children:[s.jsx("h3",{children:"净收益"}),s.jsxs("div",{className:"detail-row",style:{fontSize:16},children:[s.jsx("span",{className:"label",children:"总计"}),s.jsxs("span",{className:"value "+u,style:{fontWeight:700},children:[e.NetPnl!=null?e.NetPnl.toFixed(4)+"%":"-"," ",d!=null?s.jsxs("span",{style:{fontSize:12,opacity:.8},children:["($",d.toFixed(4),")"]}):null]})]})]})]}),t.length>0&&s.jsxs("div",{className:"detail-section detail-section-full",style:{borderTop:"1px solid var(--border)"},children:[s.jsxs("h3",{children:["订单明细 (",t.length,")"]}),s.jsxs("table",{className:"detail-orders",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"交易所"}),s.jsx("th",{children:"类型"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"价格"}),s.jsx("th",{children:"仓位"}),s.jsx("th",{children:"手续费"}),s.jsx("th",{children:"订单ID"})]})}),s.jsx("tbody",{children:c.map((g,v)=>s.jsxs("tr",{children:[s.jsx("td",{children:g.Exchange}),s.jsx("td",{children:g.Type==="entry"?"开仓":g.Type==="exit"?"平仓":g.Type==="scale"?"加仓":g.Type}),s.jsx("td",{children:g.Side==="buy"?"买":"卖"}),s.jsxs("td",{children:["$",(g.Price||0).toFixed(6)]}),s.jsx("td",{className:"text-right",children:g.Size!=null?Number(g.Size).toFixed(4):"-"}),s.jsx("td",{children:g.Fee!=null?"$"+g.Fee.toFixed(4):"-"}),s.jsx("td",{children:g.OrderID?g.OrderID.substring(0,12)+"...":"-"})]},v))})]})]})]})]})})}function Xf(){const e=z.useRef(null),[t,n]=z.useState([]),[r,l]=z.useState(0);return z.useEffect(()=>{async function i(){try{const a=((await(await fetch("/api/trades?limit=1000")).json()).trades||[]).filter(d=>d.ClosedAt&&d.NetPnl!=null).sort((d,g)=>new Date(d.ClosedAt)-new Date(g.ClosedAt));n(a);const f=a.reduce((d,g)=>d+2*(g.AmountUSD||0)*(g.NetPnl||0)/100,0);l(f)}catch{}}i();const o=setInterval(i,1e4);return()=>clearInterval(o)},[]),z.useEffect(()=>{const i=e.current;if(!i||t.length<2)return;const o=i.parentElement.getBoundingClientRect(),u=window.devicePixelRatio||1,c=o.width,a=o.height;i.width=c*u,i.height=a*u,i.style.width=c+"px",i.style.height=a+"px";const f=i.getContext("2d");f.scale(u,u);const d={top:20,right:20,bottom:35,left:55},g=c-d.left-d.right,v=a-d.top-d.bottom,x=[];let w=0;if(t.length>0){const M=new Date(t[0].ClosedAt).getTime()-1e3;x.push({x:M,y:0})}for(const M of t)w+=2*(M.AmountUSD||0)*(M.NetPnl||0)/100,x.push({x:new Date(M.ClosedAt).getTime(),y:w});const R=x[0].x,p=x[x.length-1].x,h=x.map(M=>M.y),m=Math.min(0,...h),y=Math.max(0,...h),S=Math.max(y-m,.01),_=S*.15,C=M=>d.left+(M-R)/Math.max(p-R,1)*g,E=M=>d.top+v-(M-(m-_))/(S+2*_)*v;f.clearRect(0,0,c,a),f.strokeStyle="rgba(48,54,61,0.5)",f.lineWidth=1,f.font="11px sans-serif",f.fillStyle="#8b949e";const $=5;for(let M=0;M<=$;M++){const de=m-_+(S+2*_)*M/$,fe=E(de);f.beginPath(),f.moveTo(d.left,fe),f.lineTo(c-d.right,fe),f.stroke(),f.fillText("$"+de.toFixed(2),2,fe+4)}if(m<0&&y>0){const M=E(0);f.strokeStyle="rgba(248,81,73,0.3)",f.lineWidth=1,f.setLineDash([4,4]),f.beginPath(),f.moveTo(d.left,M),f.lineTo(c-d.right,M),f.stroke(),f.setLineDash([])}const F=Math.min(6,x.length);for(let M=0;M=0?"#3fb950":"#f85149",f.fill(),f.strokeStyle="#0d1117",f.lineWidth=2,f.stroke(),f.fillStyle="#c9d1d9",f.font="bold 13px sans-serif",f.textAlign="center",f.fillText("$"+Pe.y.toFixed(2),He,Ct-12)},[t]),s.jsxs("section",{className:"card card-wide",id:"pnl-chart-card",children:[s.jsxs("h2",{children:["📈 总PnL成长曲线 ",s.jsx("span",{className:"text-dim",style:{fontSize:11},children:t.length>0?`$${r.toFixed(2)}`:""})]}),s.jsx("div",{className:"chart-container",style:{height:260},children:t.length<1?s.jsx("div",{className:"loading",style:{paddingTop:100},children:"暂无数据..."}):s.jsx("canvas",{ref:e})})]})}function Gf({momentum:e}){const[t,n]=z.useState("score"),[r,l]=z.useState("desc");function i(d){t===d?l(r==="asc"?"desc":"asc"):(n(d),l("desc"))}function o(d){return t!==d?"":r==="asc"?" ▲":" ▼"}const u=[...e].sort((d,g)=>{let v,x;switch(t){case"coin":v=d.coin,x=g.coin;break;case"bg_1s":v=d.bg_1s||0,x=g.bg_1s||0;break;case"bg_5s":v=d.bg_5s||0,x=g.bg_5s||0;break;case"bg_15s":v=d.bg_15s||0,x=g.bg_15s||0;break;case"hl_1s":v=d.hl_1s||0,x=g.hl_1s||0;break;case"hl_5s":v=d.hl_5s||0,x=g.hl_5s||0;break;case"hl_15s":v=d.hl_15s||0,x=g.hl_15s||0;break;case"bn_1s":v=d.bn_1s||0,x=g.bn_1s||0;break;case"bn_5s":v=d.bn_5s||0,x=g.bn_5s||0;break;case"bn_15s":v=d.bn_15s||0,x=g.bn_15s||0;break;case"okx_1s":v=d.okx_1s||0,x=g.okx_1s||0;break;case"okx_5s":v=d.okx_5s||0,x=g.okx_5s||0;break;case"okx_15s":v=d.okx_15s||0,x=g.okx_15s||0;break;default:v=d.score||0,x=g.score||0}return typeof v=="string"?r==="asc"?v.localeCompare(x):x.localeCompare(v):r==="asc"?v-x:x-v});function c(d){switch(d){case"up":return"↑";case"down":return"↓";case"flat":return"→";case"mixed":return"↕";default:return"-"}}function a(d){switch(d){case"up":return"text-green";case"down":return"text-red";case"mixed":return"text-yellow";default:return""}}function f(d){return d==null||d===0?"":d>0?"text-green":"text-red"}return s.jsxs("section",{className:"card card-wide",id:"momentum-card",children:[s.jsx("h2",{children:"⚡ 动量扫描 (价格变动%)"}),s.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:s.jsxs("table",{id:"momentum-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsxs("th",{onClick:()=>i("coin"),style:{cursor:"pointer"},children:["币种",o("coin")]}),s.jsxs("th",{onClick:()=>i("score"),style:{cursor:"pointer"},children:["分数",o("score")]}),s.jsx("th",{children:"方向"}),s.jsxs("th",{onClick:()=>i("bg_1s"),style:{cursor:"pointer"},children:["BG 1s",o("bg_1s")]}),s.jsxs("th",{onClick:()=>i("bg_5s"),style:{cursor:"pointer"},children:["BG 5s",o("bg_5s")]}),s.jsxs("th",{onClick:()=>i("bg_15s"),style:{cursor:"pointer"},children:["BG 15s",o("bg_15s")]}),s.jsxs("th",{onClick:()=>i("hl_1s"),style:{cursor:"pointer"},children:["HL 1s",o("hl_1s")]}),s.jsxs("th",{onClick:()=>i("hl_5s"),style:{cursor:"pointer"},children:["HL 5s",o("hl_5s")]}),s.jsxs("th",{onClick:()=>i("hl_15s"),style:{cursor:"pointer"},children:["HL 15s",o("hl_15s")]}),s.jsxs("th",{onClick:()=>i("bn_1s"),style:{cursor:"pointer"},children:["BN 1s",o("bn_1s")]}),s.jsxs("th",{onClick:()=>i("bn_5s"),style:{cursor:"pointer"},children:["BN 5s",o("bn_5s")]}),s.jsxs("th",{onClick:()=>i("bn_15s"),style:{cursor:"pointer"},children:["BN 15s",o("bn_15s")]}),s.jsxs("th",{onClick:()=>i("okx_1s"),style:{cursor:"pointer"},children:["OKX 1s",o("okx_1s")]}),s.jsxs("th",{onClick:()=>i("okx_5s"),style:{cursor:"pointer"},children:["OKX 5s",o("okx_5s")]}),s.jsxs("th",{onClick:()=>i("okx_15s"),style:{cursor:"pointer"},children:["OKX 15s",o("okx_15s")]})]})}),s.jsx("tbody",{children:u.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"15",className:"text-dim",style:{textAlign:"center",padding:20},children:"正在收集动量数据... (需要至少 15 秒数据)"})}):u.slice(0,50).map(d=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("strong",{children:d.coin})}),s.jsxs("td",{className:"text-right",style:{fontWeight:700},children:[d.score.toFixed(4),"%"]}),s.jsx("td",{className:a(d.direction),style:{textAlign:"center",fontSize:18},children:c(d.direction)}),s.jsx("td",{className:"text-right "+f(d.bg_1s),children:d.bg_1s!=null?d.bg_1s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.bg_5s),children:d.bg_5s!=null?d.bg_5s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.bg_15s),children:d.bg_15s!=null?d.bg_15s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.hl_1s),children:d.hl_1s!=null?d.hl_1s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.hl_5s),children:d.hl_5s!=null?d.hl_5s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.hl_15s),children:d.hl_15s!=null?d.hl_15s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.bn_1s),children:d.bn_1s!=null?d.bn_1s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.bn_5s),children:d.bn_5s!=null?d.bn_5s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.bn_15s),children:d.bn_15s!=null?d.bn_15s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.okx_1s),children:d.okx_1s!=null?d.okx_1s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.okx_5s),children:d.okx_5s!=null?d.okx_5s.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+f(d.okx_15s),children:d.okx_15s!=null?d.okx_15s.toFixed(3)+"%":"-"})]},d.coin))})]})})]})}function Yf({data:e}){function t(i){switch(i){case"rising":return"↑ 上涨";case"falling":return"↓ 下跌";default:return"− 中性"}}function n(i){switch(i){case"rising":return"text-green";case"falling":return"text-red";default:return"text-dim"}}function r(i){return i==="up"?"text-green":"text-red"}function l(i){return i==null||i===0?"":i>0?"text-green":"text-red"}return s.jsxs("section",{className:"card card-wide",id:"cm-card",children:[s.jsx("h2",{children:"📊 累积变动 (1min 共识)"}),s.jsx("div",{className:"table-wrap",style:{maxHeight:300},children:s.jsxs("table",{id:"cm-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"币种"}),s.jsx("th",{children:"状态"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"分数"}),s.jsx("th",{children:"均值%"}),s.jsx("th",{children:"一致"}),s.jsx("th",{children:"BG 1m"}),s.jsx("th",{children:"HL 1m"}),s.jsx("th",{children:"BN 1m"}),s.jsx("th",{children:"OKX 1m"}),s.jsx("th",{children:"BG 5m"}),s.jsx("th",{children:"HL 5m"}),s.jsx("th",{children:"BN 5m"}),s.jsx("th",{children:"OKX 5m"}),s.jsx("th",{colSpan:4,style:{borderLeft:"2px solid var(--border)"},children:"1h 趋势"}),s.jsx("th",{children:"BG 1h"}),s.jsx("th",{children:"HL 1h"}),s.jsx("th",{children:"BN 1h"}),s.jsx("th",{children:"OKX 1h"})]})}),s.jsx("tbody",{children:!e||e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"19",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待累积数据... (需要至少 1 分钟数据)"})}):e.slice(0,30).map(i=>s.jsxs("tr",{className:n(i.state),children:[s.jsx("td",{children:s.jsx("strong",{children:i.coin})}),s.jsx("td",{children:t(i.state)}),s.jsx("td",{className:r(i.direction),style:{textAlign:"center",fontSize:16},children:i.direction==="up"?"↑":"↓"}),s.jsx("td",{className:"text-right",style:{fontWeight:700},children:(i.score||0).toFixed(2)}),s.jsxs("td",{className:"text-right",children:[(i.avg_change||0).toFixed(3),"%"]}),s.jsxs("td",{className:"text-right",children:[i.ex_agree||0,"/",i.ex_total||0]}),s.jsx("td",{className:"text-right "+l(i.bg_1m),children:i.bg_1m!=null?i.bg_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.hl_1m),children:i.hl_1m!=null?i.hl_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bn_1m),children:i.bn_1m!=null?i.bn_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.okx_1m),children:i.okx_1m!=null?i.okx_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bg_5m),children:i.bg_5m!=null?i.bg_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.hl_5m),children:i.hl_5m!=null?i.hl_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bn_5m),children:i.bn_5m!=null?i.bn_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.okx_5m),children:i.okx_5m!=null?i.okx_5m.toFixed(3)+"%":"-"}),s.jsxs("td",{className:"text-right "+r(i.direction),style:{fontWeight:600,borderLeft:"2px solid var(--border)"},children:[(i.avg_1h||0).toFixed(2),"%"]}),s.jsx("td",{className:"text-right "+l(i.bg_1h),children:i.bg_1h!=null?i.bg_1h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.hl_1h),children:i.hl_1h!=null?i.hl_1h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bn_1h),children:i.bn_1h!=null?i.bn_1h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.okx_1h),children:i.okx_1h!=null?i.okx_1h.toFixed(2)+"%":"-"})]},i.coin))})]})})]})}function Zf({history:e}){function t(i){switch(i){case"rising":return"↑ 上涨";case"falling":return"↓ 下跌";default:return"− 中性"}}function n(i){switch(i){case"rising":return"text-green";case"falling":return"text-red";default:return"text-dim"}}function r(i){return i==="up"?"text-green":"text-red"}function l(i){return i==null||i===0?"":i>0?"text-green":"text-red"}return s.jsxs("section",{className:"card card-wide",id:"cm-history-card",children:[s.jsx("h2",{children:"📋 累积变动事件记录"}),s.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:s.jsxs("table",{id:"cm-history-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"时间"}),s.jsx("th",{children:"币种"}),s.jsx("th",{children:"转换"}),s.jsx("th",{children:"方向"}),s.jsx("th",{children:"分数"}),s.jsx("th",{children:"均值%"}),s.jsx("th",{children:"一致"}),s.jsx("th",{children:"BG 1m"}),s.jsx("th",{children:"HL 1m"}),s.jsx("th",{children:"BN 1m"}),s.jsx("th",{children:"OKX 1m"}),s.jsx("th",{children:"BG 5m"}),s.jsx("th",{children:"HL 5m"}),s.jsx("th",{children:"BN 5m"}),s.jsx("th",{children:"OKX 5m"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"15",className:"text-dim",style:{textAlign:"center",padding:20},children:"暂无累积变动事件记录"})}):e.slice(0,100).map((i,o)=>s.jsxs("tr",{children:[s.jsx("td",{className:"text-dim",children:i.created_at?new Date(i.created_at).toLocaleTimeString("zh-CN",{hour12:!1}):"-"}),s.jsx("td",{children:s.jsx("strong",{children:i.coin})}),s.jsxs("td",{className:n(i.new_state),children:[i.prev_state," → ",t(i.new_state)]}),s.jsx("td",{className:r(i.direction),style:{textAlign:"center",fontSize:16},children:i.direction==="up"?"↑":"↓"}),s.jsx("td",{className:"text-right",children:(i.score||0).toFixed(2)}),s.jsxs("td",{className:"text-right",children:[(i.avg_change||0).toFixed(3),"%"]}),s.jsxs("td",{className:"text-right",children:[i.ex_agree||0,"/",i.ex_total||0]}),s.jsx("td",{className:"text-right "+l(i.bg_1m),children:i.bg_1m!=null?i.bg_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.hl_1m),children:i.hl_1m!=null?i.hl_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bn_1m),children:i.bn_1m!=null?i.bn_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.okx_1m),children:i.okx_1m!=null?i.okx_1m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bg_5m),children:i.bg_5m!=null?i.bg_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.hl_5m),children:i.hl_5m!=null?i.hl_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.bn_5m),children:i.bn_5m!=null?i.bn_5m.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right "+l(i.okx_5m),children:i.okx_5m!=null?i.okx_5m.toFixed(3)+"%":"-"})]},(i.id||o)+"-cm"))})]})})]})}function Jf({filterData:e}){const t=e.filter(a=>a.passes_filter).length,n=e.filter(a=>a.signal_score>=80).length,r=e.filter(a=>a.signal_score>=50&&a.signal_score<80).length,l=e.filter(a=>a.fresh_anomaly).length;let i=`高分${n} 中分${r}`;l>0?(i+=` | ${l}币异动中`,t>0&&(i+=` → ${t}通过!`)):i+=" | 等待异动信号";function o(a){return a==null?"":a>=80?"text-green":a>=50?"text-yellow":"text-dim"}function u(a){return a==null||a<=1.5?"":a>3?"text-red":"text-orange"}function c(a){return a==null||a===0?"":a>0?"text-green":"text-red"}return s.jsxs("section",{className:"card card-wide",id:"trend-filter-card",children:[s.jsxs("h2",{children:["趋势过滤 (",t,"通过 / ",e.length,") ",s.jsx("span",{className:"text-dim",style:{fontSize:12,fontWeight:400},children:i})]}),s.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:s.jsxs("table",{id:"trend-filter-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"币种"}),s.jsx("th",{children:"分数"}),s.jsx("th",{children:"24h范围"}),s.jsx("th",{children:"基线"}),s.jsx("th",{children:"1h范围"}),s.jsx("th",{children:"成交量比"}),s.jsx("th",{children:"1h变化"}),s.jsx("th",{children:"EMA52"}),s.jsx("th",{children:"EMA斜率"}),s.jsx("th",{children:"现价"}),s.jsx("th",{children:"> EMA"}),s.jsx("th",{children:"安静24h"}),s.jsx("th",{children:"安静1h"}),s.jsx("th",{children:"异动"}),s.jsx("th",{children:"更新于"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"15",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待K线数据..."})}):e.map(a=>s.jsxs("tr",{className:a.passes_filter?"filter-pass":"",children:[s.jsx("td",{children:s.jsx("strong",{children:a.coin})}),s.jsx("td",{className:"text-right "+o(a.signal_score),style:{fontWeight:700},children:a.signal_score!=null?a.signal_score.toFixed(0):"-"}),s.jsx("td",{className:"text-right "+(a.quiet_24h?"text-green":""),children:a.range_24h!=null?a.range_24h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right text-dim",children:a.vol_baseline!=null?a.vol_baseline.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right "+(a.quiet_1h?"text-green":""),children:a.range_1h!=null?a.range_1h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right "+u(a.volume_ratio),children:a.volume_ratio!=null?a.volume_ratio.toFixed(2)+"x":"-"}),s.jsx("td",{className:"text-right "+(a.change_1h>0?"text-green":a.change_1h<0?"text-red":""),children:a.change_1h!=null?(a.change_1h>0?"+":"")+a.change_1h.toFixed(2)+"%":"-"}),s.jsx("td",{className:"text-right",children:a.ema_52?a.ema_52.toFixed(4):"-"}),s.jsx("td",{className:"text-right "+c(a.ema_slope),children:a.ema_slope!=null?(a.ema_slope>0?"+":"")+a.ema_slope.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-right",children:a.current_price?a.current_price.toFixed(4):"-"}),s.jsx("td",{className:a.price_above_ema?"text-green":"text-red",children:a.price_above_ema!=null?a.price_above_ema?"↑":"↓":"-"}),s.jsx("td",{className:a.quiet_24h?"text-green":"text-dim",children:a.quiet_24h!=null?a.quiet_24h?"✓":"✗":"-"}),s.jsx("td",{className:a.quiet_1h?"text-green":"text-dim",children:a.quiet_1h!=null?a.quiet_1h?"✓":"✗":"-"}),s.jsx("td",{className:a.fresh_anomaly?"text-orange":"text-dim",children:a.fresh_anomaly!=null&&a.fresh_anomaly?"⚠":"-"}),s.jsx("td",{className:"text-dim",children:a.last_updated?new Date(a.last_updated).toLocaleTimeString("zh-CN",{hour12:!1}):"-"})]},a.coin))})]})})]})}function qf({signals:e}){const t=e.filter(r=>r.category==="full"),n=t.filter(r=>r.type==="enter").length;return s.jsxs("section",{className:"card card-wide",id:"trend-signal-card",children:[s.jsxs("h2",{children:["完整信号 (异动+分数≥70) ",n>0&&s.jsxs("span",{className:"text-green",style:{fontSize:12,fontWeight:400,marginLeft:8},children:["共",n,"条"]})]}),s.jsx("div",{className:"table-wrap",style:{maxHeight:350},children:s.jsxs("table",{id:"trend-signal-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"时间"}),s.jsx("th",{children:"币种"}),s.jsx("th",{children:"类型"}),s.jsx("th",{children:"分数"}),s.jsx("th",{children:"价格"}),s.jsx("th",{children:"成交量比"}),s.jsx("th",{children:"EMA斜率"}),s.jsx("th",{children:"趋势状态"})]})}),s.jsx("tbody",{children:t.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"8",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待完整信号... (FreshAnomaly + 分数≥70)"})}):t.slice(0,50).map((r,l)=>{const i=r.type==="enter"?"signal-enter":"signal-exit",o=r.timestamp?new Date(r.timestamp).toLocaleTimeString("zh-CN",{hour12:!1}):"-";return s.jsxs("tr",{className:i,children:[s.jsx("td",{className:"text-dim",children:o}),s.jsx("td",{children:s.jsx("strong",{children:r.coin})}),s.jsx("td",{className:r.type==="enter"?"text-green":"text-dim",style:{fontWeight:600},children:r.type==="enter"?"开":"关"}),s.jsx("td",{className:"text-right",style:{fontWeight:700},children:r.signal_score!=null?r.signal_score.toFixed(0):"-"}),s.jsx("td",{className:"text-right",children:r.price?r.price.toFixed(4):"-"}),s.jsx("td",{className:"text-right",children:r.volume_ratio!=null?r.volume_ratio.toFixed(2)+"x":"-"}),s.jsx("td",{className:"text-right",children:r.ema_slope!=null?(r.ema_slope>0?"+":"")+r.ema_slope.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-dim",children:r.state||"-"})]},"full-"+r.timestamp+"-"+r.coin+"-"+l)})})]})})]})}function bf({signals:e}){const t=e.filter(r=>r.category==="high"),n=t.filter(r=>r.type==="enter").length;return s.jsxs("section",{className:"card card-wide",id:"high-score-card",children:[s.jsxs("h2",{children:["高分信号 (分数≥90) ",n>0&&s.jsxs("span",{className:"text-green",style:{fontSize:12,fontWeight:400,marginLeft:8},children:["共",n,"条"]})]}),s.jsx("div",{className:"table-wrap",style:{maxHeight:350},children:s.jsxs("table",{id:"high-score-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"时间"}),s.jsx("th",{children:"币种"}),s.jsx("th",{children:"类型"}),s.jsx("th",{children:"分数"}),s.jsx("th",{children:"价格"}),s.jsx("th",{children:"成交量比"}),s.jsx("th",{children:"EMA斜率"}),s.jsx("th",{children:"趋势状态"})]})}),s.jsx("tbody",{children:t.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:"8",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待高分信号... (分数≥90)"})}):t.slice(0,50).map((r,l)=>{const i=r.type==="enter"?"signal-enter":"signal-exit",o=r.timestamp?new Date(r.timestamp).toLocaleTimeString("zh-CN",{hour12:!1}):"-";return s.jsxs("tr",{className:i,children:[s.jsx("td",{className:"text-dim",children:o}),s.jsx("td",{children:s.jsx("strong",{children:r.coin})}),s.jsx("td",{className:r.type==="enter"?"text-green":"text-dim",style:{fontWeight:600},children:r.type==="enter"?"开":"关"}),s.jsx("td",{className:"text-right",style:{fontWeight:700},children:r.signal_score!=null?r.signal_score.toFixed(0):"-"}),s.jsx("td",{className:"text-right",children:r.price?r.price.toFixed(4):"-"}),s.jsx("td",{className:"text-right",children:r.volume_ratio!=null?r.volume_ratio.toFixed(2)+"x":"-"}),s.jsx("td",{className:"text-right",children:r.ema_slope!=null?(r.ema_slope>0?"+":"")+r.ema_slope.toFixed(3)+"%":"-"}),s.jsx("td",{className:"text-dim",children:r.state||"-"})]},"high-"+r.timestamp+"-"+r.coin+"-"+l)})})]})})]})}Jl.createRoot(document.getElementById("root")).render(s.jsx(Ec.StrictMode,{children:s.jsx(Af,{})})); diff --git a/frontend/dist/assets/index-DsdSIpuQ.css b/frontend/dist/assets/index-CDE5zNyv.css similarity index 88% rename from frontend/dist/assets/index-DsdSIpuQ.css rename to frontend/dist/assets/index-CDE5zNyv.css index 37580a2..621ec7c 100644 --- a/frontend/dist/assets/index-DsdSIpuQ.css +++ b/frontend/dist/assets/index-CDE5zNyv.css @@ -1 +1 @@ -:root{--bg: #0d1117;--card: #161b22;--border: #30363d;--text: #c9d1d9;--text-dim: #8b949e;--accent: #58a6ff;--green: #3fb950;--red: #f85149;--yellow: #d29922;--blue: #58a6ff}*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif;background:var(--bg);color:var(--text);font-size:14px;line-height:1.5;min-height:100vh}#app{max-width:1440px;margin:0 auto;padding:16px}header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background:var(--card);border:1px solid var(--border);border-radius:8px;margin-bottom:16px}header h1{font-size:18px;font-weight:600}.header-meta{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text-dim)}.sep{color:var(--border)}.status-offline{color:var(--red)}.status-online{color:var(--green)}.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.card-wide{grid-column:1 / -1}.card{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:12px}.card h2{font-size:14px;font-weight:600;color:var(--text-dim);margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border)}.stats-row{display:flex;gap:16px;flex-wrap:wrap}.stat{display:flex;flex-direction:column;align-items:center;min-width:60px}.stat label{font-size:11px;color:var(--text-dim);margin-bottom:2px}.stat span{font-size:20px;font-weight:700}.pct-green{color:var(--green)}.pct-red{color:var(--red)}.pct-gray{color:var(--text-dim)}.pct-yellow{color:var(--yellow)}.pct-blue{color:var(--blue)}#conn-detail{font-size:11px;white-space:nowrap}.table-wrap{overflow-x:auto;max-height:320px;overflow-y:auto}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;padding:6px 8px;color:var(--text-dim);font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.5px;position:sticky;top:0;background:var(--card);border-bottom:1px solid var(--border)}td{padding:5px 8px;border-bottom:1px solid rgba(48,54,61,.5);white-space:nowrap}tr:hover td{background:#58a6ff0d}.trade-row{cursor:pointer}.loading{text-align:center;color:var(--text-dim);padding:20px!important}.text-green{color:var(--green)}.text-red{color:var(--red)}.text-yellow{color:var(--yellow)}.text-dim{color:var(--text-dim)}.text-right{text-align:right}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#484f58}@media (max-width: 768px){.grid{grid-template-columns:1fr}header{flex-direction:column;gap:8px}.stats-row{justify-content:center}}#bl-body{display:flex;gap:8px;flex-wrap:wrap}.bl-item{background:#f851491a;border:1px solid rgba(248,81,73,.3);border-radius:4px;padding:4px 10px;font-size:12px;color:var(--red);cursor:default}.modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:#000000b3;z-index:1000;display:flex;align-items:flex-start;justify-content:center;padding:40px 16px;overflow-y:auto}.modal-content{background:var(--card);border:1px solid var(--border);border-radius:12px;max-width:700px;width:100%;box-shadow:0 8px 32px #00000080}.modal-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border)}.modal-header h2{font-size:16px;margin:0;padding:0;border:none;color:var(--text)}.modal-close{background:none;border:none;color:var(--text-dim);font-size:20px;cursor:pointer;padding:4px 8px;border-radius:4px;line-height:1}.modal-close:hover{background:#ffffff1a;color:var(--text)}#trade-detail-body{padding:0}.detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:0}.detail-section{padding:14px 20px;border-bottom:1px solid rgba(48,54,61,.4)}.detail-section:last-child{border-bottom:none}.detail-section-full{grid-column:1 / -1}.detail-section h3{font-size:12px;color:var(--text-dim);font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}.detail-row{display:flex;justify-content:space-between;padding:3px 0;font-size:13px}.detail-row .label{color:var(--text-dim)}.detail-row .value{font-weight:500}.detail-orders{width:100%;font-size:12px}.detail-orders th{background:var(--bg);font-size:10px}.detail-orders td{padding:4px 6px}#momentum-card{grid-column:1 / -1}#momentum-table th{cursor:pointer;-webkit-user-select:none;user-select:none}#momentum-table th:hover{color:var(--accent)}#momentum-table td{font-variant-numeric:tabular-nums}#trend-card{grid-column:1 / -1}#trend-table th{-webkit-user-select:none;user-select:none}#trend-table td{font-variant-numeric:tabular-nums}.trend-state{font-weight:600;font-size:12px}.trend-alert{background:#d299220d}.trend-alert:hover td{background:#d299221a!important}.trend-confirmed{background:#3fb95014}.trend-confirmed:hover td{background:#3fb95026!important}.trend-exhausting{background:#8b949e0d}.trend-exhausting:hover td{background:#8b949e1a!important} +:root{--bg: #0d1117;--card: #161b22;--border: #30363d;--text: #c9d1d9;--text-dim: #8b949e;--accent: #58a6ff;--green: #3fb950;--red: #f85149;--yellow: #d29922;--blue: #58a6ff}*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif;background:var(--bg);color:var(--text);font-size:14px;line-height:1.5;min-height:100vh}#app{max-width:1440px;margin:0 auto;padding:16px}header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background:var(--card);border:1px solid var(--border);border-radius:8px;margin-bottom:16px}header h1{font-size:18px;font-weight:600}.header-meta{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text-dim)}.sep{color:var(--border)}.status-offline{color:var(--red)}.status-online{color:var(--green)}.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.card-wide{grid-column:1 / -1}.card{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:12px}.card h2{font-size:14px;font-weight:600;color:var(--text-dim);margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border)}.stats-row{display:flex;gap:16px;flex-wrap:wrap}.stat{display:flex;flex-direction:column;align-items:center;min-width:60px}.stat label{font-size:11px;color:var(--text-dim);margin-bottom:2px}.stat span{font-size:20px;font-weight:700}.pct-green{color:var(--green)}.pct-red{color:var(--red)}.pct-gray{color:var(--text-dim)}.pct-yellow{color:var(--yellow)}.pct-blue{color:var(--blue)}#conn-detail{font-size:11px;white-space:nowrap}.table-wrap{overflow-x:auto;max-height:320px;overflow-y:auto}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;padding:6px 8px;color:var(--text-dim);font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.5px;position:sticky;top:0;background:var(--card);border-bottom:1px solid var(--border)}td{padding:5px 8px;border-bottom:1px solid rgba(48,54,61,.5);white-space:nowrap}tr:hover td{background:#58a6ff0d}.trade-row{cursor:pointer}.loading{text-align:center;color:var(--text-dim);padding:20px!important}.text-green{color:var(--green)}.text-red{color:var(--red)}.text-yellow{color:var(--yellow)}.text-dim{color:var(--text-dim)}.text-right{text-align:right}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#484f58}@media (max-width: 768px){.grid{grid-template-columns:1fr}header{flex-direction:column;gap:8px}.stats-row{justify-content:center}}#bl-body{display:flex;gap:8px;flex-wrap:wrap}.bl-item{background:#f851491a;border:1px solid rgba(248,81,73,.3);border-radius:4px;padding:4px 10px;font-size:12px;color:var(--red);cursor:default}.modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:#000000b3;z-index:1000;display:flex;align-items:flex-start;justify-content:center;padding:40px 16px;overflow-y:auto}.modal-content{background:var(--card);border:1px solid var(--border);border-radius:12px;max-width:700px;width:100%;box-shadow:0 8px 32px #00000080}.modal-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border)}.modal-header h2{font-size:16px;margin:0;padding:0;border:none;color:var(--text)}.modal-close{background:none;border:none;color:var(--text-dim);font-size:20px;cursor:pointer;padding:4px 8px;border-radius:4px;line-height:1}.modal-close:hover{background:#ffffff1a;color:var(--text)}#trade-detail-body{padding:0}.detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:0}.detail-section{padding:14px 20px;border-bottom:1px solid rgba(48,54,61,.4)}.detail-section:last-child{border-bottom:none}.detail-section-full{grid-column:1 / -1}.detail-section h3{font-size:12px;color:var(--text-dim);font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}.detail-row{display:flex;justify-content:space-between;padding:3px 0;font-size:13px}.detail-row .label{color:var(--text-dim)}.detail-row .value{font-weight:500}.detail-orders{width:100%;font-size:12px}.detail-orders th{background:var(--bg);font-size:10px}.detail-orders td{padding:4px 6px}#momentum-card{grid-column:1 / -1}#momentum-table th{cursor:pointer;-webkit-user-select:none;user-select:none}#momentum-table th:hover{color:var(--accent)}#momentum-table td{font-variant-numeric:tabular-nums}#trend-card{grid-column:1 / -1}#trend-table th{-webkit-user-select:none;user-select:none}#trend-table td{font-variant-numeric:tabular-nums}.trend-state{font-weight:600;font-size:12px}.trend-alert{background:#d299220d}.trend-alert:hover td{background:#d299221a!important}.trend-confirmed{background:#3fb95014}.trend-confirmed:hover td{background:#3fb95026!important}.trend-exhausting{background:#8b949e0d}.trend-exhausting:hover td{background:#8b949e1a!important}.text-orange{color:var(--yellow)}#trend-filter-card{grid-column:1 / -1}#trend-filter-table td{font-variant-numeric:tabular-nums}.filter-pass td{background:#3fb9500f}.filter-pass:hover td{background:#3fb9501f!important}.text-blue{color:#58a6ff}#trend-signal-card{grid-column:1 / -1}#trend-signal-table td{font-variant-numeric:tabular-nums}#high-score-card{grid-column:1 / -1}#high-score-table td{font-variant-numeric:tabular-nums}.signal-enter td{background:#3fb95014}.signal-enter:hover td{background:#3fb95026!important}.signal-exit td{background:#8b949e0d}.signal-exit:hover td{background:#8b949e1a!important} diff --git a/frontend/dist/assets/index-Dr4jUtK1.js b/frontend/dist/assets/index-Dr4jUtK1.js deleted file mode 100644 index 0c3f393..0000000 --- a/frontend/dist/assets/index-Dr4jUtK1.js +++ /dev/null @@ -1,40 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();function ac(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yo={exports:{}},il={},Zo={exports:{}},D={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var tr=Symbol.for("react.element"),cc=Symbol.for("react.portal"),dc=Symbol.for("react.fragment"),fc=Symbol.for("react.strict_mode"),hc=Symbol.for("react.profiler"),pc=Symbol.for("react.provider"),mc=Symbol.for("react.context"),gc=Symbol.for("react.forward_ref"),vc=Symbol.for("react.suspense"),xc=Symbol.for("react.memo"),yc=Symbol.for("react.lazy"),Us=Symbol.iterator;function jc(e){return e===null||typeof e!="object"?null:(e=Us&&e[Us]||e["@@iterator"],typeof e=="function"?e:null)}var Jo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},qo=Object.assign,bo={};function pn(e,t,n){this.props=e,this.context=t,this.refs=bo,this.updater=n||Jo}pn.prototype.isReactComponent={};pn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};pn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function eu(){}eu.prototype=pn.prototype;function Vi(e,t,n){this.props=e,this.context=t,this.refs=bo,this.updater=n||Jo}var Wi=Vi.prototype=new eu;Wi.constructor=Vi;qo(Wi,pn.prototype);Wi.isPureReactComponent=!0;var As=Array.isArray,tu=Object.prototype.hasOwnProperty,Qi={current:null},nu={key:!0,ref:!0,__self:!0,__source:!0};function ru(e,t,n){var r,l={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)tu.call(t,r)&&!nu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1>>1,J=k[Q];if(0>>1;Ql(F,L))Il(U,F)?(k[Q]=U,k[I]=L,Q=I):(k[Q]=F,k[Ge]=L,Q=Ge);else if(Il(U,L))k[Q]=U,k[I]=L,Q=I;else break e}}return P}function l(k,P){var L=k.sortIndex-P.sortIndex;return L!==0?L:k.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,u=s.now();e.unstable_now=function(){return s.now()-u}}var a=[],d=[],f=1,c=null,g=3,x=!1,v=!1,w=!1,R=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,h=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(k){for(var P=n(d);P!==null;){if(P.callback===null)r(d);else if(P.startTime<=k)r(d),P.sortIndex=P.expirationTime,t(a,P);else break;P=n(d)}}function y(k){if(w=!1,m(k),!v)if(n(a)!==null)v=!0,fe(S);else{var P=n(d);P!==null&&te(y,P.startTime-k)}}function S(k,P){v=!1,w&&(w=!1,p(E),E=-1),x=!0;var L=g;try{for(m(P),c=n(a);c!==null&&(!(c.expirationTime>P)||k&&!le());){var Q=c.callback;if(typeof Q=="function"){c.callback=null,g=c.priorityLevel;var J=Q(c.expirationTime<=P);P=e.unstable_now(),typeof J=="function"?c.callback=J:c===n(a)&&r(a),m(P)}else r(a);c=n(a)}if(c!==null)var At=!0;else{var Ge=n(d);Ge!==null&&te(y,Ge.startTime-P),At=!1}return At}finally{c=null,g=L,x=!1}}var _=!1,C=null,E=-1,A=5,T=-1;function le(){return!(e.unstable_now()-Tk||125Q?(k.sortIndex=L,t(d,k),n(a)===null&&k===n(d)&&(w?(p(E),E=-1):w=!0,te(y,L-Q))):(k.sortIndex=J,t(a,k),v||x||(v=!0,fe(S))),k},e.unstable_shouldYield=le,e.unstable_wrapCallback=function(k){var P=g;return function(){var L=g;g=P;try{return k.apply(this,arguments)}finally{g=L}}}})(uu);ou.exports=uu;var Fc=ou.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Dc=z,Ne=Fc;function j(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Yl=Object.prototype.hasOwnProperty,Oc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Bs={},Vs={};function Rc(e){return Yl.call(Vs,e)?!0:Yl.call(Bs,e)?!1:Oc.test(e)?Vs[e]=!0:(Bs[e]=!0,!1)}function Mc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ic(e,t,n,r){if(t===null||typeof t>"u"||Mc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ge(e,t,n,r,l,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var oe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){oe[e]=new ge(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];oe[t]=new ge(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){oe[e]=new ge(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){oe[e]=new ge(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){oe[e]=new ge(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){oe[e]=new ge(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){oe[e]=new ge(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){oe[e]=new ge(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){oe[e]=new ge(e,5,!1,e.toLowerCase(),null,!1,!1)});var Xi=/[\-:]([a-z])/g;function Gi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Xi,Gi);oe[t]=new ge(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Xi,Gi);oe[t]=new ge(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Xi,Gi);oe[t]=new ge(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){oe[e]=new ge(e,1,!1,e.toLowerCase(),null,!1,!1)});oe.xlinkHref=new ge("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){oe[e]=new ge(e,1,!1,e.toLowerCase(),null,!0,!0)});function Yi(e,t,n,r){var l=oe.hasOwnProperty(t)?oe[t]:null;(l!==null?l.type!==0:r||!(2u||l[s]!==i[u]){var a=` -`+l[s].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=s&&0<=u);break}}}finally{_l=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Nn(e):""}function $c(e){switch(e.tag){case 5:return Nn(e.type);case 16:return Nn("Lazy");case 13:return Nn("Suspense");case 19:return Nn("SuspenseList");case 0:case 2:case 15:return e=Nl(e.type,!1),e;case 11:return e=Nl(e.type.render,!1),e;case 1:return e=Nl(e.type,!0),e;default:return""}}function bl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Vt:return"Fragment";case Bt:return"Portal";case Zl:return"Profiler";case Zi:return"StrictMode";case Jl:return"Suspense";case ql:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case du:return(e.displayName||"Context")+".Consumer";case cu:return(e._context.displayName||"Context")+".Provider";case Ji:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case qi:return t=e.displayName||null,t!==null?t:bl(e.type)||"Memo";case st:t=e._payload,e=e._init;try{return bl(e(t))}catch{}}return null}function Uc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return bl(t);case 8:return t===Zi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function jt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function hu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ac(e){var t=hu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ur(e){e._valueTracker||(e._valueTracker=Ac(e))}function pu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=hu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Rr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function ei(e,t){var n=t.checked;return G({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Qs(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=jt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function mu(e,t){t=t.checked,t!=null&&Yi(e,"checked",t,!1)}function ti(e,t){mu(e,t);var n=jt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ni(e,t.type,n):t.hasOwnProperty("defaultValue")&&ni(e,t.type,jt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ks(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ni(e,t,n){(t!=="number"||Rr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Cn=Array.isArray;function en(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=ar.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Un(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var zn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Hc=["Webkit","ms","Moz","O"];Object.keys(zn).forEach(function(e){Hc.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),zn[t]=zn[e]})});function yu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||zn.hasOwnProperty(e)&&zn[e]?(""+t).trim():t+"px"}function ju(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=yu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Bc=G({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ii(e,t){if(t){if(Bc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(j(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(j(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(j(61))}if(t.style!=null&&typeof t.style!="object")throw Error(j(62))}}function si(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var oi=null;function bi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ui=null,tn=null,nn=null;function Ys(e){if(e=lr(e)){if(typeof ui!="function")throw Error(j(280));var t=e.stateNode;t&&(t=cl(t),ui(e.stateNode,e.type,t))}}function wu(e){tn?nn?nn.push(e):nn=[e]:tn=e}function Su(){if(tn){var e=tn,t=nn;if(nn=tn=null,Ys(e),t)for(e=0;e>>=0,e===0?32:31-(bc(e)/ed|0)|0}var cr=64,dr=4194304;function En(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Ur(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var u=s&~l;u!==0?r=En(u):(i&=s,i!==0&&(r=En(i)))}else s=n&~l,s!==0?r=En(s):i!==0&&(r=En(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function nr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ue(t),e[t]=n}function ld(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ln),lo=" ",io=!1;function Bu(e,t){switch(e){case"keyup":return Fd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Wt=!1;function Od(e,t){switch(e){case"compositionend":return Vu(t);case"keypress":return t.which!==32?null:(io=!0,lo);case"textInput":return e=t.data,e===lo&&io?null:e;default:return null}}function Rd(e,t){if(Wt)return e==="compositionend"||!os&&Bu(e,t)?(e=Au(),Cr=ls=ct=null,Wt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ao(n)}}function Xu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Xu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Gu(){for(var e=window,t=Rr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Rr(e.document)}return t}function us(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Wd(e){var t=Gu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Xu(n.ownerDocument.documentElement,n)){if(r!==null&&us(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=co(n,i);var s=co(n,r);l&&s&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Qt=null,pi=null,Dn=null,mi=!1;function fo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;mi||Qt==null||Qt!==Rr(r)||(r=Qt,"selectionStart"in r&&us(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Dn&&Qn(Dn,r)||(Dn=r,r=Br(pi,"onSelect"),0Gt||(e.current=wi[Gt],wi[Gt]=null,Gt--)}function H(e,t){Gt++,wi[Gt]=e.current,e.current=t}var wt={},de=kt(wt),ye=kt(!1),Dt=wt;function un(e,t){var n=e.type.contextTypes;if(!n)return wt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function je(e){return e=e.childContextTypes,e!=null}function Wr(){V(ye),V(de)}function yo(e,t,n){if(de.current!==wt)throw Error(j(168));H(de,t),H(ye,n)}function ra(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(j(108,Uc(e)||"Unknown",l));return G({},n,r)}function Qr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||wt,Dt=de.current,H(de,e),H(ye,ye.current),!0}function jo(e,t,n){var r=e.stateNode;if(!r)throw Error(j(169));n?(e=ra(e,t,Dt),r.__reactInternalMemoizedMergedChildContext=e,V(ye),V(de),H(de,e)):V(ye),H(ye,n)}var Ze=null,dl=!1,Ul=!1;function la(e){Ze===null?Ze=[e]:Ze.push(e)}function nf(e){dl=!0,la(e)}function _t(){if(!Ul&&Ze!==null){Ul=!0;var e=0,t=$;try{var n=Ze;for($=1;e>=s,l-=s,Je=1<<32-Ue(t)+l|n<E?(A=C,C=null):A=C.sibling;var T=g(p,C,m[E],y);if(T===null){C===null&&(C=A);break}e&&C&&T.alternate===null&&t(p,C),h=i(T,h,E),_===null?S=T:_.sibling=T,_=T,C=A}if(E===m.length)return n(p,C),W&&Ct(p,E),S;if(C===null){for(;EE?(A=C,C=null):A=C.sibling;var le=g(p,C,T.value,y);if(le===null){C===null&&(C=A);break}e&&C&&le.alternate===null&&t(p,C),h=i(le,h,E),_===null?S=le:_.sibling=le,_=le,C=A}if(T.done)return n(p,C),W&&Ct(p,E),S;if(C===null){for(;!T.done;E++,T=m.next())T=c(p,T.value,y),T!==null&&(h=i(T,h,E),_===null?S=T:_.sibling=T,_=T);return W&&Ct(p,E),S}for(C=r(p,C);!T.done;E++,T=m.next())T=x(C,p,E,T.value,y),T!==null&&(e&&T.alternate!==null&&C.delete(T.key===null?E:T.key),h=i(T,h,E),_===null?S=T:_.sibling=T,_=T);return e&&C.forEach(function(Pe){return t(p,Pe)}),W&&Ct(p,E),S}function R(p,h,m,y){if(typeof m=="object"&&m!==null&&m.type===Vt&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case or:e:{for(var S=m.key,_=h;_!==null;){if(_.key===S){if(S=m.type,S===Vt){if(_.tag===7){n(p,_.sibling),h=l(_,m.props.children),h.return=p,p=h;break e}}else if(_.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===st&&ko(S)===_.type){n(p,_.sibling),h=l(_,m.props),h.ref=Sn(p,_,m),h.return=p,p=h;break e}n(p,_);break}else t(p,_);_=_.sibling}m.type===Vt?(h=Ft(m.props.children,p.mode,y,m.key),h.return=p,p=h):(y=Or(m.type,m.key,m.props,null,p.mode,y),y.ref=Sn(p,h,m),y.return=p,p=y)}return s(p);case Bt:e:{for(_=m.key;h!==null;){if(h.key===_)if(h.tag===4&&h.stateNode.containerInfo===m.containerInfo&&h.stateNode.implementation===m.implementation){n(p,h.sibling),h=l(h,m.children||[]),h.return=p,p=h;break e}else{n(p,h);break}else t(p,h);h=h.sibling}h=Xl(m,p.mode,y),h.return=p,p=h}return s(p);case st:return _=m._init,R(p,h,_(m._payload),y)}if(Cn(m))return v(p,h,m,y);if(vn(m))return w(p,h,m,y);xr(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,h!==null&&h.tag===6?(n(p,h.sibling),h=l(h,m),h.return=p,p=h):(n(p,h),h=Kl(m,p.mode,y),h.return=p,p=h),s(p)):n(p,h)}return R}var cn=ua(!0),aa=ua(!1),Gr=kt(null),Yr=null,Jt=null,fs=null;function hs(){fs=Jt=Yr=null}function ps(e){var t=Gr.current;V(Gr),e._currentValue=t}function _i(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ln(e,t){Yr=e,fs=Jt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(xe=!0),e.firstContext=null)}function De(e){var t=e._currentValue;if(fs!==e)if(e={context:e,memoizedValue:t,next:null},Jt===null){if(Yr===null)throw Error(j(308));Jt=e,Yr.dependencies={lanes:0,firstContext:e}}else Jt=Jt.next=e;return t}var zt=null;function ms(e){zt===null?zt=[e]:zt.push(e)}function ca(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,ms(t)):(n.next=l.next,l.next=n),t.interleaved=n,nt(e,r)}function nt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var ot=!1;function gs(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function da(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function be(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,O&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,nt(e,n)}return l=r.interleaved,l===null?(t.next=t,ms(r)):(t.next=l.next,l.next=t),r.interleaved=t,nt(e,n)}function Pr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ts(e,n)}}function _o(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var s={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=s:i=i.next=s,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Zr(e,t,n,r){var l=e.updateQueue;ot=!1;var i=l.firstBaseUpdate,s=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var a=u,d=a.next;a.next=null,s===null?i=d:s.next=d,s=a;var f=e.alternate;f!==null&&(f=f.updateQueue,u=f.lastBaseUpdate,u!==s&&(u===null?f.firstBaseUpdate=d:u.next=d,f.lastBaseUpdate=a))}if(i!==null){var c=l.baseState;s=0,f=d=a=null,u=i;do{var g=u.lane,x=u.eventTime;if((r&g)===g){f!==null&&(f=f.next={eventTime:x,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var v=e,w=u;switch(g=t,x=n,w.tag){case 1:if(v=w.payload,typeof v=="function"){c=v.call(x,c,g);break e}c=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=w.payload,g=typeof v=="function"?v.call(x,c,g):v,g==null)break e;c=G({},c,g);break e;case 2:ot=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,g=l.effects,g===null?l.effects=[u]:g.push(u))}else x={eventTime:x,lane:g,tag:u.tag,payload:u.payload,callback:u.callback,next:null},f===null?(d=f=x,a=c):f=f.next=x,s|=g;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;g=u,u=g.next,g.next=null,l.lastBaseUpdate=g,l.shared.pending=null}}while(!0);if(f===null&&(a=c),l.baseState=a,l.firstBaseUpdate=d,l.lastBaseUpdate=f,t=l.shared.interleaved,t!==null){l=t;do s|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);Mt|=s,e.lanes=s,e.memoizedState=c}}function No(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Hl.transition;Hl.transition={};try{e(!1),t()}finally{$=n,Hl.transition=r}}function Pa(){return Oe().memoizedState}function of(e,t,n){var r=xt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},za(e))Ta(t,n);else if(n=ca(e,t,n,r),n!==null){var l=pe();Ae(n,e,r,l),La(n,t,r)}}function uf(e,t,n){var r=xt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(za(e))Ta(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,u=i(s,n);if(l.hasEagerState=!0,l.eagerState=u,He(u,s)){var a=t.interleaved;a===null?(l.next=l,ms(t)):(l.next=a.next,a.next=l),t.interleaved=l;return}}catch{}finally{}n=ca(e,t,l,r),n!==null&&(l=pe(),Ae(n,e,r,l),La(n,t,r))}}function za(e){var t=e.alternate;return e===X||t!==null&&t===X}function Ta(e,t){On=qr=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function La(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ts(e,n)}}var br={readContext:De,useCallback:ue,useContext:ue,useEffect:ue,useImperativeHandle:ue,useInsertionEffect:ue,useLayoutEffect:ue,useMemo:ue,useReducer:ue,useRef:ue,useState:ue,useDebugValue:ue,useDeferredValue:ue,useTransition:ue,useMutableSource:ue,useSyncExternalStore:ue,useId:ue,unstable_isNewReconciler:!1},af={readContext:De,useCallback:function(e,t){return We().memoizedState=[e,t===void 0?null:t],e},useContext:De,useEffect:Eo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Tr(4194308,4,ka.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Tr(4194308,4,e,t)},useInsertionEffect:function(e,t){return Tr(4,2,e,t)},useMemo:function(e,t){var n=We();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=We();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=of.bind(null,X,e),[r.memoizedState,e]},useRef:function(e){var t=We();return e={current:e},t.memoizedState=e},useState:Co,useDebugValue:_s,useDeferredValue:function(e){return We().memoizedState=e},useTransition:function(){var e=Co(!1),t=e[0];return e=sf.bind(null,e[1]),We().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=X,l=We();if(W){if(n===void 0)throw Error(j(407));n=n()}else{if(n=t(),re===null)throw Error(j(349));Rt&30||ma(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Eo(va.bind(null,r,i,e),[e]),r.flags|=2048,bn(9,ga.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=We(),t=re.identifierPrefix;if(W){var n=qe,r=Je;n=(r&~(1<<32-Ue(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Jn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Qe]=t,e[Gn]=r,Ha(e,t,!1,!1),t.stateNode=e;e:{switch(s=si(n,r),n){case"dialog":B("cancel",e),B("close",e),l=r;break;case"iframe":case"object":case"embed":B("load",e),l=r;break;case"video":case"audio":for(l=0;lhn&&(t.flags|=128,r=!0,kn(i,!1),t.lanes=4194304)}else{if(!r)if(e=Jr(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),kn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!W)return ae(t),null}else 2*Z()-i.renderingStartTime>hn&&n!==1073741824&&(t.flags|=128,r=!0,kn(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Z(),t.sibling=null,n=K.current,H(K,r?n&1|2:n&1),t):(ae(t),null);case 22:case 23:return Ts(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Se&1073741824&&(ae(t),t.subtreeFlags&6&&(t.flags|=8192)):ae(t),null;case 24:return null;case 25:return null}throw Error(j(156,t.tag))}function vf(e,t){switch(cs(t),t.tag){case 1:return je(t.type)&&Wr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return dn(),V(ye),V(de),ys(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return xs(t),null;case 13:if(V(K),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(j(340));an()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return V(K),null;case 4:return dn(),null;case 10:return ps(t.type._context),null;case 22:case 23:return Ts(),null;case 24:return null;default:return null}}var jr=!1,ce=!1,xf=typeof WeakSet=="function"?WeakSet:Set,N=null;function qt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Y(e,t,r)}else n.current=null}function Di(e,t,n){try{n()}catch(r){Y(e,t,r)}}var $o=!1;function yf(e,t){if(gi=Ar,e=Gu(),us(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,u=-1,a=-1,d=0,f=0,c=e,g=null;t:for(;;){for(var x;c!==n||l!==0&&c.nodeType!==3||(u=s+l),c!==i||r!==0&&c.nodeType!==3||(a=s+r),c.nodeType===3&&(s+=c.nodeValue.length),(x=c.firstChild)!==null;)g=c,c=x;for(;;){if(c===e)break t;if(g===n&&++d===l&&(u=s),g===i&&++f===r&&(a=s),(x=c.nextSibling)!==null)break;c=g,g=c.parentNode}c=x}n=u===-1||a===-1?null:{start:u,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(vi={focusedElem:e,selectionRange:n},Ar=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var w=v.memoizedProps,R=v.memoizedState,p=t.stateNode,h=p.getSnapshotBeforeUpdate(t.elementType===t.type?w:Me(t.type,w),R);p.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(j(163))}}catch(y){Y(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return v=$o,$o=!1,v}function Rn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Di(t,n,i)}l=l.next}while(l!==r)}}function pl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Oi(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Wa(e){var t=e.alternate;t!==null&&(e.alternate=null,Wa(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Qe],delete t[Gn],delete t[ji],delete t[ef],delete t[tf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Qa(e){return e.tag===5||e.tag===3||e.tag===4}function Uo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Qa(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ri(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Vr));else if(r!==4&&(e=e.child,e!==null))for(Ri(e,t,n),e=e.sibling;e!==null;)Ri(e,t,n),e=e.sibling}function Mi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Mi(e,t,n),e=e.sibling;e!==null;)Mi(e,t,n),e=e.sibling}var ie=null,Ie=!1;function it(e,t,n){for(n=n.child;n!==null;)Ka(e,t,n),n=n.sibling}function Ka(e,t,n){if(Ke&&typeof Ke.onCommitFiberUnmount=="function")try{Ke.onCommitFiberUnmount(sl,n)}catch{}switch(n.tag){case 5:ce||qt(n,t);case 6:var r=ie,l=Ie;ie=null,it(e,t,n),ie=r,Ie=l,ie!==null&&(Ie?(e=ie,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ie.removeChild(n.stateNode));break;case 18:ie!==null&&(Ie?(e=ie,n=n.stateNode,e.nodeType===8?$l(e.parentNode,n):e.nodeType===1&&$l(e,n),Vn(e)):$l(ie,n.stateNode));break;case 4:r=ie,l=Ie,ie=n.stateNode.containerInfo,Ie=!0,it(e,t,n),ie=r,Ie=l;break;case 0:case 11:case 14:case 15:if(!ce&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Di(n,t,s),l=l.next}while(l!==r)}it(e,t,n);break;case 1:if(!ce&&(qt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){Y(n,t,u)}it(e,t,n);break;case 21:it(e,t,n);break;case 22:n.mode&1?(ce=(r=ce)||n.memoizedState!==null,it(e,t,n),ce=r):it(e,t,n);break;default:it(e,t,n)}}function Ao(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new xf),t.forEach(function(r){var l=Pf.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Re(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=s),r&=~i}if(r=l,r=Z()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*wf(r/1960))-r,10e?16:e,dt===null)var r=!1;else{if(e=dt,dt=null,nl=0,O&6)throw Error(j(331));var l=O;for(O|=4,N=e.current;N!==null;){var i=N,s=i.child;if(N.flags&16){var u=i.deletions;if(u!==null){for(var a=0;aZ()-Ps?Lt(e,0):Es|=n),we(e,t)}function ec(e,t){t===0&&(e.mode&1?(t=dr,dr<<=1,!(dr&130023424)&&(dr=4194304)):t=1);var n=pe();e=nt(e,t),e!==null&&(nr(e,t,n),we(e,n))}function Ef(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ec(e,n)}function Pf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(j(314))}r!==null&&r.delete(t),ec(e,n)}var tc;tc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ye.current)xe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return xe=!1,mf(e,t,n);xe=!!(e.flags&131072)}else xe=!1,W&&t.flags&1048576&&ia(t,Xr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Lr(e,t),e=t.pendingProps;var l=un(t,de.current);ln(t,n),l=ws(null,t,r,e,l,n);var i=Ss();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,je(r)?(i=!0,Qr(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,gs(t),l.updater=hl,t.stateNode=l,l._reactInternals=t,Ci(t,r,e,n),t=zi(null,t,r,!0,i,n)):(t.tag=0,W&&i&&as(t),he(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Lr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Tf(r),e=Me(r,e),l){case 0:t=Pi(null,t,r,e,n);break e;case 1:t=Ro(null,t,r,e,n);break e;case 11:t=Do(null,t,r,e,n);break e;case 14:t=Oo(null,t,r,Me(r.type,e),n);break e}throw Error(j(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Pi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Ro(e,t,r,l,n);case 3:e:{if($a(t),e===null)throw Error(j(387));r=t.pendingProps,i=t.memoizedState,l=i.element,da(e,t),Zr(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=fn(Error(j(423)),t),t=Mo(e,t,r,n,l);break e}else if(r!==l){l=fn(Error(j(424)),t),t=Mo(e,t,r,n,l);break e}else for(ke=mt(t.stateNode.containerInfo.firstChild),_e=t,W=!0,$e=null,n=aa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(an(),r===l){t=rt(e,t,n);break e}he(e,t,r,n)}t=t.child}return t;case 5:return fa(t),e===null&&ki(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,s=l.children,xi(r,l)?s=null:i!==null&&xi(r,i)&&(t.flags|=32),Ia(e,t),he(e,t,s,n),t.child;case 6:return e===null&&ki(t),null;case 13:return Ua(e,t,n);case 4:return vs(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=cn(t,null,r,n):he(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Do(e,t,r,l,n);case 7:return he(e,t,t.pendingProps,n),t.child;case 8:return he(e,t,t.pendingProps.children,n),t.child;case 12:return he(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,s=l.value,H(Gr,r._currentValue),r._currentValue=s,i!==null)if(He(i.value,s)){if(i.children===l.children&&!ye.current){t=rt(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var u=i.dependencies;if(u!==null){s=i.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(i.tag===1){a=be(-1,n&-n),a.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var f=d.pending;f===null?a.next=a:(a.next=f.next,f.next=a),d.pending=a}}i.lanes|=n,a=i.alternate,a!==null&&(a.lanes|=n),_i(i.return,n,t),u.lanes|=n;break}a=a.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(j(341));s.lanes|=n,u=s.alternate,u!==null&&(u.lanes|=n),_i(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}he(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,ln(t,n),l=De(l),r=r(l),t.flags|=1,he(e,t,r,n),t.child;case 14:return r=t.type,l=Me(r,t.pendingProps),l=Me(r.type,l),Oo(e,t,r,l,n);case 15:return Ra(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Me(r,l),Lr(e,t),t.tag=1,je(r)?(e=!0,Qr(t)):e=!1,ln(t,n),Fa(t,r,l),Ci(t,r,l,n),zi(null,t,r,!0,e,n);case 19:return Aa(e,t,n);case 22:return Ma(e,t,n)}throw Error(j(156,t.tag))};function nc(e,t){return zu(e,t)}function zf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Le(e,t,n,r){return new zf(e,t,n,r)}function Fs(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Tf(e){if(typeof e=="function")return Fs(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ji)return 11;if(e===qi)return 14}return 2}function yt(e,t){var n=e.alternate;return n===null?(n=Le(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Or(e,t,n,r,l,i){var s=2;if(r=e,typeof e=="function")Fs(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case Vt:return Ft(n.children,l,i,t);case Zi:s=8,l|=8;break;case Zl:return e=Le(12,n,t,l|2),e.elementType=Zl,e.lanes=i,e;case Jl:return e=Le(13,n,t,l),e.elementType=Jl,e.lanes=i,e;case ql:return e=Le(19,n,t,l),e.elementType=ql,e.lanes=i,e;case fu:return gl(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case cu:s=10;break e;case du:s=9;break e;case Ji:s=11;break e;case qi:s=14;break e;case st:s=16,r=null;break e}throw Error(j(130,e==null?e:typeof e,""))}return t=Le(s,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function Ft(e,t,n,r){return e=Le(7,e,r,t),e.lanes=n,e}function gl(e,t,n,r){return e=Le(22,e,r,t),e.elementType=fu,e.lanes=n,e.stateNode={isHidden:!1},e}function Kl(e,t,n){return e=Le(6,e,null,t),e.lanes=n,e}function Xl(e,t,n){return t=Le(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Lf(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=El(0),this.expirationTimes=El(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=El(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Ds(e,t,n,r,l,i,s,u,a){return e=new Lf(e,t,n,u,a),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Le(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},gs(i),e}function Ff(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(sc)}catch(e){console.error(e)}}sc(),su.exports=Ce;var If=su.exports,Go=If;Gl.createRoot=Go.createRoot,Gl.hydrateRoot=Go.hydrateRoot;const oc=["HyperLiquid","Bitget","Binance","OKX"];function Hi(e){return e==null||e<=0?"-":e>=100?e.toFixed(2):e>=1?e.toFixed(4):e.toFixed(6)}function Bi(e){return e==null?"":e>0?"text-green":e<0?"text-red":""}function $f(){const[e,t]=z.useState("--:--:--"),[n,r]=z.useState("● 未连接"),[l,i]=z.useState(!1),[s,u]=z.useState(""),[a,d]=z.useState([]),[f,c]=z.useState(""),[g,x]=z.useState([]),[v,w]=z.useState([]),[R,p]=z.useState([]),[h,m]=z.useState({}),[y,S]=z.useState([]),[_,C]=z.useState([]),[E,A]=z.useState([]),[T,le]=z.useState([]),[Pe,Be]=z.useState([]),[Nt,M]=z.useState([]),fe=z.useRef({});z.useEffect(()=>{const F=()=>t(new Date().toLocaleTimeString("zh-CN",{hour12:!1}));F();const I=setInterval(F,1e3);return()=>clearInterval(I)},[]),z.useEffect(()=>{let F=new EventSource("/events");return F.addEventListener("connected",()=>{r("● 已连接"),i(!0)}),F.onerror=()=>{r("● 已断开 (重连中...)"),i(!1),setTimeout(()=>{F=new EventSource("/events")},3e3)},F.onmessage=I=>{try{const U=JSON.parse(I.data);switch(U.event){case"prices":L(U.data);break;case"arb":x(U.data||[]);break;case"positions":w(U.data||[]);break;case"blacklist":p(U.data||[]);break;case"momentum":C(U.data||[]);break;case"trend":A(U.data||[]);break;case"cumulative":Be(U.data||[]);break;case"stats":m(U.data||{}),U.data&&U.data.blacklist&&p(U.data.blacklist);break;case"trade_close":te();break}}catch{}},()=>F.close()},[]);const te=z.useCallback(async()=>{try{const I=await(await fetch("/api/trades")).json();S(I.trades||[])}catch{}},[]);z.useEffect(()=>{te();const F=setInterval(te,1e4);return()=>clearInterval(F)},[te]);const k=z.useCallback(async()=>{try{const I=await(await fetch("/api/trend-history")).json();le(I.events||[])}catch{}},[]);z.useEffect(()=>{k();const F=setInterval(k,5e3);return()=>clearInterval(F)},[k]);const P=z.useCallback(async()=>{try{const I=await(await fetch("/api/cm-history")).json();M(I.events||[])}catch{}},[]);z.useEffect(()=>{P();const F=setInterval(P,5e3);return()=>clearInterval(F)},[P]);function L(F){if(!F||F.length===0)return;d(F),c(new Date().toLocaleTimeString("zh-CN",{hour12:!1}));const I=fe.current;for(const U of F)for(const Is of oc){const wl=U.coin+"."+Is,$s=U[Is]||0;I[wl]?I[wl].last=$s:I[wl]={last:$s}}}function Q(){const F=new Set,I=[];if(!a)return I;for(const U of a)F.has(U.coin)||(F.add(U.coin),I.push(U.coin));return I}function J(F,I){var U;return(U=fe.current[F+"."+I])==null?void 0:U.last}function At(F,I){return F==null||I==null?"":I>F?"text-green":I`${i}:${s}`).join(" "));let l="";return e.exchange_funds&&(l=Object.entries(e.exchange_funds).map(([i,s])=>`${i}: $${s.balance.toFixed(2)}`).join(" | ")),o.jsxs("section",{className:"card",id:"stats-card",children:[o.jsx("h2",{children:"📊 统计数据"}),o.jsxs("div",{className:"stats-row",children:[o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"总交易"}),o.jsx("span",{id:"stat-total",children:e.total_trades||0})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"收敛"}),o.jsx("span",{className:"pct-green",children:e.converged||0})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"发散"}),o.jsx("span",{className:"pct-red",children:e.diverged||0})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"持平"}),o.jsx("span",{className:"pct-gray",children:e.flat||0})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"持仓"}),o.jsxs("span",{className:"pct-yellow",children:[e.open_positions||0," / ",o.jsx("span",{children:"5"})]})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"币种"}),o.jsx("span",{className:"pct-blue",children:e.coins||0})]}),o.jsxs("div",{className:"stat",id:"conn-stats",children:[o.jsx("label",{children:"连接"}),o.jsx("span",{id:"conn-detail",style:{fontSize:11},children:r})]})]}),l&&o.jsx("div",{className:"stats-row",style:{marginTop:2,fontSize:11,opacity:.85},children:o.jsxs("div",{className:"stat",style:{gridColumn:"1 / -1"},children:[o.jsx("label",{children:"资金"}),o.jsx("span",{style:{fontWeight:600},children:l})]})}),t&&o.jsxs("div",{className:"stats-row detail-stats",style:{marginTop:4,fontSize:12,opacity:.85},children:[o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"总PnL"}),o.jsx("span",{children:(t.total_pnl_usd!=null?"$"+t.total_pnl_usd.toFixed(2):"—")+(t.capital_pnl!=null?" ("+t.capital_pnl.toFixed(4)+"%)":"")})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"本金"}),o.jsx("span",{children:n!=null?"$"+n.toFixed(0):"—"})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"胜率"}),o.jsx("span",{children:t.win_rate!=null?t.win_rate.toFixed(1)+"%":"—"})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"最多盈利"}),o.jsx("span",{className:"text-green",children:t.max_profit!=null?t.max_profit.toFixed(4)+"%":"—"})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"最多亏损"}),o.jsx("span",{className:"text-red",children:t.max_loss!=null?t.max_loss.toFixed(4)+"%":"—"})]}),o.jsxs("div",{className:"stat",children:[o.jsx("label",{children:"平均持仓"}),o.jsx("span",{children:t.avg_dur||"—"})]})]})]})}function Af({positions:e}){const[t,n]=z.useState(!1),[r,l]=z.useState(null),[i,s]=z.useState([]);function u(d){d&&(n(!0),l(null),s([]),fetch("/api/trade/"+d).then(f=>f.json()).then(f=>{l(f.trade),s(f.orders||[])}).catch(()=>{l({ID:d})}))}function a(){n(!1)}return z.useEffect(()=>{if(!t)return;function d(f){f.key==="Escape"&&a()}return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]),o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"card",id:"positions-card",children:[o.jsx("h2",{children:"🔒 当前持仓"}),o.jsx("div",{className:"table-wrap",children:o.jsxs("table",{id:"positions-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"币种"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"规模"}),o.jsx("th",{children:"入价差"}),o.jsx("th",{children:"现价差"}),o.jsx("th",{children:"估盈亏"}),o.jsx("th",{children:"加仓"}),o.jsx("th",{children:"时长"})]})}),o.jsx("tbody",{id:"positions-body",children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"8",className:"loading",children:"无持仓"})}):[...e].sort((d,f)=>d.coin.localeCompare(f.coin)).map(d=>o.jsxs("tr",{className:"trade-row",onClick:()=>u(d.db_trade_id),children:[o.jsx("td",{children:o.jsx("strong",{children:d.coin})}),o.jsx("td",{children:d.direction}),o.jsxs("td",{className:"text-right",children:["$",(d.amount_usd||0).toFixed(0)]}),o.jsxs("td",{className:"text-right",children:[(d.entry_spread||0).toFixed(4),"%"]}),o.jsx("td",{className:"text-right",children:d.current_spread!=null?d.current_spread.toFixed(4)+"%":"-"}),o.jsx("td",{className:"text-right "+Bi(d.pnl_est),children:o.jsx("strong",{children:d.pnl_est!=null?"$"+d.pnl_est.toFixed(4):"-"})}),o.jsx("td",{className:"text-right",children:d.scales||0}),o.jsx("td",{children:d.duration||"-"})]},d.coin))})]})})]}),t&&o.jsx(uc,{trade:r,orders:i,onClose:a})]})}function Hf({blacklist:e}){return o.jsxs("section",{className:"card",id:"bl-card",children:[o.jsx("h2",{children:"⛔ 黑名单"}),o.jsx("div",{className:"stats-row",id:"bl-body",children:!e||e.length===0?o.jsx("span",{className:"text-dim",children:"暂无"}):e.map((t,n)=>{const r=t.remaining_sec||0,l=r>0?`${Math.floor(r/60)}m${r%60}s`:"";return o.jsxs("span",{className:"bl-item",title:`${t.coin}: ${l}`,children:["⛔ ",t.coin,l?` (${l})`:""]},n)})})]})}function Bf({coins:e,prices:t,getPrevPrice:n,priceClass:r,pricesAge:l}){return o.jsxs("section",{className:"card",id:"prices-card",children:[o.jsxs("h2",{children:["💰 实时价格 ",o.jsx("span",{className:"text-dim",style:{fontSize:11},children:l})]}),o.jsx("div",{className:"table-wrap",children:o.jsxs("table",{id:"price-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"币种"}),o.jsx("th",{children:"HyperLiquid"}),o.jsx("th",{children:"Bitget"}),o.jsx("th",{children:"Binance"}),o.jsx("th",{children:"OKX"}),o.jsx("th",{children:"毛价差"}),o.jsx("th",{children:"BG→HL净利"}),o.jsx("th",{children:"HL→BG净利"})]})}),o.jsx("tbody",{id:"price-body",children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"8",className:"loading",children:"等待数据..."})}):e.map(i=>{const s=t.find(v=>v.coin===i);if(!s)return o.jsxs("tr",{children:[o.jsx("td",{children:i}),o.jsx("td",{className:"text-dim",children:"-"}),o.jsx("td",{className:"text-dim",children:"-"}),o.jsx("td",{className:"text-dim",children:"-"}),o.jsx("td",{className:"text-dim",children:"-"}),o.jsx("td",{className:"text-dim",children:"-"})]},i);const u=oc.map(v=>{const w=s[v],R=n(i,v),p=R?r(R,w||0):"";return o.jsx("td",{className:p,children:Hi(w)},v)}),a=s.bg_hl_spread,d=a>.2?"text-green":a<-.2?"text-red":"",f=s.net_bg_to_hl,c=s.net_hl_to_bg,g=f!=null?Bi(f):"",x=c!=null?Bi(c):"";return o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:i})}),u,o.jsx("td",{className:d,children:a!=null?a.toFixed(4)+"%":"-"}),o.jsx("td",{className:g,children:f!=null?f.toFixed(2)+"%":"-"}),o.jsx("td",{className:x,children:c!=null?c.toFixed(2)+"%":"-"})]},i)})})]})})]})}function Vf({opps:e}){return o.jsxs("section",{className:"card",id:"arb-card",children:[o.jsx("h2",{children:"🎯 套利机会 (BG↔HL)"}),o.jsx("div",{className:"table-wrap",children:o.jsxs("table",{id:"arb-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"币种"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"买价"}),o.jsx("th",{children:"卖价"}),o.jsx("th",{children:"净利%"})]})}),o.jsx("tbody",{id:"arb-body",children:!e||e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"5",className:"text-dim",children:"暂无套利机会"})}):e.map((t,n)=>{const r=t.net_profit>.1?"text-green":t.net_profit>.05?"text-yellow":"";return o.jsxs("tr",{children:[o.jsx("td",{children:t.coin}),o.jsx("td",{children:t.direction}),o.jsx("td",{className:"text-right",children:Hi(t.buy_price)}),o.jsx("td",{className:"text-right",children:Hi(t.sell_price)}),o.jsx("td",{className:"text-right "+r,children:o.jsx("strong",{children:(t.net_profit||0).toFixed(4)})})]},n)})})]})})]})}function Wf({trades:e,onRefresh:t}){const[n,r]=z.useState(null),[l,i]=z.useState([]),[s,u]=z.useState(!1);function a(f){u(!0),r(null),i([]),fetch("/api/trade/"+f).then(c=>c.json()).then(c=>{r(c.trade),i(c.orders||[])}).catch(()=>{r({ID:f})})}function d(){u(!1)}return z.useEffect(()=>{if(!s)return;function f(c){c.key==="Escape"&&d()}return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s]),o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"card card-wide",id:"trades-card",children:[o.jsx("h2",{children:"📋 历史交易"}),o.jsx("div",{className:"table-wrap",children:o.jsxs("table",{id:"trades-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"时间"}),o.jsx("th",{children:"币种"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"入价差"}),o.jsx("th",{children:"出价差"}),o.jsx("th",{children:"净利%"}),o.jsx("th",{children:"结果"}),o.jsx("th",{children:"原因"})]})}),o.jsx("tbody",{id:"trades-body",children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"8",className:"text-dim",children:"暂无交易记录"})}):e.slice(0,20).map(f=>{const c=f.NetPnl>0?"text-green":f.NetPnl<0?"text-red":"",g=f.Convergence==="价差收敛"?"text-green":f.Convergence==="价差发散"?"text-red":"text-yellow";return o.jsxs("tr",{className:"trade-row",onClick:()=>a(f.ID),children:[o.jsx("td",{className:"text-dim",children:f.ClosedAt?new Date(f.ClosedAt).toLocaleTimeString("zh-CN",{hour12:!1}):"-"}),o.jsx("td",{children:o.jsx("strong",{children:f.Coin})}),o.jsx("td",{children:f.Direction}),o.jsx("td",{className:"text-right",children:f.EntrySpread!=null?f.EntrySpread.toFixed(4):"-"}),o.jsx("td",{className:"text-right",children:f.ExitSpread!=null?f.ExitSpread.toFixed(4):"-"}),o.jsx("td",{className:"text-right "+c,children:o.jsx("strong",{children:f.NetPnl!=null?f.NetPnl.toFixed(4)+"%":"-"})}),o.jsx("td",{className:g,children:f.Convergence||"-"}),o.jsx("td",{children:f.ExitReason||"-"})]},f.ID)})})]})})]}),s&&o.jsx(uc,{trade:n,orders:l,onClose:d})]})}function uc({trade:e,orders:t,onClose:n}){function r(g){g.target===g.currentTarget&&n()}if(!e)return o.jsx("div",{className:"modal-overlay",onClick:r,children:o.jsxs("div",{className:"modal-content",children:[o.jsxs("div",{className:"modal-header",children:[o.jsx("h2",{children:"📋 交易详情"}),o.jsx("button",{className:"modal-close",onClick:n,children:"✕"})]}),o.jsx("div",{id:"trade-detail-body",children:o.jsx("div",{className:"loading",children:"加载中..."})})]})});const l=new Date(e.OpenedAt),i=e.ClosedAt?new Date(e.ClosedAt):null,s=i?Math.round((i-l)/1e3)+"s":"-",u=e.NetPnl>0?"text-green":e.NetPnl<0?"text-red":"",a=[...t||[]].sort((g,x)=>{const v=(g.Exchange||"").localeCompare(x.Exchange||"");return v!==0?v:new Date(g.CreatedAt)-new Date(x.CreatedAt)}),d=e.AmountUSD&&e.LongPnl!=null?e.AmountUSD*e.LongPnl/100:null,f=e.AmountUSD&&e.ShortPnl!=null?e.AmountUSD*e.ShortPnl/100:null,c=e.AmountUSD&&e.NetPnl!=null?2*e.AmountUSD*e.NetPnl/100:null;return o.jsx("div",{className:"modal-overlay",onClick:r,children:o.jsxs("div",{className:"modal-content",children:[o.jsxs("div",{className:"modal-header",children:[o.jsx("h2",{children:"📋 交易详情"}),o.jsx("button",{className:"modal-close",onClick:n,children:"✕"})]}),o.jsxs("div",{id:"trade-detail-body",children:[o.jsxs("div",{className:"detail-grid",children:[o.jsxs("div",{className:"detail-section",children:[o.jsx("h3",{children:"概览"}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"币种"}),o.jsxs("span",{className:"value",children:[o.jsx("strong",{children:e.Coin}),"/USDT"]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"方向"}),o.jsx("span",{className:"value",children:e.Direction||"-"})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"状态"}),o.jsx("span",{className:"value",children:e.Status==="closed"?"已平仓":e.Status})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"加仓次数"}),o.jsxs("span",{className:"value",children:[e.ScaleCount||0," 次"]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"总规模"}),o.jsxs("span",{className:"value",children:["$",(e.AmountUSD||0).toFixed(0)]})]})]}),o.jsxs("div",{className:"detail-section",children:[o.jsx("h3",{children:"时间"}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"开仓"}),o.jsx("span",{className:"value",children:l.toLocaleString("zh-CN",{hour12:!1})})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"平仓"}),o.jsx("span",{className:"value",children:i?i.toLocaleString("zh-CN",{hour12:!1}):"-"})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"持仓时长"}),o.jsx("span",{className:"value",children:s})]})]}),o.jsxs("div",{className:"detail-section",children:[o.jsx("h3",{children:"价差"}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"入场价差"}),o.jsx("span",{className:"value",children:e.EntrySpread!=null?e.EntrySpread.toFixed(4)+"%":"-"})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"出场价差"}),o.jsx("span",{className:"value",children:e.ExitSpread!=null?e.ExitSpread.toFixed(4)+"%":"-"})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"收敛情况"}),o.jsx("span",{className:"value "+(e.Convergence==="价差收敛"?"text-green":e.Convergence==="价差发散"?"text-red":""),children:e.Convergence||"-"})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"平仓原因"}),o.jsx("span",{className:"value",children:e.ExitReason||"-"})]})]}),o.jsxs("div",{className:"detail-section",children:[o.jsx("h3",{children:"手续费"}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"开仓费"}),o.jsxs("span",{className:"value",children:["$",(e.FeeEntry||0).toFixed(4)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"平仓费"}),o.jsxs("span",{className:"value",children:["$",(e.FeeExit||0).toFixed(4)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"总手续费"}),o.jsxs("span",{className:"value",children:["$",((e.FeeEntry||0)+(e.FeeExit||0)).toFixed(4)]})]})]}),o.jsxs("div",{className:"detail-section",children:[o.jsxs("h3",{children:["多仓 ",e.LongExchange||"-"]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"入场价"}),o.jsxs("span",{className:"value",children:["$",(e.LongEntry||0).toFixed(6)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"出场价"}),o.jsxs("span",{className:"value",children:["$",(e.LongExit||0).toFixed(6)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"盈亏"}),o.jsxs("span",{className:"value "+(e.LongPnl>0?"text-green":e.LongPnl<0?"text-red":""),children:[e.LongPnl!=null?e.LongPnl.toFixed(4)+"%":"-"," ",d!=null?o.jsxs("span",{style:{fontSize:11,opacity:.8},children:["($",d.toFixed(4),")"]}):null]})]})]}),o.jsxs("div",{className:"detail-section",children:[o.jsxs("h3",{children:["空仓 ",e.ShortExchange||"-"]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"入场价"}),o.jsxs("span",{className:"value",children:["$",(e.ShortEntry||0).toFixed(6)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"出场价"}),o.jsxs("span",{className:"value",children:["$",(e.ShortExit||0).toFixed(6)]})]}),o.jsxs("div",{className:"detail-row",children:[o.jsx("span",{className:"label",children:"盈亏"}),o.jsxs("span",{className:"value "+(e.ShortPnl>0?"text-green":e.ShortPnl<0?"text-red":""),children:[e.ShortPnl!=null?e.ShortPnl.toFixed(4)+"%":"-"," ",f!=null?o.jsxs("span",{style:{fontSize:11,opacity:.8},children:["($",f.toFixed(4),")"]}):null]})]})]}),o.jsxs("div",{className:"detail-section detail-section-full",children:[o.jsx("h3",{children:"净收益"}),o.jsxs("div",{className:"detail-row",style:{fontSize:16},children:[o.jsx("span",{className:"label",children:"总计"}),o.jsxs("span",{className:"value "+u,style:{fontWeight:700},children:[e.NetPnl!=null?e.NetPnl.toFixed(4)+"%":"-"," ",c!=null?o.jsxs("span",{style:{fontSize:12,opacity:.8},children:["($",c.toFixed(4),")"]}):null]})]})]})]}),t.length>0&&o.jsxs("div",{className:"detail-section detail-section-full",style:{borderTop:"1px solid var(--border)"},children:[o.jsxs("h3",{children:["订单明细 (",t.length,")"]}),o.jsxs("table",{className:"detail-orders",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"交易所"}),o.jsx("th",{children:"类型"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"价格"}),o.jsx("th",{children:"仓位"}),o.jsx("th",{children:"手续费"}),o.jsx("th",{children:"订单ID"})]})}),o.jsx("tbody",{children:a.map((g,x)=>o.jsxs("tr",{children:[o.jsx("td",{children:g.Exchange}),o.jsx("td",{children:g.Type==="entry"?"开仓":g.Type==="exit"?"平仓":g.Type==="scale"?"加仓":g.Type}),o.jsx("td",{children:g.Side==="buy"?"买":"卖"}),o.jsxs("td",{children:["$",(g.Price||0).toFixed(6)]}),o.jsx("td",{className:"text-right",children:g.Size!=null?Number(g.Size).toFixed(4):"-"}),o.jsx("td",{children:g.Fee!=null?"$"+g.Fee.toFixed(4):"-"}),o.jsx("td",{children:g.OrderID?g.OrderID.substring(0,12)+"...":"-"})]},x))})]})]})]})]})})}function Qf(){const e=z.useRef(null),[t,n]=z.useState([]),[r,l]=z.useState(0);return z.useEffect(()=>{async function i(){try{const d=((await(await fetch("/api/trades?limit=1000")).json()).trades||[]).filter(c=>c.ClosedAt&&c.NetPnl!=null).sort((c,g)=>new Date(c.ClosedAt)-new Date(g.ClosedAt));n(d);const f=d.reduce((c,g)=>c+2*(g.AmountUSD||0)*(g.NetPnl||0)/100,0);l(f)}catch{}}i();const s=setInterval(i,1e4);return()=>clearInterval(s)},[]),z.useEffect(()=>{const i=e.current;if(!i||t.length<2)return;const s=i.parentElement.getBoundingClientRect(),u=window.devicePixelRatio||1,a=s.width,d=s.height;i.width=a*u,i.height=d*u,i.style.width=a+"px",i.style.height=d+"px";const f=i.getContext("2d");f.scale(u,u);const c={top:20,right:20,bottom:35,left:55},g=a-c.left-c.right,x=d-c.top-c.bottom,v=[];let w=0;if(t.length>0){const M=new Date(t[0].ClosedAt).getTime()-1e3;v.push({x:M,y:0})}for(const M of t)w+=2*(M.AmountUSD||0)*(M.NetPnl||0)/100,v.push({x:new Date(M.ClosedAt).getTime(),y:w});const R=v[0].x,p=v[v.length-1].x,h=v.map(M=>M.y),m=Math.min(0,...h),y=Math.max(0,...h),S=Math.max(y-m,.01),_=S*.15,C=M=>c.left+(M-R)/Math.max(p-R,1)*g,E=M=>c.top+x-(M-(m-_))/(S+2*_)*x;f.clearRect(0,0,a,d),f.strokeStyle="rgba(48,54,61,0.5)",f.lineWidth=1,f.font="11px sans-serif",f.fillStyle="#8b949e";const A=5;for(let M=0;M<=A;M++){const fe=m-_+(S+2*_)*M/A,te=E(fe);f.beginPath(),f.moveTo(c.left,te),f.lineTo(a-c.right,te),f.stroke(),f.fillText("$"+fe.toFixed(2),2,te+4)}if(m<0&&y>0){const M=E(0);f.strokeStyle="rgba(248,81,73,0.3)",f.lineWidth=1,f.setLineDash([4,4]),f.beginPath(),f.moveTo(c.left,M),f.lineTo(a-c.right,M),f.stroke(),f.setLineDash([])}const T=Math.min(6,v.length);for(let M=0;M=0?"#3fb950":"#f85149",f.fill(),f.strokeStyle="#0d1117",f.lineWidth=2,f.stroke(),f.fillStyle="#c9d1d9",f.font="bold 13px sans-serif",f.textAlign="center",f.fillText("$"+Pe.y.toFixed(2),Be,Nt-12)},[t]),o.jsxs("section",{className:"card card-wide",id:"pnl-chart-card",children:[o.jsxs("h2",{children:["📈 总PnL成长曲线 ",o.jsx("span",{className:"text-dim",style:{fontSize:11},children:t.length>0?`$${r.toFixed(2)}`:""})]}),o.jsx("div",{className:"chart-container",style:{height:260},children:t.length<1?o.jsx("div",{className:"loading",style:{paddingTop:100},children:"暂无数据..."}):o.jsx("canvas",{ref:e})})]})}function Kf({momentum:e}){const[t,n]=z.useState("score"),[r,l]=z.useState("desc");function i(c){t===c?l(r==="asc"?"desc":"asc"):(n(c),l("desc"))}function s(c){return t!==c?"":r==="asc"?" ▲":" ▼"}const u=[...e].sort((c,g)=>{let x,v;switch(t){case"coin":x=c.coin,v=g.coin;break;case"bg_1s":x=c.bg_1s||0,v=g.bg_1s||0;break;case"bg_5s":x=c.bg_5s||0,v=g.bg_5s||0;break;case"bg_15s":x=c.bg_15s||0,v=g.bg_15s||0;break;case"hl_1s":x=c.hl_1s||0,v=g.hl_1s||0;break;case"hl_5s":x=c.hl_5s||0,v=g.hl_5s||0;break;case"hl_15s":x=c.hl_15s||0,v=g.hl_15s||0;break;case"bn_1s":x=c.bn_1s||0,v=g.bn_1s||0;break;case"bn_5s":x=c.bn_5s||0,v=g.bn_5s||0;break;case"bn_15s":x=c.bn_15s||0,v=g.bn_15s||0;break;case"okx_1s":x=c.okx_1s||0,v=g.okx_1s||0;break;case"okx_5s":x=c.okx_5s||0,v=g.okx_5s||0;break;case"okx_15s":x=c.okx_15s||0,v=g.okx_15s||0;break;default:x=c.score||0,v=g.score||0}return typeof x=="string"?r==="asc"?x.localeCompare(v):v.localeCompare(x):r==="asc"?x-v:v-x});function a(c){switch(c){case"up":return"↑";case"down":return"↓";case"flat":return"→";case"mixed":return"↕";default:return"-"}}function d(c){switch(c){case"up":return"text-green";case"down":return"text-red";case"mixed":return"text-yellow";default:return""}}function f(c){return c==null||c===0?"":c>0?"text-green":"text-red"}return o.jsxs("section",{className:"card card-wide",id:"momentum-card",children:[o.jsx("h2",{children:"⚡ 动量扫描 (价格变动%)"}),o.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:o.jsxs("table",{id:"momentum-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsxs("th",{onClick:()=>i("coin"),style:{cursor:"pointer"},children:["币种",s("coin")]}),o.jsxs("th",{onClick:()=>i("score"),style:{cursor:"pointer"},children:["分数",s("score")]}),o.jsx("th",{children:"方向"}),o.jsxs("th",{onClick:()=>i("bg_1s"),style:{cursor:"pointer"},children:["BG 1s",s("bg_1s")]}),o.jsxs("th",{onClick:()=>i("bg_5s"),style:{cursor:"pointer"},children:["BG 5s",s("bg_5s")]}),o.jsxs("th",{onClick:()=>i("bg_15s"),style:{cursor:"pointer"},children:["BG 15s",s("bg_15s")]}),o.jsxs("th",{onClick:()=>i("hl_1s"),style:{cursor:"pointer"},children:["HL 1s",s("hl_1s")]}),o.jsxs("th",{onClick:()=>i("hl_5s"),style:{cursor:"pointer"},children:["HL 5s",s("hl_5s")]}),o.jsxs("th",{onClick:()=>i("hl_15s"),style:{cursor:"pointer"},children:["HL 15s",s("hl_15s")]}),o.jsxs("th",{onClick:()=>i("bn_1s"),style:{cursor:"pointer"},children:["BN 1s",s("bn_1s")]}),o.jsxs("th",{onClick:()=>i("bn_5s"),style:{cursor:"pointer"},children:["BN 5s",s("bn_5s")]}),o.jsxs("th",{onClick:()=>i("bn_15s"),style:{cursor:"pointer"},children:["BN 15s",s("bn_15s")]}),o.jsxs("th",{onClick:()=>i("okx_1s"),style:{cursor:"pointer"},children:["OKX 1s",s("okx_1s")]}),o.jsxs("th",{onClick:()=>i("okx_5s"),style:{cursor:"pointer"},children:["OKX 5s",s("okx_5s")]}),o.jsxs("th",{onClick:()=>i("okx_15s"),style:{cursor:"pointer"},children:["OKX 15s",s("okx_15s")]})]})}),o.jsx("tbody",{children:u.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"15",className:"text-dim",style:{textAlign:"center",padding:20},children:"正在收集动量数据... (需要至少 15 秒数据)"})}):u.slice(0,50).map(c=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:c.coin})}),o.jsxs("td",{className:"text-right",style:{fontWeight:700},children:[c.score.toFixed(4),"%"]}),o.jsx("td",{className:d(c.direction),style:{textAlign:"center",fontSize:18},children:a(c.direction)}),o.jsx("td",{className:"text-right "+f(c.bg_1s),children:c.bg_1s!=null?c.bg_1s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.bg_5s),children:c.bg_5s!=null?c.bg_5s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.bg_15s),children:c.bg_15s!=null?c.bg_15s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.hl_1s),children:c.hl_1s!=null?c.hl_1s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.hl_5s),children:c.hl_5s!=null?c.hl_5s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.hl_15s),children:c.hl_15s!=null?c.hl_15s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.bn_1s),children:c.bn_1s!=null?c.bn_1s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.bn_5s),children:c.bn_5s!=null?c.bn_5s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.bn_15s),children:c.bn_15s!=null?c.bn_15s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.okx_1s),children:c.okx_1s!=null?c.okx_1s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.okx_5s),children:c.okx_5s!=null?c.okx_5s.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+f(c.okx_15s),children:c.okx_15s!=null?c.okx_15s.toFixed(3)+"%":"-"})]},c.coin))})]})})]})}function Xf({trend:e}){function t(s){switch(s){case"alert":return"⚠ 异动";case"confirmed":return"🚀 趋势";case"exhausting":return"🔄 衰减";default:return s}}function n(s){switch(s){case"alert":return"trend-alert";case"confirmed":return"trend-confirmed";case"exhausting":return"trend-exhausting";default:return""}}function r(s){return s==="up"?"↑":"↓"}function l(s){return s==="up"?"text-green":"text-red"}function i(s){return s==null||s===0?"":s>0?"text-green":"text-red"}return o.jsxs("section",{className:"card card-wide",id:"trend-card",children:[o.jsx("h2",{children:"📈 趋势检测 (价格异动)"}),o.jsx("div",{className:"table-wrap",style:{maxHeight:300},children:o.jsxs("table",{id:"trend-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"币种"}),o.jsx("th",{children:"状态"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"异动分"}),o.jsx("th",{children:"波动率"}),o.jsx("th",{children:"一致数"}),o.jsx("th",{children:"BG 15s"}),o.jsx("th",{children:"HL 15s"}),o.jsx("th",{children:"BN 15s"}),o.jsx("th",{children:"OKX 15s"}),o.jsx("th",{children:"时长"})]})}),o.jsx("tbody",{children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"11",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待检测数据... (需要至少 3 个交易所数据)"})}):e.slice(0,30).map(s=>o.jsxs("tr",{className:n(s.state),children:[o.jsx("td",{children:o.jsx("strong",{children:s.coin})}),o.jsx("td",{className:"trend-state",children:t(s.state)}),o.jsx("td",{className:l(s.direction),style:{textAlign:"center",fontSize:18},children:r(s.direction)}),o.jsxs("td",{className:"text-right",style:{fontWeight:700},children:[(s.anomaly_score||0).toFixed(1),"σ"]}),o.jsxs("td",{className:"text-right",children:[(s.volatility||0).toFixed(4),"%"]}),o.jsxs("td",{className:"text-right",children:[s.ex_changes||0,"/4"]}),o.jsx("td",{className:"text-right "+i(s.bg_change),children:s.bg_change!=null?s.bg_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.hl_change),children:s.hl_change!=null?s.hl_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.bn_change),children:s.bn_change!=null?s.bn_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.okx_change),children:s.okx_change!=null?s.okx_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-dim",children:s.duration||"-"})]},s.coin))})]})})]})}function Gf({data:e}){function t(i){switch(i){case"rising":return"↑ 上涨";case"falling":return"↓ 下跌";default:return"− 中性"}}function n(i){switch(i){case"rising":return"text-green";case"falling":return"text-red";default:return"text-dim"}}function r(i){return i==="up"?"text-green":"text-red"}function l(i){return i==null||i===0?"":i>0?"text-green":"text-red"}return o.jsxs("section",{className:"card card-wide",id:"cm-card",children:[o.jsx("h2",{children:"📊 累积变动 (1min 共识)"}),o.jsx("div",{className:"table-wrap",style:{maxHeight:300},children:o.jsxs("table",{id:"cm-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"币种"}),o.jsx("th",{children:"状态"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"分数"}),o.jsx("th",{children:"均值%"}),o.jsx("th",{children:"一致"}),o.jsx("th",{children:"BG 1m"}),o.jsx("th",{children:"HL 1m"}),o.jsx("th",{children:"BN 1m"}),o.jsx("th",{children:"OKX 1m"}),o.jsx("th",{children:"BG 5m"}),o.jsx("th",{children:"HL 5m"}),o.jsx("th",{children:"BN 5m"}),o.jsx("th",{children:"OKX 5m"})]})}),o.jsx("tbody",{children:!e||e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"14",className:"text-dim",style:{textAlign:"center",padding:20},children:"等待累积数据... (需要至少 1 分钟数据)"})}):e.slice(0,30).map(i=>o.jsxs("tr",{className:n(i.state),children:[o.jsx("td",{children:o.jsx("strong",{children:i.coin})}),o.jsx("td",{children:t(i.state)}),o.jsx("td",{className:r(i.direction),style:{textAlign:"center",fontSize:16},children:i.direction==="up"?"↑":"↓"}),o.jsx("td",{className:"text-right",style:{fontWeight:700},children:(i.score||0).toFixed(2)}),o.jsxs("td",{className:"text-right",children:[(i.avg_change||0).toFixed(3),"%"]}),o.jsxs("td",{className:"text-right",children:[i.ex_agree||0,"/",i.ex_total||0]}),o.jsx("td",{className:"text-right "+l(i.bg_1m),children:i.bg_1m!=null?i.bg_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.hl_1m),children:i.hl_1m!=null?i.hl_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bn_1m),children:i.bn_1m!=null?i.bn_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.okx_1m),children:i.okx_1m!=null?i.okx_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bg_5m),children:i.bg_5m!=null?i.bg_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.hl_5m),children:i.hl_5m!=null?i.hl_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bn_5m),children:i.bn_5m!=null?i.bn_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.okx_5m),children:i.okx_5m!=null?i.okx_5m.toFixed(3)+"%":"-"})]},i.coin))})]})})]})}function Yf({history:e}){function t(i){switch(i){case"rising":return"↑ 上涨";case"falling":return"↓ 下跌";default:return"− 中性"}}function n(i){switch(i){case"rising":return"text-green";case"falling":return"text-red";default:return"text-dim"}}function r(i){return i==="up"?"text-green":"text-red"}function l(i){return i==null||i===0?"":i>0?"text-green":"text-red"}return o.jsxs("section",{className:"card card-wide",id:"cm-history-card",children:[o.jsx("h2",{children:"📋 累积变动事件记录"}),o.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:o.jsxs("table",{id:"cm-history-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"时间"}),o.jsx("th",{children:"币种"}),o.jsx("th",{children:"转换"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"分数"}),o.jsx("th",{children:"均值%"}),o.jsx("th",{children:"一致"}),o.jsx("th",{children:"BG 1m"}),o.jsx("th",{children:"HL 1m"}),o.jsx("th",{children:"BN 1m"}),o.jsx("th",{children:"OKX 1m"}),o.jsx("th",{children:"BG 5m"}),o.jsx("th",{children:"HL 5m"}),o.jsx("th",{children:"BN 5m"}),o.jsx("th",{children:"OKX 5m"})]})}),o.jsx("tbody",{children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"15",className:"text-dim",style:{textAlign:"center",padding:20},children:"暂无累积变动事件记录"})}):e.slice(0,100).map((i,s)=>o.jsxs("tr",{children:[o.jsx("td",{className:"text-dim",children:i.created_at?new Date(i.created_at).toLocaleTimeString("zh-CN",{hour12:!1}):"-"}),o.jsx("td",{children:o.jsx("strong",{children:i.coin})}),o.jsxs("td",{className:n(i.new_state),children:[i.prev_state," → ",t(i.new_state)]}),o.jsx("td",{className:r(i.direction),style:{textAlign:"center",fontSize:16},children:i.direction==="up"?"↑":"↓"}),o.jsx("td",{className:"text-right",children:(i.score||0).toFixed(2)}),o.jsxs("td",{className:"text-right",children:[(i.avg_change||0).toFixed(3),"%"]}),o.jsxs("td",{className:"text-right",children:[i.ex_agree||0,"/",i.ex_total||0]}),o.jsx("td",{className:"text-right "+l(i.bg_1m),children:i.bg_1m!=null?i.bg_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.hl_1m),children:i.hl_1m!=null?i.hl_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bn_1m),children:i.bn_1m!=null?i.bn_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.okx_1m),children:i.okx_1m!=null?i.okx_1m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bg_5m),children:i.bg_5m!=null?i.bg_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.hl_5m),children:i.hl_5m!=null?i.hl_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.bn_5m),children:i.bn_5m!=null?i.bn_5m.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+l(i.okx_5m),children:i.okx_5m!=null?i.okx_5m.toFixed(3)+"%":"-"})]},(i.id||s)+"-cm"))})]})})]})}function Zf({history:e}){function t(s){switch(s){case"alert":return"⚠ 异动";case"confirmed":return"🚀 趋势";case"exhausting":return"🔄 衰减";case"idle":return"✓ 结束";default:return s}}function n(s){switch(s){case"alert":return"text-yellow";case"confirmed":return"text-green";case"exhausting":return"text-dim";case"idle":return"text-dim";default:return""}}function r(s){return s==="up"?"↑":"↓"}function l(s){return s==="up"?"text-green":"text-red"}function i(s){return s==null||s===0?"":s>0?"text-green":"text-red"}return o.jsxs("section",{className:"card card-wide",id:"trend-history-card",children:[o.jsx("h2",{children:"📋 趋势事件记录"}),o.jsx("div",{className:"table-wrap",style:{maxHeight:400},children:o.jsxs("table",{id:"trend-history-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"时间"}),o.jsx("th",{children:"币种"}),o.jsx("th",{children:"转换"}),o.jsx("th",{children:"方向"}),o.jsx("th",{children:"异动分"}),o.jsx("th",{children:"波动率"}),o.jsx("th",{children:"一致"}),o.jsx("th",{children:"BG"}),o.jsx("th",{children:"HL"}),o.jsx("th",{children:"BN"}),o.jsx("th",{children:"OKX"})]})}),o.jsx("tbody",{children:e.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:"11",className:"text-dim",style:{textAlign:"center",padding:20},children:"暂无趋势事件记录"})}):e.slice(0,100).map((s,u)=>o.jsxs("tr",{children:[o.jsx("td",{className:"text-dim",children:s.timestamp?new Date(s.timestamp).toLocaleTimeString("zh-CN",{hour12:!1}):s.created_at?new Date(s.created_at).toLocaleTimeString("zh-CN",{hour12:!1}):"-"}),o.jsx("td",{children:o.jsx("strong",{children:s.coin})}),o.jsxs("td",{className:n(s.new_state),children:[s.prev_state," → ",t(s.new_state)]}),o.jsx("td",{className:l(s.direction),style:{textAlign:"center",fontSize:16},children:r(s.direction)}),o.jsxs("td",{className:"text-right",children:[(s.z_score||0).toFixed(1),"σ"]}),o.jsxs("td",{className:"text-right",children:[(s.volatility||0).toFixed(4),"%"]}),o.jsxs("td",{className:"text-right",children:[s.ex_agree||0,"/",s.ex_total||0]}),o.jsx("td",{className:"text-right "+i(s.bg_change),children:s.bg_change!=null?s.bg_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.hl_change),children:s.hl_change!=null?s.hl_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.bn_change),children:s.bn_change!=null?s.bn_change.toFixed(3)+"%":"-"}),o.jsx("td",{className:"text-right "+i(s.okx_change),children:s.okx_change!=null?s.okx_change.toFixed(3)+"%":"-"})]},(s.timestamp||s.id||u)+"-"+u))})]})})]})}Gl.createRoot(document.getElementById("root")).render(o.jsx(Nc.StrictMode,{children:o.jsx($f,{})})); diff --git a/frontend/dist/index.html b/frontend/dist/index.html index de016e4..aafcf58 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -4,8 +4,8 @@ Exchange Monitor Dashboard - - + +
diff --git a/frontend/src/App.css b/frontend/src/App.css index c1ae7c0..08d1378 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -242,3 +242,23 @@ tr:hover td { background: rgba(88, 166, 255, 0.05); } .trend-confirmed:hover td { background: rgba(63, 185, 80, 0.15) !important; } .trend-exhausting { background: rgba(139, 148, 158, 0.05); } .trend-exhausting:hover td { background: rgba(139, 148, 158, 0.1) !important; } + +/* Trend Filter Card */ +.text-orange { color: var(--yellow); } +#trend-filter-card { grid-column: 1 / -1; } +#trend-filter-table td { font-variant-numeric: tabular-nums; } +.filter-pass td { background: rgba(63, 185, 80, 0.06); } +.filter-pass:hover td { background: rgba(63, 185, 80, 0.12) !important; } + +/* blue text for categories */ +.text-blue { color: #58a6ff; } + +/* Trend Signal Card */ +#trend-signal-card { grid-column: 1 / -1; } +#trend-signal-table td { font-variant-numeric: tabular-nums; } +#high-score-card { grid-column: 1 / -1; } +#high-score-table td { font-variant-numeric: tabular-nums; } +.signal-enter td { background: rgba(63, 185, 80, 0.08); } +.signal-enter:hover td { background: rgba(63, 185, 80, 0.15) !important; } +.signal-exit td { background: rgba(139, 148, 158, 0.05); } +.signal-exit:hover td { background: rgba(139, 148, 158, 0.1) !important; } diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 4f40553..bda7589 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -28,9 +28,10 @@ export default function App() { const [trades, setTrades] = useState([]) const [momentum, setMomentum] = useState([]) const [trendData, setTrendData] = useState([]) - const [trendHistory, setTrendHistory] = useState([]) const [cmData, setCmData] = useState([]) const [cmHistory, setCmHistory] = useState([]) + const [trendFilter, setTrendFilter] = useState([]) + const [trendSignals, setTrendSignals] = useState([]) const priceCacheRef = useRef({}) // Clock @@ -83,6 +84,13 @@ export default function App() { case 'cumulative': setCmData(msg.data || []) break + case 'trend_filter': + setTrendFilter(msg.data || []) + break + case 'trend_signal': + // Prepend new signal to list + setTrendSignals(prev => [msg.data, ...prev].slice(0, 100)) + break case 'stats': setStats(msg.data || {}) if (msg.data && msg.data.blacklist) { @@ -118,23 +126,6 @@ export default function App() { return () => clearInterval(id) }, [loadTrades]) - // Load trend history - const loadTrendHistory = useCallback(async () => { - try { - const resp = await fetch('/api/trend-history') - const data = await resp.json() - setTrendHistory(data.events || []) - } catch (err) { - // ignore - } - }, []) - - useEffect(() => { - loadTrendHistory() - const id = setInterval(loadTrendHistory, 5000) - return () => clearInterval(id) - }, [loadTrendHistory]) - // Load cumulative history const loadCmHistory = useCallback(async () => { try { @@ -152,6 +143,23 @@ export default function App() { return () => clearInterval(id) }, [loadCmHistory]) + // Load trend signals from API + const loadTrendSignals = useCallback(async () => { + try { + const resp = await fetch('/api/trend-signals') + const data = await resp.json() + if (data.signals) setTrendSignals(data.signals) + } catch (err) { + // ignore + } + }, []) + + useEffect(() => { + loadTrendSignals() + const id = setInterval(loadTrendSignals, 5000) + return () => clearInterval(id) + }, [loadTrendSignals]) + // Handle prices function handlePrices(data) { if (!data || data.length === 0) return @@ -210,6 +218,21 @@ export default function App() {
+ {/* Trend Filter (K-line quiet + EMA52) — 最优先 */} + + + {/* Full Signal Records (FreshAnomaly + Score >= 70) */} + + + {/* High Score Signal Records (Score >= 90) */} + + + {/* Cumulative Change (1min consensus) */} + + + {/* Cumulative History */} + + {/* Price Table */} @@ -219,18 +242,6 @@ export default function App() { {/* Momentum Scanner */} - {/* Trend Detection */} - - - {/* Trend History */} - - - {/* Cumulative Change (1min consensus) */} - - - {/* Cumulative History */} - - {/* ---- 交易相关 ---- */} {/* Stats Summary */} @@ -958,87 +969,6 @@ function MomentumCard({ momentum }) { ) } -// ============ Trend Detection Card ============ -function TrendCard({ trend }) { - function stateLabel(state) { - switch (state) { - case 'alert': return '⚠ 异动' - case 'confirmed': return '🚀 趋势' - case 'exhausting': return '🔄 衰减' - default: return state - } - } - - function stateClass(state) { - switch (state) { - case 'alert': return 'trend-alert' - case 'confirmed': return 'trend-confirmed' - case 'exhausting': return 'trend-exhausting' - default: return '' - } - } - - function dirIcon(dir) { - return dir === 'up' ? '\u2191' : '\u2193' - } - - function dirClass(dir) { - return dir === 'up' ? 'text-green' : 'text-red' - } - - function changeClass(val) { - if (val == null || val === 0) return '' - return val > 0 ? 'text-green' : 'text-red' - } - - return ( -
-

📈 趋势检测 (价格异动)

-
- - - - - - - - - - - - - - - - - - {trend.length === 0 ? ( - - ) : trend.slice(0, 30).map(entry => ( - - - - - - - - - - - - - - ))} - -
币种状态方向异动分波动率一致数BG 15sHL 15sBN 15sOKX 15s时长
- 等待检测数据... (需要至少 3 个交易所数据) -
{entry.coin}{stateLabel(entry.state)}{dirIcon(entry.direction)}{(entry.anomaly_score || 0).toFixed(1)}σ{(entry.volatility || 0).toFixed(4)}%{entry.ex_changes || 0}/4{entry.bg_change != null ? entry.bg_change.toFixed(3) + '%' : '-'}{entry.hl_change != null ? entry.hl_change.toFixed(3) + '%' : '-'}{entry.bn_change != null ? entry.bn_change.toFixed(3) + '%' : '-'}{entry.okx_change != null ? entry.okx_change.toFixed(3) + '%' : '-'}{entry.duration || '-'}
-
-
- ) -} - -// ============ Trend History Card ============ // ============ Cumulative Change Card (1min consensus) ============ function CmCard({ data }) { function stateLabel(state) { @@ -1087,11 +1017,16 @@ function CmCard({ data }) { HL 5m BN 5m OKX 5m + 1h 趋势 + BG 1h + HL 1h + BN 1h + OKX 1h {!data || data.length === 0 ? ( - + 等待累积数据... (需要至少 1 分钟数据) ) : data.slice(0, 30).map(entry => ( @@ -1110,6 +1045,11 @@ function CmCard({ data }) { {entry.hl_5m != null ? entry.hl_5m.toFixed(3) + '%' : '-'} {entry.bn_5m != null ? entry.bn_5m.toFixed(3) + '%' : '-'} {entry.okx_5m != null ? entry.okx_5m.toFixed(3) + '%' : '-'} + {(entry.avg_1h || 0).toFixed(2)}% + {entry.bg_1h != null ? entry.bg_1h.toFixed(2) + '%' : '-'} + {entry.hl_1h != null ? entry.hl_1h.toFixed(2) + '%' : '-'} + {entry.bn_1h != null ? entry.bn_1h.toFixed(2) + '%' : '-'} + {entry.okx_1h != null ? entry.okx_1h.toFixed(2) + '%' : '-'} ))} @@ -1201,78 +1141,85 @@ function CmHistoryCard({ history }) { ) } -function TrendHistoryCard({ history }) { - function stateLabel(state) { - switch (state) { - case 'alert': return '⚠ 异动' - case 'confirmed': return '🚀 趋势' - case 'exhausting': return '🔄 衰减' - case 'idle': return '✓ 结束' - default: return state +function TrendFilterCard({ filterData }) { + const passing = filterData.filter(f => f.passes_filter).length + const highScore = filterData.filter(f => f.signal_score >= 80).length + const midScore = filterData.filter(f => f.signal_score >= 50 && f.signal_score < 80).length + const anomalyCount = filterData.filter(f => f.fresh_anomaly).length + + // Build header description + let desc = `高分${highScore} 中分${midScore}` + if (anomalyCount > 0) { + desc += ` | ${anomalyCount}币异动中` + if (passing > 0) { + desc += ` → ${passing}通过!` } + } else { + desc += ' | 等待异动信号' } - function stateClass(state) { - switch (state) { - case 'alert': return 'text-yellow' - case 'confirmed': return 'text-green' - case 'exhausting': return 'text-dim' - case 'idle': return 'text-dim' - default: return '' - } + function scoreClass(s) { + if (s == null) return '' + if (s >= 80) return 'text-green' + if (s >= 50) return 'text-yellow' + return 'text-dim' } - function dirIcon(dir) { - return dir === 'up' ? '\u2191' : '\u2193' + function volClass(r) { + if (r == null || r <= 1.5) return '' + if (r > 3.0) return 'text-red' + return 'text-orange' } - function dirClass(dir) { - return dir === 'up' ? 'text-green' : 'text-red' - } - - function changeClass(val) { - if (val == null || val === 0) return '' - return val > 0 ? 'text-green' : 'text-red' + function slopeClass(s) { + if (s == null || s === 0) return '' + return s > 0 ? 'text-green' : 'text-red' } return ( -
-

📋 趋势事件记录

+
+

趋势过滤 ({passing}通过 / {filterData.length}) {desc}

- +
- - - - - - - - - - + + + + + + + + + + + + + + - {history.length === 0 ? ( - - ) : history.slice(0, 100).map((ev, i) => ( - - - - - - - - - - - - + {filterData.length === 0 ? ( + + ) : filterData.map(entry => ( + + + + + + + + + + + + + + + + ))} @@ -1281,3 +1228,107 @@ function TrendHistoryCard({ history }) { ) } + +// ============ Full Signal Records Card (FreshAnomaly + Score >= 70) ============ +function FullSignalCard({ signals }) { + const filtered = signals.filter(s => s.category === 'full') + const enterCount = filtered.filter(s => s.type === 'enter').length + + return ( +
+

完整信号 (异动+分数≥70) {enterCount > 0 && 共{enterCount}条}

+
+
时间 币种转换方向异动分波动率一致BGHLBNOKX分数24h范围基线1h范围成交量比1h变化EMA52EMA斜率现价> EMA安静24h安静1h异动更新于
- 暂无趋势事件记录 -
{ev.timestamp ? new Date(ev.timestamp).toLocaleTimeString('zh-CN', { hour12: false }) : (ev.created_at ? new Date(ev.created_at).toLocaleTimeString('zh-CN', { hour12: false }) : '-')}{ev.coin}{ev.prev_state} → {stateLabel(ev.new_state)}{dirIcon(ev.direction)}{(ev.z_score || 0).toFixed(1)}σ{(ev.volatility || 0).toFixed(4)}%{ev.ex_agree || 0}/{ev.ex_total || 0}{ev.bg_change != null ? ev.bg_change.toFixed(3) + '%' : '-'}{ev.hl_change != null ? ev.hl_change.toFixed(3) + '%' : '-'}{ev.bn_change != null ? ev.bn_change.toFixed(3) + '%' : '-'}{ev.okx_change != null ? ev.okx_change.toFixed(3) + '%' : '-'}
等待K线数据...
{entry.coin}{entry.signal_score != null ? entry.signal_score.toFixed(0) : '-'}{entry.range_24h != null ? entry.range_24h.toFixed(2) + '%' : '-'}{entry.vol_baseline != null ? entry.vol_baseline.toFixed(2) + '%' : '-'}{entry.range_1h != null ? entry.range_1h.toFixed(2) + '%' : '-'}{entry.volume_ratio != null ? entry.volume_ratio.toFixed(2) + 'x' : '-'} 0 ? 'text-green' : entry.change_1h < 0 ? 'text-red' : '')}>{entry.change_1h != null ? (entry.change_1h > 0 ? '+' : '') + entry.change_1h.toFixed(2) + '%' : '-'}{entry.ema_52 ? entry.ema_52.toFixed(4) : '-'}{entry.ema_slope != null ? (entry.ema_slope > 0 ? '+' : '') + entry.ema_slope.toFixed(3) + '%' : '-'}{entry.current_price ? entry.current_price.toFixed(4) : '-'}{entry.price_above_ema != null ? (entry.price_above_ema ? '↑' : '↓') : '-'}{entry.quiet_24h != null ? (entry.quiet_24h ? '✓' : '✗') : '-'}{entry.quiet_1h != null ? (entry.quiet_1h ? '✓' : '✗') : '-'}{entry.fresh_anomaly != null ? (entry.fresh_anomaly ? '⚠' : '-') : '-'}{entry.last_updated ? new Date(entry.last_updated).toLocaleTimeString('zh-CN', {hour12:false}) : '-'}
+ + + + + + + + + + + + + + {filtered.length === 0 ? ( + + ) : filtered.slice(0, 50).map((s, i) => { + const rowClass = s.type === 'enter' ? 'signal-enter' : 'signal-exit' + const ts = s.timestamp ? new Date(s.timestamp).toLocaleTimeString('zh-CN', { hour12: false }) : '-' + return ( + + + + + + + + + + + ) + })} + +
时间币种类型分数价格成交量比EMA斜率趋势状态
+ 等待完整信号... (FreshAnomaly + 分数≥70) +
{ts}{s.coin} + {s.type === 'enter' ? '开' : '关'} + {s.signal_score != null ? s.signal_score.toFixed(0) : '-'}{s.price ? s.price.toFixed(4) : '-'}{s.volume_ratio != null ? s.volume_ratio.toFixed(2) + 'x' : '-'}{s.ema_slope != null ? (s.ema_slope > 0 ? '+' : '') + s.ema_slope.toFixed(3) + '%' : '-'}{s.state || '-'}
+
+
+ ) +} + +// ============ High Score Signal Records Card (Score >= 90) ============ +function HighScoreCard({ signals }) { + const filtered = signals.filter(s => s.category === 'high') + const enterCount = filtered.filter(s => s.type === 'enter').length + + return ( +
+

高分信号 (分数≥90) {enterCount > 0 && 共{enterCount}条}

+
+ + + + + + + + + + + + + + + {filtered.length === 0 ? ( + + ) : filtered.slice(0, 50).map((s, i) => { + const rowClass = s.type === 'enter' ? 'signal-enter' : 'signal-exit' + const ts = s.timestamp ? new Date(s.timestamp).toLocaleTimeString('zh-CN', { hour12: false }) : '-' + return ( + + + + + + + + + + + ) + })} + +
时间币种类型分数价格成交量比EMA斜率趋势状态
+ 等待高分信号... (分数≥90) +
{ts}{s.coin} + {s.type === 'enter' ? '开' : '关'} + {s.signal_score != null ? s.signal_score.toFixed(0) : '-'}{s.price ? s.price.toFixed(4) : '-'}{s.volume_ratio != null ? s.volume_ratio.toFixed(2) + 'x' : '-'}{s.ema_slope != null ? (s.ema_slope > 0 ? '+' : '') + s.ema_slope.toFixed(3) + '%' : '-'}{s.state || '-'}
+
+
+ ) +} diff --git a/main.go b/main.go index 0cfd2cc..cb0b872 100644 --- a/main.go +++ b/main.go @@ -75,6 +75,11 @@ func main() { cumulativeTracker := NewCumulativeTracker() log.Printf("[CM] Cumulative change tracking enabled (1m >= %.1f%%, 3+ exchanges)", cumulativeTracker.surgePct1m) + // Initialize trend filter (Binance K-line based quiet + EMA52 filter) + trendFilter := NewTrendFilter(store, trendDetector) + trendFilter.Start() + defer trendFilter.Stop() + // Initialize SQLite database database, err := db.Open("") if err != nil { @@ -90,7 +95,7 @@ func main() { trader.startIPCServer() // Initialize dashboard (web server + SSE) - dashboard := NewDashboard(store, trader, database, ":8888", cfg, momentumTracker, trendDetector, cumulativeTracker) + dashboard := NewDashboard(store, trader, database, ":8888", cfg, momentumTracker, trendDetector, cumulativeTracker, trendFilter) go dashboard.Run() // Spread window tracker — measures how long spreads stay above threshold diff --git a/momentum.go b/momentum.go index e3a3563..93ba021 100644 --- a/momentum.go +++ b/momentum.go @@ -18,6 +18,7 @@ var momentumWindows = []momentumWindow{ {"t1s", 20, "1s"}, {"t5s", 100, "5s"}, {"t15s", 300, "15s"}, + {"t60s", 1200, "60s"}, } const maxMomentumRecords = 600 @@ -35,15 +36,19 @@ type MomentumEntry struct { BG1s float64 `json:"bg_1s"` BG5s float64 `json:"bg_5s"` BG15s float64 `json:"bg_15s"` + BG60s float64 `json:"bg_60s"` HL1s float64 `json:"hl_1s"` HL5s float64 `json:"hl_5s"` HL15s float64 `json:"hl_15s"` + HL60s float64 `json:"hl_60s"` BN1s float64 `json:"bn_1s"` BN5s float64 `json:"bn_5s"` BN15s float64 `json:"bn_15s"` + BN60s float64 `json:"bn_60s"` OKX1s float64 `json:"okx_1s"` OKX5s float64 `json:"okx_5s"` OKX15s float64 `json:"okx_15s"` + OKX60s float64 `json:"okx_60s"` Score float64 `json:"score"` // max abs change across all windows Direction string `json:"direction"` // "up", "down", "flat", "mixed" } @@ -105,6 +110,7 @@ func (mt *MomentumTracker) Snapshot(thresholdPct float64) []MomentumEntry { entry.BG1s = changes[0] entry.BG5s = changes[1] entry.BG15s = changes[2] + entry.BG60s = changes[3] allChanges = append(allChanges, changes[:]...) } if hasHL { @@ -112,6 +118,7 @@ func (mt *MomentumTracker) Snapshot(thresholdPct float64) []MomentumEntry { entry.HL1s = changes[0] entry.HL5s = changes[1] entry.HL15s = changes[2] + entry.HL60s = changes[3] allChanges = append(allChanges, changes[:]...) } if hasBN { @@ -119,6 +126,7 @@ func (mt *MomentumTracker) Snapshot(thresholdPct float64) []MomentumEntry { entry.BN1s = changes[0] entry.BN5s = changes[1] entry.BN15s = changes[2] + entry.BN60s = changes[3] allChanges = append(allChanges, changes[:]...) } if hasOK { @@ -126,6 +134,7 @@ func (mt *MomentumTracker) Snapshot(thresholdPct float64) []MomentumEntry { entry.OKX1s = changes[0] entry.OKX5s = changes[1] entry.OKX15s = changes[2] + entry.OKX60s = changes[3] allChanges = append(allChanges, changes[:]...) } @@ -178,10 +187,10 @@ func (mt *MomentumTracker) Snapshot(thresholdPct float64) []MomentumEntry { return result } -// calcWindows computes change% for all 3 windows: (current - old) / old * 100. +// calcWindows computes change% for all windows: (current - old) / old * 100. // Returns 0 for windows that don't have enough data yet. -func calcWindows(buf *momentumBuffer) [3]float64 { - var result [3]float64 +func calcWindows(buf *momentumBuffer) [4]float64 { + var result [4]float64 for i, w := range momentumWindows { if buf.count < w.Ticks+1 { continue diff --git a/trend.go b/trend.go index c942a63..fda57d5 100644 --- a/trend.go +++ b/trend.go @@ -51,7 +51,7 @@ type TrendEntry struct { Direction TrendDirection `json:"direction"` AnomalyScore float64 `json:"anomaly_score"` // max z-score across all exchanges Volatility float64 `json:"volatility"` // current EMA volatility baseline - BGChange float64 `json:"bg_change"` // 15s change % + BGChange float64 `json:"bg_change"` // 60s change % HLChange float64 `json:"hl_change"` BNChange float64 `json:"bn_change"` OKXChange float64 `json:"okx_change"` @@ -72,6 +72,7 @@ type trendCoinState struct { state TrendState direction TrendDirection anomalyScore float64 + peakScore float64 // highest z-score seen during current cycle volatility float64 alertedAt time.Time @@ -198,19 +199,19 @@ func (td *TrendDetector) Tick() { defer td.mu.Unlock() for _, entry := range entries { - // Collect 15s changes from all 4 exchanges + // Collect 60s changes from all 4 exchanges var changes []exchangeChange - if entry.BG15s != 0 { - changes = append(changes, exchangeChange{name: ExBitget, change: entry.BG15s}) + if entry.BG60s != 0 { + changes = append(changes, exchangeChange{name: ExBitget, change: entry.BG60s}) } - if entry.HL15s != 0 { - changes = append(changes, exchangeChange{name: ExHyperLiquid, change: entry.HL15s}) + if entry.HL60s != 0 { + changes = append(changes, exchangeChange{name: ExHyperLiquid, change: entry.HL60s}) } - if entry.BN15s != 0 { - changes = append(changes, exchangeChange{name: ExBinance, change: entry.BN15s}) + if entry.BN60s != 0 { + changes = append(changes, exchangeChange{name: ExBinance, change: entry.BN60s}) } - if entry.OKX15s != 0 { - changes = append(changes, exchangeChange{name: ExOKX, change: entry.OKX15s}) + if entry.OKX60s != 0 { + changes = append(changes, exchangeChange{name: ExOKX, change: entry.OKX60s}) } if len(changes) < 3 { @@ -258,8 +259,11 @@ func (td *TrendDetector) Tick() { cs.volatility = cs.volatility*(1-alpha) + maxAbs*alpha } - // Update anomaly score + // Update anomaly score — track the peak during the current cycle cs.anomalyScore = zScore + if zScore > cs.peakScore { + cs.peakScore = zScore + } // Determine majority direction majorityDir := TrendUp @@ -279,10 +283,11 @@ func (td *TrendDetector) Tick() { cs.direction = majorityDir cs.alertedAt = now cs.stateSince = now + cs.peakScore = zScore cs.confirmCount = 1 cs.misalignCount = 0 td.recordEvent(entry.Coin, "idle", "alert", string(majorityDir), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } @@ -296,7 +301,7 @@ func (td *TrendDetector) Tick() { cs.confirmedAt = now cs.stateSince = now td.recordEvent(entry.Coin, "alert", "confirmed", string(cs.direction), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } } else { @@ -308,7 +313,7 @@ func (td *TrendDetector) Tick() { cs.confirmCount = 0 cs.misalignCount = 0 td.recordEvent(entry.Coin, "alert", "idle", string(cs.direction), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } } @@ -320,7 +325,7 @@ func (td *TrendDetector) Tick() { cs.state = TrendExhausting cs.stateSince = now td.recordEvent(entry.Coin, "confirmed", "exhausting", string(cs.direction), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } @@ -332,7 +337,7 @@ func (td *TrendDetector) Tick() { cs.confirmCount = 0 cs.misalignCount = 0 td.recordEvent(entry.Coin, "exhausting", "idle", string(cs.direction), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } // Also immediately go to idle if below threshold @@ -342,16 +347,16 @@ func (td *TrendDetector) Tick() { cs.confirmCount = 0 cs.misalignCount = 0 td.recordEvent(entry.Coin, "exhausting", "idle", string(cs.direction), - zScore, cs.volatility, entry.BG15s, entry.HL15s, entry.BN15s, entry.OKX15s, + zScore, cs.volatility, entry.BG60s, entry.HL60s, entry.BN60s, entry.OKX60s, majorityCount, len(changes)) } } } - // Cleanup stale entries (no update for > 60s) - cutoff := time.Now().Add(-60 * time.Second) + // Cleanup stale entries that never even reached alert state (> 120s) + cutoff := time.Now().Add(-120 * time.Second) for coin, cs := range td.coins { - if cs.state == TrendIdle && cs.stateSince.Before(cutoff) { + if cs.state == TrendIdle && cs.alertedAt.IsZero() && cs.stateSince.Before(cutoff) { delete(td.coins, coin) } } @@ -370,15 +375,16 @@ func (td *TrendDetector) Snapshot() []TrendEntry { var result []TrendEntry for coin, cs := range td.coins { - if cs.state == TrendIdle { - continue // skip idle coins + // Skip coins that never even reached alert state + if cs.state == TrendIdle && cs.alertedAt.IsZero() { + continue } entry := TrendEntry{ Coin: coin, State: cs.state, Direction: cs.direction, - AnomalyScore: math.Round(cs.anomalyScore*100) / 100, + AnomalyScore: math.Round(cs.peakScore*100) / 100, Volatility: math.Round(cs.volatility*10000) / 10000, ExChanges: 0, } @@ -416,12 +422,13 @@ func (td *TrendDetector) Snapshot() []TrendEntry { result = append(result, entry) } - // Sort: confirmed first, then alert, then exhausting + // Sort: confirmed first, then alert, then exhausting, then idle (completed) sort.Slice(result, func(i, j int) bool { order := map[TrendState]int{ TrendConfirmed: 0, TrendAlert: 1, TrendExhausting: 2, + TrendIdle: 3, } oi := order[result[i].State] oj := order[result[j].State] @@ -464,6 +471,25 @@ func (td *TrendDetector) IsTrending(coin string) bool { return ok && cs.state == TrendConfirmed } +// IsAnomalous returns true if the coin is in alert or confirmed trend state. +func (td *TrendDetector) IsAnomalous(coin string) bool { + td.mu.RLock() + defer td.mu.RUnlock() + cs, ok := td.coins[coin] + return ok && (cs.state == TrendAlert || cs.state == TrendConfirmed) +} + +// State returns the human-readable trend state for a coin, or empty string if unknown. +func (td *TrendDetector) State(coin string) string { + td.mu.RLock() + defer td.mu.RUnlock() + cs, ok := td.coins[coin] + if !ok { + return "" + } + return string(cs.state) +} + // GetTrendingCoins returns all coins currently in confirmed trend. func (td *TrendDetector) GetTrendingCoins() map[string]TrendDirection { td.mu.RLock() diff --git a/trend_filter.go b/trend_filter.go new file mode 100644 index 0000000..24b1905 --- /dev/null +++ b/trend_filter.go @@ -0,0 +1,770 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log" + "math" + "net/http" + "os" + "sort" + "strings" + "sync" + "time" + +) + +// Binance klines endpoint (unauthenticated, USDⓈ-M futures) +const binanceFapiBase = "https://fapi.binance.com" +const klineCachePath = "data/kline_cache.json" +const signalsCachePath = "data/trend_signals_cache.json" + +// Default thresholds for quiet/active classification. +var ( + range1hThreshold = 2.0 // 1h max range < 2% → quiet +) + +// FilterState stores trend filter results for one coin. +type FilterState struct { + Coin string `json:"coin"` + Range24h float64 `json:"range_24h"` // avg % range of 24 hourly candles + Range1h float64 `json:"range_1h"` // max % range of 12 five-minute candles + EMA52 float64 `json:"ema_52"` // EMA52 of 1h close prices + CurrentPrice float64 `json:"current_price"` // latest Binance price from live feed + PriceAboveEMA bool `json:"price_above_ema"` // current price > EMA52 + Quiet24h bool `json:"quiet_24h"` // 24h range below threshold + Quiet1h bool `json:"quiet_1h"` // 1h range below threshold + FreshAnomaly bool `json:"fresh_anomaly"` // coin in alert/confirmed state + PassesFilter bool `json:"passes_filter"` // all conditions met + LastUpdated int64 `json:"last_updated"` // unix millis + // v2: adaptive scoring fields + VolumeRatio float64 `json:"volume_ratio"` // recent 1h volume / 24h avg volume + EMASlope float64 `json:"ema_slope"` // EMA52 slope over last 3 candles (%) + VolBaseline float64 `json:"vol_baseline"` // per-coin 24h volatility baseline (median %) + SignalScore float64 `json:"signal_score"` // composite signal score 0-100 + Change1h float64 `json:"change_1h"` // 1h price change % (from 5m klines) + KlineClose float64 `json:"-"` // last 5m kline close (for real-time drift calc, not serialized) + DriftPct float64 `json:"drift_pct"` // real-time drift % from last kline close +} + +// klineData holds parsed fields from one Binance kline. +type klineData struct { + High float64 + Low float64 + Close float64 + Volume float64 +} + +// TrendSignal records a signal event when trade conditions are met. +type TrendSignal struct { + Timestamp int64 `json:"timestamp"` + Coin string `json:"coin"` + Type string `json:"type"` // "enter" or "exit" + Category string `json:"category"` // "full" (anomaly+score>=70) or "high" (score>=90) + SignalScore float64 `json:"signal_score"` + Price float64 `json:"price"` + EMA52 float64 `json:"ema_52"` + EMASlope float64 `json:"ema_slope"` + VolumeRatio float64 `json:"volume_ratio"` + Range24h float64 `json:"range_24h"` + VolBaseline float64 `json:"vol_baseline"` + PriceAboveEMA bool `json:"price_above_ema"` + State string `json:"state"` // trend detector state at time of signal +} + +// TrendFilter fetches Binance klines, computes EMA52/ranges, and filters +// coins that show fresh anomaly signals from TrendDetector. +type TrendFilter struct { + mu sync.RWMutex + states map[string]*FilterState + store *PriceStore + trendDetector *TrendDetector + client *http.Client + refreshTicker *time.Ticker + stopCh chan struct{} + // Signal recording + signals []TrendSignal + signaledCoins map[string]bool // coins currently in "full" enter signal state + highScoreCoins map[string]bool // coins currently in "high" enter signal state + OnNewSignal func(TrendSignal) // callback for SSE broadcast +} + +// NewTrendFilter creates a TrendFilter. Call Start() to begin periodic refresh. +func NewTrendFilter(store *PriceStore, td *TrendDetector) *TrendFilter { + p := os.Getenv("HTTPS_PROXY") + if p == "" { + p = os.Getenv("https_proxy") + } + log.Printf("[TrendFilter] HTTPS_PROXY=%s", p) + + return &TrendFilter{ + client: &http.Client{ + Timeout: 15 * time.Second, + Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, + }, + states: make(map[string]*FilterState), + store: store, + trendDetector: td, + stopCh: make(chan struct{}), + signaledCoins: make(map[string]bool), + highScoreCoins: make(map[string]bool), + } +} + +// Start begins the background kline fetch loop. The first fetch runs immediately. +func (tf *TrendFilter) Start() { + // Load cached data on startup so we have data immediately + if cached := loadCache(); cached != nil { + tf.mu.Lock() + tf.states = cached + tf.mu.Unlock() + } + // Load signal history + tf.loadSignals() + + go func() { + tf.fetchBatch() + tf.refreshTicker = time.NewTicker(5 * time.Minute) + for { + select { + case <-tf.refreshTicker.C: + tf.fetchBatch() + case <-tf.stopCh: + return + } + } + }() +} + +// Stop stops the background refresh. +func (tf *TrendFilter) Stop() { + close(tf.stopCh) + if tf.refreshTicker != nil { + tf.refreshTicker.Stop() + } +} + +// Tick updates anomaly status from TrendDetector and recalculates PassesFilter. +// Call this every ~1s from the SSE broadcast loop (no HTTP calls). +func (tf *TrendFilter) Tick() { + tf.mu.Lock() + defer tf.mu.Unlock() + + for coin, st := range tf.states { + // Update fresh anomaly from trend detector + if tf.trendDetector != nil { + st.FreshAnomaly = tf.trendDetector.IsAnomalous(coin) + } + + // Update current price from live feed + if p, ok := tf.store.Get(coin, ExBinance); ok && p > 0 { + // Compute real-time drift from last kline close + if st.KlineClose > 0 && st.CurrentPrice > 0 { + st.DriftPct = math.Round((p-st.KlineClose)/st.KlineClose*10000) / 10000 + } + st.CurrentPrice = p + if st.EMA52 > 0 { + st.PriceAboveEMA = p > st.EMA52 + } + } + + // Re-evaluate overall pass + st.PassesFilter = st.Quiet24h && st.Quiet1h && st.FreshAnomaly && st.PriceAboveEMA + // Recalculate signal score (FreshAnomaly and PriceAboveEMA may have changed) + st.SignalScore = computeSignalScore(st) + } + // Check for signal triggers (must hold lock) + tf.checkSignals() +} + +// Snapshot returns filter states, sorted with passing coins first. +func (tf *TrendFilter) Snapshot(limit int) []FilterState { + tf.mu.RLock() + defer tf.mu.RUnlock() + + result := make([]FilterState, 0, len(tf.states)) + for _, st := range tf.states { + result = append(result, *st) + } + + sort.Slice(result, func(i, j int) bool { + // Highest signal score first + if result[i].SignalScore != result[j].SignalScore { + return result[i].SignalScore > result[j].SignalScore + } + return result[i].Coin < result[j].Coin + }) + + if limit > 0 && limit < len(result) { + result = result[:limit] + } + return result +} + +// fetchBatch fetches klines for all tracked coins concurrently. +func (tf *TrendFilter) fetchBatch() { + log.Printf("[TrendFilter] Starting kline fetch (%d coins)...", len(TrackedCoins)) + // Collect coins that have a Binance symbol + type coinSymbol struct { + name string + symbol string + } + var targets []coinSymbol + for _, tc := range TrackedCoins { + if tc.BN != "" { + targets = append(targets, coinSymbol{name: tc.Name, symbol: tc.BN}) + } + } + if len(targets) == 0 { + return + } + + // Semaphore: max 20 concurrent goroutines + sem := make(chan struct{}, 20) + var mu sync.Mutex + type coinResult struct { + name string + klines1h []klineData + klines5m []klineData + err error + } + results := make([]coinResult, len(targets)) + + var wg sync.WaitGroup + for i, t := range targets { + wg.Add(1) + sem <- struct{}{} + go func(idx int, coin, symbol string) { + defer wg.Done() + defer func() { <-sem }() + + k1h, err1 := tf.fetchKlines(symbol, "1h", 500) + if err1 != nil { + mu.Lock() + results[idx] = coinResult{name: coin, err: err1} + mu.Unlock() + return + } + k5m, err2 := tf.fetchKlines(symbol, "5m", 12) + if err2 != nil { + mu.Lock() + results[idx] = coinResult{name: coin, err: err2} + mu.Unlock() + return + } + mu.Lock() + results[idx] = coinResult{name: coin, klines1h: k1h, klines5m: k5m} + mu.Unlock() + }(i, t.name, t.symbol) + } + wg.Wait() + + // Process results + now := time.Now().UnixMilli() + newStates := make(map[string]*FilterState, len(results)) + var errCount int + for _, r := range results { + if r.err != nil || len(r.klines1h) == 0 { + if r.err != nil && errCount < 3 { + log.Printf("[TrendFilter] Error for %s: %v", r.name, r.err) + errCount++ + } + continue + } + fs := tf.computeFilterState(r.name, r.klines1h, r.klines5m, now) + newStates[r.name] = fs + } + + // Merge: overwrite computed states, preserve anomaly for coins that errored + tf.mu.Lock() + for coin, fs := range newStates { + tf.states[coin] = fs + if tf.trendDetector != nil { + fs.FreshAnomaly = tf.trendDetector.IsAnomalous(coin) + } + if p, ok := tf.store.Get(coin, ExBinance); ok && p > 0 { + fs.CurrentPrice = p + if fs.EMA52 > 0 { + fs.PriceAboveEMA = p > fs.EMA52 + } + } + fs.PassesFilter = fs.Quiet24h && fs.Quiet1h && fs.FreshAnomaly && fs.PriceAboveEMA + // Recalculate signal score with live data + fs.SignalScore = computeSignalScore(fs) + } + tf.mu.Unlock() + + if len(newStates) > 0 { + tf.saveCache() + } + log.Printf("[TrendFilter] Fetch complete: %d/%d coins have data", len(newStates), len(results)) +} + +// fetchKlines calls Binance fapi klines endpoint and parses the response. +func (tf *TrendFilter) fetchKlines(symbol, interval string, limit int) ([]klineData, error) { + url := fmt.Sprintf("%s/fapi/v1/klines?symbol=%s&interval=%s&limit=%d", + binanceFapiBase, strings.ToUpper(symbol), interval, limit) + + resp, err := tf.client.Get(url) + if err != nil { + return nil, fmt.Errorf("fetch %s: %w", symbol, err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("fetch %s: HTTP %d: %s", symbol, resp.StatusCode, string(body)) + } + + // Binance returns [[time,open,high,low,close,volume,...], ...] + var raw [][]interface{} + if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil { + return nil, fmt.Errorf("decode %s: %w", symbol, err) + } + + result := make([]klineData, 0, len(raw)) + for _, item := range raw { + if len(item) < 6 { + continue + } + h := parseFloat(item[2]) + l := parseFloat(item[3]) + c := parseFloat(item[4]) + v := parseFloat(item[5]) + if h > 0 && l > 0 && c > 0 { + result = append(result, klineData{High: h, Low: l, Close: c, Volume: v}) + } + } + return result, nil +} + +// parseFloat converts a JSON string field to float64. +func parseFloat(v interface{}) float64 { + s, _ := v.(string) + var f float64 + _, _ = fmt.Sscanf(s, "%f", &f) + return f +} + +// computeFilterState derives all filter fields from kline data. +// v2: adaptive volatility baseline, volume ratio, EMA slope, composite score. +func (tf *TrendFilter) computeFilterState(coin string, k1h, k5m []klineData, now int64) *FilterState { + fs := &FilterState{ + Coin: coin, + LastUpdated: now, + } + + n := len(k1h) + + // ── Compute per-candle ranges for volatility baseline ── + candleRanges := make([]float64, 0, n) + for _, k := range k1h { + if k.Low > 0 { + candleRanges = append(candleRanges, (k.High-k.Low)/k.Low*100) + } + } + + // ── Adaptive volatility baseline ── + // Short-term: median range of last 24 candles + // Long-term: median range of ALL candles + // Quiet24h = short-term < long-term * 1.5 + if len(candleRanges) >= 24 { + shortTerm := candleRanges + if len(shortTerm) > 24 { + shortTerm = candleRanges[len(candleRanges)-24:] + } + shortMedian := median(shortTerm) + longMedian := median(candleRanges) + + fs.VolBaseline = math.Round(longMedian*100) / 100 + fs.Range24h = math.Round(shortMedian*100) / 100 + fs.Quiet24h = shortMedian < longMedian*1.5 + } + + // ── Compute EMA52 from hourly close prices ── + if n >= 52 { + prices := make([]float64, n) + for i, k := range k1h { + prices[i] = k.Close + } + ema := computeEMA(prices, 52) + if len(ema) > 0 { + fs.EMA52 = math.Round(ema[len(ema)-1]*10000) / 10000 + } + // EMA slope: (ema[-1] - ema[-4]) / ema[-4] * 100 + if len(ema) >= 4 && ema[len(ema)-4] > 0 { + slope := (ema[len(ema)-1] - ema[len(ema)-4]) / ema[len(ema)-4] * 100 + fs.EMASlope = math.Round(slope*10000) / 10000 + } + } + + // ── Compute 1h max range from 5m klines ── + if len(k5m) > 0 { + var maxRange float64 + for _, k := range k5m { + if k.Low <= 0 { + continue + } + r := (k.High - k.Low) / k.Low * 100 + if r > maxRange { + maxRange = r + } + } + fs.Range1h = math.Round(maxRange*100) / 100 + fs.Quiet1h = fs.Range1h < range1hThreshold + } + + // ── Volume ratio: last 1h volume / 24h avg volume ── + if n >= 24 { + lastVol := k1h[n-1].Volume + var sumVol float64 + for i := n - 24; i < n-1; i++ { + sumVol += k1h[i].Volume + } + avgVol := sumVol / 23 // exclude current candle from avg + if avgVol > 0 { + fs.VolumeRatio = math.Round(lastVol/avgVol*100) / 100 + } + } + + // ── 1h price change % from 5m klines ── + if len(k5m) >= 2 { + firstClose := k5m[0].Close + lastClose := k5m[len(k5m)-1].Close + if firstClose > 0 { + fs.Change1h = math.Round((lastClose-firstClose)/firstClose*10000) / 10000 + } + } + // Store last kline close for real-time drift calculation + if len(k5m) > 0 { + fs.KlineClose = k5m[len(k5m)-1].Close + } + + // ── Composite SignalScore (0-100) ── + var score float64 + if fs.PriceAboveEMA { + score += 25 + } + if fs.Quiet24h { + score += 25 + } + if fs.Quiet1h { + score += 20 + } + if fs.FreshAnomaly { + score += 15 + } + if fs.VolumeRatio > 1.5 { + score += 15 + } + // Bonus points + if fs.EMASlope > 0.1 { + score += 10 + } + if fs.VolumeRatio > 3.0 { + score += 10 + } + // 1h price direction + if fs.Change1h > 0 { + score += 15 + } else if fs.Change1h < -0.1 { + score -= 20 + } else if fs.Change1h < 0 { + score -= 10 + } + if score < 0 { + score = 0 + } + if score > 100 { + score = 100 + } + fs.SignalScore = score + + return fs +} + +// median returns the median value of a sorted copy of the slice. +func median(values []float64) float64 { + if len(values) == 0 { + return 0 + } + sorted := make([]float64, len(values)) + copy(sorted, values) + sort.Float64s(sorted) + mid := len(sorted) / 2 + if len(sorted)%2 == 0 { + return (sorted[mid-1] + sorted[mid]) / 2 + } + return sorted[mid] +} + +// computeSignalScore calculates the composite signal score (0-100) from a FilterState. +// Must be called after FreshAnomaly, PriceAboveEMA, and volume fields are set. +func computeSignalScore(fs *FilterState) float64 { + var score float64 + if fs.PriceAboveEMA { + score += 25 + } + if fs.Quiet24h { + score += 25 + } + if fs.Quiet1h { + score += 20 + } + if fs.FreshAnomaly { + score += 15 + } + if fs.VolumeRatio > 1.5 { + score += 15 + } + // Bonus: strong EMA uptrend + if fs.EMASlope > 0.1 { + score += 10 + } + // Bonus: very high volume + if fs.VolumeRatio > 3.0 { + score += 10 + } + // 1h price direction: positive change adds, negative change subtracts + if fs.Change1h > 0 { + score += 15 + } else if fs.Change1h < -0.1 { + score -= 20 // actively dropping — heavily penalize + } else if fs.Change1h < 0 { + score -= 10 // slightly dropping + } + // Real-time drift: if current price is falling below last kline close, penalize + if fs.DriftPct < -0.1 { + score -= 15 + } else if fs.DriftPct < 0 { + score -= 5 + } + if score < 0 { + score = 0 + } + if score > 100 { + score = 100 + } + return score +} + +// ── Signal recording ── + +const signalScoreThreshold = 70.0 +const highScoreThreshold = 90.0 + +// checkSignals scans all coins for enter/exit signal conditions. +// Must be called with tf.mu held. +func (tf *TrendFilter) checkSignals() { + now := time.Now().UnixMilli() + for coin, st := range tf.states { + if st.EMA52 <= 0 { + continue // no K-line data yet + } + + // ── Full signal: FreshAnomaly + score >= 70 ── + fullSignaled := tf.signaledCoins[coin] + if st.FreshAnomaly && st.SignalScore >= signalScoreThreshold { + if !fullSignaled { + tf.recordSignal(now, coin, st, "enter", "full") + } + } else if fullSignaled { + tf.recordSignal(now, coin, st, "exit", "full") + } + + // ── High score signal: score >= 90 (no anomaly required) ── + highSignaled := tf.highScoreCoins[coin] + if st.SignalScore >= highScoreThreshold { + if !highSignaled { + tf.recordSignal(now, coin, st, "enter", "high") + } + } else if highSignaled { + tf.recordSignal(now, coin, st, "exit", "high") + } + } +} + +// recordSignal creates, stores, and broadcasts a signal event. +func (tf *TrendFilter) recordSignal(now int64, coin string, st *FilterState, sigType, category string) { + sig := TrendSignal{ + Timestamp: now, + Coin: coin, + Type: sigType, + Category: category, + SignalScore: st.SignalScore, + Price: st.CurrentPrice, + EMA52: st.EMA52, + EMASlope: st.EMASlope, + VolumeRatio: st.VolumeRatio, + Range24h: st.Range24h, + VolBaseline: st.VolBaseline, + PriceAboveEMA: st.PriceAboveEMA, + State: tf.trendDetectorState(coin), + } + tf.signals = append(tf.signals, sig) + + // Track signaled state per category + if sigType == "enter" { + switch category { + case "full": + tf.signaledCoins[coin] = true + case "high": + tf.highScoreCoins[coin] = true + } + } else { + switch category { + case "full": + delete(tf.signaledCoins, coin) + case "high": + delete(tf.highScoreCoins, coin) + } + } + + tf.saveSignals() + if tf.OnNewSignal != nil { + tf.OnNewSignal(sig) + } + log.Printf("[TrendFilter] SIGNAL %s/%s: %s score=%.0f price=%.4f vol=%.2fx slope=%.3f%%", + sigType, category, coin, st.SignalScore, st.CurrentPrice, st.VolumeRatio, st.EMASlope) +} + +// trendDetectorState reads the current trend detector state for a coin. +func (tf *TrendFilter) trendDetectorState(coin string) string { + if tf.trendDetector == nil { + return "" + } + return tf.trendDetector.State(coin) +} + +// GetSignals returns the most recent N signals. +func (tf *TrendFilter) GetSignals(limit int) []TrendSignal { + tf.mu.RLock() + defer tf.mu.RUnlock() + n := len(tf.signals) + if n == 0 { + return nil + } + start := n - limit + if start < 0 { + start = 0 + } + result := make([]TrendSignal, n-start) + copy(result, tf.signals[start:]) + // Return in reverse order (newest first) + for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { + result[i], result[j] = result[j], result[i] + } + return result +} + +// saveSignals persists signals to disk. +func (tf *TrendFilter) saveSignals() { + if len(tf.signals) == 0 { + return + } + // Keep only last 2000 signals + if len(tf.signals) > 2000 { + tf.signals = tf.signals[len(tf.signals)-2000:] + } + data, err := json.Marshal(tf.signals) + if err != nil { + return + } + os.WriteFile(signalsCachePath, data, 0644) +} + +// loadSignals reads signals from disk. +func (tf *TrendFilter) loadSignals() { + raw, err := os.ReadFile(signalsCachePath) + if err != nil { + return + } + var sigs []TrendSignal + if err := json.Unmarshal(raw, &sigs); err != nil { + return + } + tf.signals = sigs + for _, s := range sigs { + if s.Type == "enter" { + switch s.Category { + case "full": + tf.signaledCoins[s.Coin] = true + case "high": + tf.highScoreCoins[s.Coin] = true + } + } else { + switch s.Category { + case "full": + delete(tf.signaledCoins, s.Coin) + case "high": + delete(tf.highScoreCoins, s.Coin) + } + } + } + log.Printf("[TrendFilter] Loaded %d signal records", len(tf.signals)) +} + +// saveCache writes current filter states to disk (transient fields reset on load). +func (tf *TrendFilter) saveCache() { + tf.mu.RLock() + defer tf.mu.RUnlock() + + data, err := json.Marshal(tf.states) + if err != nil { + return + } + os.WriteFile(klineCachePath, data, 0644) +} + +// loadCache reads filter states from disk, returning only non-transient fields. +func loadCache() map[string]*FilterState { + raw, err := os.ReadFile(klineCachePath) + if err != nil { + return nil + } + var states map[string]*FilterState + if err := json.Unmarshal(raw, &states); err != nil { + return nil + } + // Reset transient fields — they will be set by Tick() + for _, st := range states { + st.CurrentPrice = 0 + st.PriceAboveEMA = false + st.FreshAnomaly = false + st.PassesFilter = false + } + log.Printf("[TrendFilter] Loaded %d coins from cache", len(states)) + return states +} + +// computeEMA calculates EMA over price data for the given period. +// Uses SMA of first `period` values as seed, then EMA formula. +func computeEMA(prices []float64, period int) []float64 { + if len(prices) < period || period < 2 { + return nil + } + + result := make([]float64, len(prices)) + + // SMA seed + var sum float64 + for i := 0; i < period; i++ { + sum += prices[i] + } + result[period-1] = sum / float64(period) + + // EMA multiplier + multiplier := 2.0 / float64(period+1) + + for i := period; i < len(prices); i++ { + result[i] = (prices[i]-result[i-1])*multiplier + result[i-1] + } + + // Fill leading entries with SMA value + for i := 0; i < period-1; i++ { + result[i] = result[period-1] + } + + return result +}