'use client'; import React, { useState, useMemo } from 'react'; import { useSandboxStore } from '@/lib/store'; import { predictCryptoTrend, calculateBetaPosterior } from '@/lib/math/statistics'; import 'katex/dist/katex.min.css'; import { BlockMath, InlineMath } from 'react-katex'; import { Cpu, Search, RefreshCw, BarChart2, TrendingUp, AlertCircle, Info, ChevronDown, ChevronUp, ArrowUpRight, ArrowDownRight, Compass, ShieldAlert, Sparkles } from 'lucide-react'; interface CoinData { ticker: string; name: string; price: string; change24h: number; fundingRate: number; // in % openInterestChange: number; // in % longShortRatio: number; whaleInflow: number; // net flows exchangeReserves: number; // in % liqLong: string; liqShort: string; } const defaultCoins: Record = { 'BTC': { ticker: 'BTC', name: 'Bitcoin', price: '$69,450', change24h: 2.4, fundingRate: -0.015, openInterestChange: 8.2, longShortRatio: 0.92, whaleInflow: 480, exchangeReserves: -1.4, liqLong: '$68,200', liqShort: '$70,500' }, 'ETH': { ticker: 'ETH', name: 'Ethereum', price: '$3,820', change24h: -1.2, fundingRate: 0.045, openInterestChange: -3.5, longShortRatio: 1.34, whaleInflow: -120, exchangeReserves: 0.8, liqLong: '$3,710', liqShort: '$3,920' }, 'SOL': { ticker: 'SOL', name: 'Solana', price: '$184.20', change24h: 5.8, fundingRate: 0.082, openInterestChange: 14.5, longShortRatio: 1.62, whaleInflow: 1250, exchangeReserves: -2.8, liqLong: '$176.00', liqShort: '$192.50' } }; export default function CryptoDemo() { const { alphaSuccess, betaFailure, addModelTrial } = useSandboxStore(); const [activeTicker, setActiveTicker] = useState('BTC'); const [searchQuery, setSearchQuery] = useState(''); const [customCoins, setCustomCoins] = useState>({}); const [searchError, setSearchError] = useState(false); const [showMathAccordion, setShowMathAccordion] = useState(false); const [simulatedTrialLogged, setSimulatedTrialLogged] = useState(false); const [lastTrialSuccess, setLastTrialSuccess] = useState(false); // Active Coin data retrieval const activeCoin = useMemo(() => { return customCoins[activeTicker] || defaultCoins[activeTicker] || defaultCoins['BTC']; }, [activeTicker, customCoins]); // Compute live Random Forest baseline predictions const mlPredictions = useMemo(() => { const inputs = { fundingRate: activeCoin.fundingRate, openInterestChange: activeCoin.openInterestChange, longShortRatio: activeCoin.longShortRatio, whaleInflow: activeCoin.whaleInflow }; return predictCryptoTrend(inputs); }, [activeCoin]); // Apply Bayesian online learning error-correction posterior update const correctedPredictions = useMemo(() => { // Correct short term probability const shortTermCorrected = calculateBetaPosterior( alphaSuccess, betaFailure, mlPredictions.shortTermProb, 12 // pseudo weight/confidence scale ); // Correct medium term probability const mediumTermCorrected = calculateBetaPosterior( alphaSuccess, betaFailure, mlPredictions.mediumTermProb, 12 ); return { shortTerm: shortTermCorrected, mediumTerm: mediumTermCorrected }; }, [mlPredictions, alphaSuccess, betaFailure]); // Perform search check for Altcoins const handleAltcoinSearch = (e: React.FormEvent) => { e.preventDefault(); setSearchError(false); const query = searchQuery.trim().toUpperCase(); if (!query) return; if (defaultCoins[query]) { setActiveTicker(query); setSearchQuery(''); return; } if (customCoins[query]) { setActiveTicker(query); setSearchQuery(''); return; } // Generate simulated data for Altcoin const isBull = Math.random() > 0.45; const simulatedChange = isBull ? 3 + Math.random() * 8 : -2 - Math.random() * 6; const simulatedPrice = isBull ? 2 + Math.random() * 10 : 0.2 + Math.random() * 3; const newCoin: CoinData = { ticker: query, name: `${query} Token`, price: `$${simulatedPrice.toFixed(4)}`, change24h: parseFloat(simulatedChange.toFixed(2)), fundingRate: parseFloat((Math.random() * 0.12 - 0.04).toFixed(3)), openInterestChange: parseFloat((Math.random() * 30 - 10).toFixed(1)), longShortRatio: parseFloat((0.8 + Math.random() * 1.1).toFixed(2)), whaleInflow: Math.floor(Math.random() * 1500 - 400), exchangeReserves: parseFloat((Math.random() * 4 - 2).toFixed(1)), liqLong: `$${(simulatedPrice * 0.9).toFixed(4)}`, liqShort: `$${(simulatedPrice * 1.1).toFixed(4)}` }; setCustomCoins(prev => ({ ...prev, [query]: newCoin })); setActiveTicker(query); setSearchQuery(''); }; const handleSimulateTrial = (success: boolean) => { addModelTrial(success); setLastTrialSuccess(success); setSimulatedTrialLogged(true); setTimeout(() => setSimulatedTrialLogged(false), 2500); }; const totalTrials = alphaSuccess + betaFailure; const priorAccuracy = (alphaSuccess / (totalTrials || 1)) * 100; return (
{/* Header */}
Element 4

Predictive Krypto-Modelle & Bayes Self-Correction

A-Priori Genauigkeit

{priorAccuracy.toFixed(1)}% (n={totalTrials})

{/* SECTION 1: Top 3 Cards & Search Mask */}
{/* Status Cards BTC, ETH, SOL */} {['BTC', 'ETH', 'SOL'].map((tick) => { const coin = defaultCoins[tick]; const isActive = activeTicker === tick; const isUp = coin.change24h >= 0; return (
setActiveTicker(tick)} className={`p-4 rounded-xl border cursor-pointer transition-all hover:bg-slate-850 flex items-center justify-between relative overflow-hidden ${isActive ? 'border-cyan-500/40 bg-cyan-500/5 shadow-md shadow-cyan-500/5' : 'border-slate-850 bg-slate-950/20'}`} >
{coin.name}
{coin.price}
{isUp ? : } {isUp ? '+' : ''}{coin.change24h}%
{tick}
); })} {/* Custom Search bar */}
setSearchQuery(e.target.value)} />
{Object.keys(customCoins).length > 0 && (
{Object.keys(customCoins).map(tick => ( ))}
)}
{/* SECTION 2: Derivatives & On-Chain Metrics Ledger */}
{/* Left Column: Metrics Widgets */}

On-Chain & Derivate-Indikatoren ({activeCoin.ticker})

{/* Funding & Open Interest Widget */}

Ref-Zinssatz & Kontrakte (OI)

Daily Funding Rate: {activeCoin.fundingRate > 0 ? '+' : ''}{activeCoin.fundingRate.toFixed(3)}%
Open Interest (24h Δ): = 0 ? 'text-emerald-400' : 'text-rose-400'}`}> {activeCoin.openInterestChange > 0 ? '+' : ''}{activeCoin.openInterestChange.toFixed(1)}%
{/* Long/Short & Liquidation Widget */}

Positionierung & Liquidationen

Long / Short Ratio: {activeCoin.longShortRatio}
Liq-Cluster: Long: {activeCoin.liqLong} | Short: {activeCoin.liqShort}
{/* Whale Flows Widget */}

Whale-Ströme (Nettozufluss)

Netto Inflow (Wallets): = 0 ? 'text-emerald-400' : 'text-rose-400'}`}> {activeCoin.whaleInflow > 0 ? '+' : ''}{activeCoin.whaleInflow} {activeCoin.ticker}
Positive Werte signalisieren, dass Großinvestoren Bestände von Börsen auf private Wallets (Akkumulation) abziehen.
{/* Exchange Reserves Widget */}

Börsenreserven (Spot)

Reservenänderung (7d): {activeCoin.exchangeReserves > 0 ? '+' : ''}{activeCoin.exchangeReserves}%
Sinkende Reserven an den Spot-Börsen reduzieren den verfügbaren Verkaufsdruck und begünstigen Squeezes.
{/* Right Column: Predictive Gauges & Correction Calibration */}

Vorhersage-Wahrscheinlichkeiten

{/* Gauges / Progress Bars */}
{/* 24h Gauge */}
24h Volatility Squeeze (Short-Term) {(correctedPredictions.shortTerm * 100).toFixed(0)}%
{/* ML Baseline Overlay */}
{/* Corrected Posterior Marker */}
ML-Signal: {(mlPredictions.shortTermProb * 100).toFixed(0)}% Bayes-Korrigiert: {(correctedPredictions.shortTerm * 100).toFixed(0)}%
{/* 14d Gauge */}
14d Struktureller Bullish-Trend (Medium-Term) {(correctedPredictions.mediumTerm * 100).toFixed(0)}%
ML-Signal: {(mlPredictions.mediumTermProb * 100).toFixed(0)}% Bayes-Korrigiert: {(correctedPredictions.mediumTerm * 100).toFixed(0)}%
{/* Model Calibration Log & Simulation */}

Bayes Modell-Kalibrierung

n = {totalTrials} Trials
Erfolge (α):
{alphaSuccess}
Fehlalarme (β):
{betaFailure}
{/* Trial simulator */}

Modell-Drift simulieren: Fügen Sie richtige/falsche Outcomes hinzu, um die Beta-Verteilung anzupassen.

{simulatedTrialLogged && (
Trial geloggt! Bayes-Prior wurde auf {lastTrialSuccess ? 'Erfolg' : 'Fehlalarm'} aktualisiert.
)}
{/* SECTION 3: Mathematical LaTeX Accordion */}
{showMathAccordion && (

1. Bayesianische Beta-Konjugierte Fehlerkorrektur

Wir modellieren das Vertrauensintervall über die Fehlerraten des Modells mittels einer Beta-Verteilung. Der A-Priori Fehlerzustand wird durch die Parameter (Erfolge) und (Fehlalarme) dargestellt:

Bei einem neuen ML-Signal führen wir ein konjugiertes Bayes-Update mit einem Vertrauensgewicht aus:

Ist das Modell historisch sehr instabil (hohes ), korrigiert der Bayesianische Term ein übermütiges ML-Signal nach unten, was die Robustheit des Gesamtsystems schützt.

2. Random Forest Nicht-Lineares Signalmapping

Der Random Forest simuliert ein Ensemble von 10 schwachen Entscheidungsbäumen. Jeder Baum spaltet die Daten nach Schwellenwerten (z.B. „Funding-Rate < -0.04%“ und „Open Interest > 10%“) auf:

wobei der prognostizierte Ausgabewert des -ten Entscheidungsbaumes für den Featurevektor ist.

)}
); }