Initial commit: Mantle AI Trading Bot
Features: - AI-powered signal generation with multi-factor analysis - Fundamental news aggregation from multiple sources - Technical analysis with 6+ indicators - VectorDB integration for semantic search - Backtesting engine with performance metrics - Demo/paper trading mode - Real-time WebSocket updates - Comprehensive dashboard UI Built for Mantle Turing Test Hackathon - AI Trading track - AI Alpha & Data track
This commit is contained in:
54
.gitignore
vendored
Normal file
54
.gitignore
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
local-*
|
||||
.claude
|
||||
.z-ai-config
|
||||
*.log
|
||||
dev.log
|
||||
dev.out.log
|
||||
test
|
||||
prompt
|
||||
|
||||
server.log
|
||||
# Skills directory
|
||||
/skills/
|
||||
122
.zscripts/build.sh
Executable file
122
.zscripts/build.sh
Executable file
@@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 将 stderr 重定向到 stdout,避免 execute_command 因为 stderr 输出而报错
|
||||
exec 2>&1
|
||||
|
||||
set -e
|
||||
|
||||
# 获取脚本所在目录(.zscripts 目录,即 workspace-agent/.zscripts)
|
||||
# 使用 $0 获取脚本路径(兼容 sh 和 bash)
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# Next.js 项目路径
|
||||
NEXTJS_PROJECT_DIR="/home/z/my-project"
|
||||
|
||||
# 检查 Next.js 项目目录是否存在
|
||||
if [ ! -d "$NEXTJS_PROJECT_DIR" ]; then
|
||||
echo "❌ 错误: Next.js 项目目录不存在: $NEXTJS_PROJECT_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🚀 开始构建 Next.js 应用和 mini-services..."
|
||||
echo "📁 Next.js 项目路径: $NEXTJS_PROJECT_DIR"
|
||||
|
||||
# 切换到 Next.js 项目目录
|
||||
cd "$NEXTJS_PROJECT_DIR" || exit 1
|
||||
|
||||
# 设置环境变量
|
||||
export NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
BUILD_DIR="/tmp/build_fullstack_$BUILD_ID"
|
||||
echo "📁 清理并创建构建目录: $BUILD_DIR"
|
||||
mkdir -p "$BUILD_DIR"
|
||||
|
||||
# 安装依赖
|
||||
echo "📦 安装依赖..."
|
||||
bun install
|
||||
|
||||
# 构建 Next.js 应用
|
||||
echo "🔨 构建 Next.js 应用..."
|
||||
bun run build
|
||||
|
||||
# 构建 mini-services
|
||||
# 检查 Next.js 项目目录下是否有 mini-services 目录
|
||||
if [ -d "$NEXTJS_PROJECT_DIR/mini-services" ]; then
|
||||
echo "🔨 构建 mini-services..."
|
||||
# 使用 workspace-agent 目录下的 mini-services 脚本
|
||||
sh "$SCRIPT_DIR/mini-services-install.sh"
|
||||
sh "$SCRIPT_DIR/mini-services-build.sh"
|
||||
|
||||
# 复制 mini-services-start.sh 到 mini-services-dist 目录
|
||||
echo " - 复制 mini-services-start.sh 到 $BUILD_DIR"
|
||||
cp "$SCRIPT_DIR/mini-services-start.sh" "$BUILD_DIR/mini-services-start.sh"
|
||||
chmod +x "$BUILD_DIR/mini-services-start.sh"
|
||||
else
|
||||
echo "ℹ️ mini-services 目录不存在,跳过"
|
||||
fi
|
||||
|
||||
# 将所有构建产物复制到临时构建目录
|
||||
echo "📦 收集构建产物到 $BUILD_DIR..."
|
||||
|
||||
# 复制 Next.js standalone 构建输出
|
||||
if [ -d ".next/standalone" ]; then
|
||||
echo " - 复制 .next/standalone"
|
||||
cp -r .next/standalone "$BUILD_DIR/next-service-dist/"
|
||||
fi
|
||||
|
||||
# 复制 Next.js 静态文件
|
||||
if [ -d ".next/static" ]; then
|
||||
echo " - 复制 .next/static"
|
||||
mkdir -p "$BUILD_DIR/next-service-dist/.next"
|
||||
cp -r .next/static "$BUILD_DIR/next-service-dist/.next/"
|
||||
fi
|
||||
|
||||
# 复制 public 目录
|
||||
if [ -d "public" ]; then
|
||||
echo " - 复制 public"
|
||||
cp -r public "$BUILD_DIR/next-service-dist/"
|
||||
fi
|
||||
|
||||
# 将测试环境数据库复制到构建产物中,生产环境直接使用这份数据库
|
||||
if [ -f "./db/custom.db" ]; then
|
||||
echo "🗄️ 复制测试环境数据库到构建产物..."
|
||||
mkdir -p "$BUILD_DIR/db"
|
||||
cp -r ./db/. "$BUILD_DIR/db/"
|
||||
|
||||
echo "🗄️ 同步构建产物中的数据库结构..."
|
||||
DATABASE_URL="file:$BUILD_DIR/db/custom.db" bun run db:push
|
||||
echo "✅ 构建产物数据库已准备完成"
|
||||
ls -lah "$BUILD_DIR/db"
|
||||
else
|
||||
echo "❌ 未找到测试环境数据库文件 ./db/custom.db,无法继续构建生产包"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 复制 Caddyfile(如果存在)
|
||||
if [ -f "Caddyfile" ]; then
|
||||
echo " - 复制 Caddyfile"
|
||||
cp Caddyfile "$BUILD_DIR/"
|
||||
else
|
||||
echo "ℹ️ Caddyfile 不存在,跳过"
|
||||
fi
|
||||
|
||||
# 复制 start.sh 脚本
|
||||
echo " - 复制 start.sh 到 $BUILD_DIR"
|
||||
cp "$SCRIPT_DIR/start.sh" "$BUILD_DIR/start.sh"
|
||||
chmod +x "$BUILD_DIR/start.sh"
|
||||
|
||||
# 打包到 $BUILD_DIR.tar.gz
|
||||
PACKAGE_FILE="${BUILD_DIR}.tar.gz"
|
||||
echo ""
|
||||
echo "📦 打包构建产物到 $PACKAGE_FILE..."
|
||||
cd "$BUILD_DIR" || exit 1
|
||||
tar -czf "$PACKAGE_FILE" .
|
||||
cd - > /dev/null || exit 1
|
||||
|
||||
# # 清理临时目录
|
||||
# rm -rf "$BUILD_DIR"
|
||||
|
||||
echo ""
|
||||
echo "✅ 构建完成!所有产物已打包到 $PACKAGE_FILE"
|
||||
echo "📊 打包文件大小:"
|
||||
ls -lh "$PACKAGE_FILE"
|
||||
1
.zscripts/dev.pid
Normal file
1
.zscripts/dev.pid
Normal file
@@ -0,0 +1 @@
|
||||
1719
|
||||
154
.zscripts/dev.sh
Executable file
154
.zscripts/dev.sh
Executable file
@@ -0,0 +1,154 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# 获取脚本所在目录(.zscripts)
|
||||
# 使用 $0 获取脚本路径(与 build.sh 保持一致)
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
|
||||
log_step_start() {
|
||||
local step_name="$1"
|
||||
echo "=========================================="
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting: $step_name"
|
||||
echo "=========================================="
|
||||
export STEP_START_TIME
|
||||
STEP_START_TIME=$(date +%s)
|
||||
}
|
||||
|
||||
log_step_end() {
|
||||
local step_name="${1:-Unknown step}"
|
||||
local end_time
|
||||
end_time=$(date +%s)
|
||||
local duration=$((end_time - STEP_START_TIME))
|
||||
echo "=========================================="
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Completed: $step_name"
|
||||
echo "[LOG] Step: $step_name | Duration: ${duration}s"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
}
|
||||
|
||||
start_mini_services() {
|
||||
local mini_services_dir="$PROJECT_DIR/mini-services"
|
||||
local started_count=0
|
||||
|
||||
log_step_start "Starting mini-services"
|
||||
if [ ! -d "$mini_services_dir" ]; then
|
||||
echo "Mini-services directory not found, skipping..."
|
||||
log_step_end "Starting mini-services"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Found mini-services directory, scanning for sub-services..."
|
||||
|
||||
for service_dir in "$mini_services_dir"/*; do
|
||||
if [ ! -d "$service_dir" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
local service_name
|
||||
service_name=$(basename "$service_dir")
|
||||
echo "Checking service: $service_name"
|
||||
|
||||
if [ ! -f "$service_dir/package.json" ]; then
|
||||
echo "[$service_name] No package.json found, skipping..."
|
||||
continue
|
||||
fi
|
||||
|
||||
if ! grep -q '"dev"' "$service_dir/package.json"; then
|
||||
echo "[$service_name] No dev script found, skipping..."
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "Starting $service_name in background..."
|
||||
(
|
||||
cd "$service_dir"
|
||||
echo "[$service_name] Installing dependencies..."
|
||||
bun install
|
||||
echo "[$service_name] Running bun run dev..."
|
||||
exec bun run dev
|
||||
) >"$PROJECT_DIR/.zscripts/mini-service-${service_name}.log" 2>&1 &
|
||||
|
||||
local service_pid=$!
|
||||
echo "[$service_name] Started in background (PID: $service_pid)"
|
||||
echo "[$service_name] Log: $PROJECT_DIR/.zscripts/mini-service-${service_name}.log"
|
||||
disown "$service_pid" 2>/dev/null || true
|
||||
started_count=$((started_count + 1))
|
||||
done
|
||||
|
||||
echo "Mini-services startup completed. Started $started_count service(s)."
|
||||
log_step_end "Starting mini-services"
|
||||
}
|
||||
|
||||
wait_for_service() {
|
||||
local host="$1"
|
||||
local port="$2"
|
||||
local service_name="$3"
|
||||
local max_attempts="${4:-60}"
|
||||
local attempt=1
|
||||
|
||||
echo "Waiting for $service_name to be ready on $host:$port..."
|
||||
|
||||
while [ "$attempt" -le "$max_attempts" ]; do
|
||||
if curl -s --connect-timeout 2 --max-time 5 "http://$host:$port" >/dev/null 2>&1; then
|
||||
echo "$service_name is ready!"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Attempt $attempt/$max_attempts: $service_name not ready yet, waiting..."
|
||||
sleep 1
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
echo "ERROR: $service_name failed to start within $max_attempts seconds"
|
||||
return 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ -n "${DEV_PID:-}" ] && kill -0 "$DEV_PID" >/dev/null 2>&1; then
|
||||
echo "Stopping Next.js dev server (PID: $DEV_PID)..."
|
||||
kill "$DEV_PID" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
if ! command -v bun >/dev/null 2>&1; then
|
||||
echo "ERROR: bun is not installed or not in PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
log_step_start "bun install"
|
||||
echo "[BUN] Installing dependencies..."
|
||||
bun install
|
||||
log_step_end "bun install"
|
||||
|
||||
log_step_start "bun run db:push"
|
||||
echo "[BUN] Setting up database..."
|
||||
bun run db:push
|
||||
log_step_end "bun run db:push"
|
||||
|
||||
log_step_start "Starting Next.js dev server"
|
||||
echo "[BUN] Starting development server..."
|
||||
bun run dev &
|
||||
DEV_PID=$!
|
||||
log_step_end "Starting Next.js dev server"
|
||||
|
||||
log_step_start "Waiting for Next.js dev server"
|
||||
wait_for_service "localhost" "3000" "Next.js dev server"
|
||||
log_step_end "Waiting for Next.js dev server"
|
||||
|
||||
log_step_start "Health check"
|
||||
echo "[BUN] Performing health check..."
|
||||
curl -fsS localhost:3000 >/dev/null
|
||||
echo "[BUN] Health check passed"
|
||||
log_step_end "Health check"
|
||||
|
||||
start_mini_services
|
||||
|
||||
echo "Next.js dev server is running in background (PID: $DEV_PID)."
|
||||
echo "Use 'kill $DEV_PID' to stop it."
|
||||
disown "$DEV_PID" 2>/dev/null || true
|
||||
unset DEV_PID
|
||||
78
.zscripts/mini-services-build.sh
Executable file
78
.zscripts/mini-services-build.sh
Executable file
@@ -0,0 +1,78 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 配置项
|
||||
ROOT_DIR="/home/z/my-project/mini-services"
|
||||
DIST_DIR="/tmp/build_fullstack_$BUILD_ID/mini-services-dist"
|
||||
|
||||
main() {
|
||||
echo "🚀 开始批量构建..."
|
||||
|
||||
# 检查 rootdir 是否存在
|
||||
if [ ! -d "$ROOT_DIR" ]; then
|
||||
echo "ℹ️ 目录 $ROOT_DIR 不存在,跳过构建"
|
||||
return
|
||||
fi
|
||||
|
||||
# 创建输出目录(如果不存在)
|
||||
mkdir -p "$DIST_DIR"
|
||||
|
||||
# 统计变量
|
||||
success_count=0
|
||||
fail_count=0
|
||||
|
||||
# 遍历 mini-services 目录下的所有文件夹
|
||||
for dir in "$ROOT_DIR"/*; do
|
||||
# 检查是否是目录且包含 package.json
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
project_name=$(basename "$dir")
|
||||
|
||||
# 智能查找入口文件 (按优先级查找)
|
||||
entry_path=""
|
||||
for entry in "src/index.ts" "index.ts" "src/index.js" "index.js"; do
|
||||
if [ -f "$dir/$entry" ]; then
|
||||
entry_path="$dir/$entry"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$entry_path" ]; then
|
||||
echo "⚠️ 跳过 $project_name: 未找到入口文件 (index.ts/js)"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📦 正在构建: $project_name..."
|
||||
|
||||
# 使用 bun build CLI 构建
|
||||
output_file="$DIST_DIR/mini-service-$project_name.js"
|
||||
|
||||
if bun build "$entry_path" \
|
||||
--outfile "$output_file" \
|
||||
--target bun \
|
||||
--minify; then
|
||||
echo "✅ $project_name 构建成功 -> $output_file"
|
||||
success_count=$((success_count + 1))
|
||||
else
|
||||
echo "❌ $project_name 构建失败"
|
||||
fail_count=$((fail_count + 1))
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -f ./.zscripts/mini-services-start.sh ]; then
|
||||
cp ./.zscripts/mini-services-start.sh "$DIST_DIR/mini-services-start.sh"
|
||||
chmod +x "$DIST_DIR/mini-services-start.sh"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎉 所有任务完成!"
|
||||
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
|
||||
echo "✅ 成功: $success_count 个"
|
||||
if [ $fail_count -gt 0 ]; then
|
||||
echo "❌ 失败: $fail_count 个"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
65
.zscripts/mini-services-install.sh
Executable file
65
.zscripts/mini-services-install.sh
Executable file
@@ -0,0 +1,65 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 配置项
|
||||
ROOT_DIR="/home/z/my-project/mini-services"
|
||||
|
||||
main() {
|
||||
echo "🚀 开始批量安装依赖..."
|
||||
|
||||
# 检查 rootdir 是否存在
|
||||
if [ ! -d "$ROOT_DIR" ]; then
|
||||
echo "ℹ️ 目录 $ROOT_DIR 不存在,跳过安装"
|
||||
return
|
||||
fi
|
||||
|
||||
# 统计变量
|
||||
success_count=0
|
||||
fail_count=0
|
||||
failed_projects=""
|
||||
|
||||
# 遍历 mini-services 目录下的所有文件夹
|
||||
for dir in "$ROOT_DIR"/*; do
|
||||
# 检查是否是目录且包含 package.json
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
project_name=$(basename "$dir")
|
||||
echo ""
|
||||
echo "📦 正在安装依赖: $project_name..."
|
||||
|
||||
# 进入项目目录并执行 bun install
|
||||
if (cd "$dir" && bun install); then
|
||||
echo "✅ $project_name 依赖安装成功"
|
||||
success_count=$((success_count + 1))
|
||||
else
|
||||
echo "❌ $project_name 依赖安装失败"
|
||||
fail_count=$((fail_count + 1))
|
||||
if [ -z "$failed_projects" ]; then
|
||||
failed_projects="$project_name"
|
||||
else
|
||||
failed_projects="$failed_projects $project_name"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# 汇总结果
|
||||
echo ""
|
||||
echo "=================================================="
|
||||
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
|
||||
echo "🎉 安装完成!"
|
||||
echo "✅ 成功: $success_count 个"
|
||||
if [ $fail_count -gt 0 ]; then
|
||||
echo "❌ 失败: $fail_count 个"
|
||||
echo ""
|
||||
echo "失败的项目:"
|
||||
for project in $failed_projects; do
|
||||
echo " - $project"
|
||||
done
|
||||
fi
|
||||
else
|
||||
echo "ℹ️ 未找到任何包含 package.json 的项目"
|
||||
fi
|
||||
echo "=================================================="
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
123
.zscripts/mini-services-start.sh
Executable file
123
.zscripts/mini-services-start.sh
Executable file
@@ -0,0 +1,123 @@
|
||||
#!/bin/sh
|
||||
|
||||
# 配置项
|
||||
DIST_DIR="./mini-services-dist"
|
||||
|
||||
# 存储所有子进程的 PID
|
||||
pids=""
|
||||
|
||||
# 清理函数:优雅关闭所有服务
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "🛑 正在关闭所有服务..."
|
||||
|
||||
# 发送 SIGTERM 信号给所有子进程
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
|
||||
echo " 关闭进程 $pid ($service_name)..."
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# 等待所有进程退出(最多等待 5 秒)
|
||||
sleep 1
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
# 如果还在运行,等待最多 4 秒
|
||||
timeout=4
|
||||
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
# 如果仍然在运行,强制关闭
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo " 强制关闭进程 $pid..."
|
||||
kill -KILL "$pid" 2>/dev/null
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo "✅ 所有服务已关闭"
|
||||
}
|
||||
|
||||
main() {
|
||||
echo "🚀 开始启动所有 mini services..."
|
||||
|
||||
# 检查 dist 目录是否存在
|
||||
if [ ! -d "$DIST_DIR" ]; then
|
||||
echo "ℹ️ 目录 $DIST_DIR 不存在"
|
||||
return
|
||||
fi
|
||||
|
||||
# 查找所有 mini-service-*.js 文件
|
||||
service_files=""
|
||||
for file in "$DIST_DIR"/mini-service-*.js; do
|
||||
if [ -f "$file" ]; then
|
||||
if [ -z "$service_files" ]; then
|
||||
service_files="$file"
|
||||
else
|
||||
service_files="$service_files $file"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# 计算服务文件数量
|
||||
service_count=0
|
||||
for file in $service_files; do
|
||||
service_count=$((service_count + 1))
|
||||
done
|
||||
|
||||
if [ $service_count -eq 0 ]; then
|
||||
echo "ℹ️ 未找到任何 mini service 文件"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "📦 找到 $service_count 个服务,开始启动..."
|
||||
echo ""
|
||||
|
||||
# 启动每个服务
|
||||
for file in $service_files; do
|
||||
service_name=$(basename "$file" .js | sed 's/mini-service-//')
|
||||
echo "▶️ 启动服务: $service_name..."
|
||||
|
||||
# 使用 bun 运行服务(后台运行)
|
||||
bun "$file" &
|
||||
pid=$!
|
||||
if [ -z "$pids" ]; then
|
||||
pids="$pid"
|
||||
else
|
||||
pids="$pids $pid"
|
||||
fi
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 0.5
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
echo "❌ $service_name 启动失败"
|
||||
# 从字符串中移除失败的 PID
|
||||
pids=$(echo "$pids" | sed "s/\b$pid\b//" | sed 's/ */ /g' | sed 's/^ *//' | sed 's/ *$//')
|
||||
else
|
||||
echo "✅ $service_name 已启动 (PID: $pid)"
|
||||
fi
|
||||
done
|
||||
|
||||
# 计算运行中的服务数量
|
||||
running_count=0
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
running_count=$((running_count + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "🎉 所有服务已启动!共 $running_count 个服务正在运行"
|
||||
echo ""
|
||||
echo "💡 按 Ctrl+C 停止所有服务"
|
||||
echo ""
|
||||
|
||||
# 等待所有后台进程
|
||||
wait
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
135
.zscripts/start.sh
Executable file
135
.zscripts/start.sh
Executable file
@@ -0,0 +1,135 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
# 获取脚本所在目录
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
BUILD_DIR="$SCRIPT_DIR"
|
||||
|
||||
# 存储所有子进程的 PID
|
||||
pids=""
|
||||
|
||||
# 清理函数:优雅关闭所有服务
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "🛑 正在关闭所有服务..."
|
||||
|
||||
# 发送 SIGTERM 信号给所有子进程
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
|
||||
echo " 关闭进程 $pid ($service_name)..."
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# 等待所有进程退出(最多等待 5 秒)
|
||||
sleep 1
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
# 如果还在运行,等待最多 4 秒
|
||||
timeout=4
|
||||
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
# 如果仍然在运行,强制关闭
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo " 强制关闭进程 $pid..."
|
||||
kill -KILL "$pid" 2>/dev/null
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo "✅ 所有服务已关闭"
|
||||
exit 0
|
||||
}
|
||||
|
||||
echo "🚀 开始启动所有服务..."
|
||||
echo ""
|
||||
|
||||
# 切换到构建目录
|
||||
cd "$BUILD_DIR" || exit 1
|
||||
|
||||
ls -lah
|
||||
|
||||
DEFAULT_PACKAGED_DB_PATH="/app/db/custom.db"
|
||||
DEFAULT_PACKAGED_DATABASE_URL="file:$DEFAULT_PACKAGED_DB_PATH"
|
||||
|
||||
# 启动 Next.js 服务器
|
||||
if [ -f "./next-service-dist/server.js" ]; then
|
||||
echo "🚀 启动 Next.js 服务器..."
|
||||
cd next-service-dist/ || exit 1
|
||||
|
||||
# 设置环境变量
|
||||
export NODE_ENV=production
|
||||
export PORT="${PORT:-3000}"
|
||||
export HOSTNAME="${HOSTNAME:-0.0.0.0}"
|
||||
export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PACKAGED_DATABASE_URL}"
|
||||
|
||||
if [ "$DATABASE_URL" = "$DEFAULT_PACKAGED_DATABASE_URL" ]; then
|
||||
if [ ! -f "$DEFAULT_PACKAGED_DB_PATH" ]; then
|
||||
echo "❌ 未找到打包后的数据库文件 $DEFAULT_PACKAGED_DB_PATH"
|
||||
echo " 为避免生产环境启动到空数据库,启动已终止"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🗄️ 当前使用打包数据库: $DEFAULT_PACKAGED_DB_PATH"
|
||||
else
|
||||
echo "🗄️ 当前使用外部指定数据库: $DATABASE_URL"
|
||||
fi
|
||||
|
||||
# 后台启动 Next.js
|
||||
bun server.js &
|
||||
NEXT_PID=$!
|
||||
pids="$NEXT_PID"
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 1
|
||||
if ! kill -0 "$NEXT_PID" 2>/dev/null; then
|
||||
echo "❌ Next.js 服务器启动失败"
|
||||
exit 1
|
||||
else
|
||||
echo "✅ Next.js 服务器已启动 (PID: $NEXT_PID, Port: $PORT)"
|
||||
fi
|
||||
|
||||
cd ../
|
||||
else
|
||||
echo "⚠️ 未找到 Next.js 服务器文件: ./next-service-dist/server.js"
|
||||
fi
|
||||
|
||||
# 启动 mini-services
|
||||
if [ -f "./mini-services-start.sh" ]; then
|
||||
echo "🚀 启动 mini-services..."
|
||||
|
||||
# 运行启动脚本(从根目录运行,脚本内部会处理 mini-services-dist 目录)
|
||||
sh ./mini-services-start.sh &
|
||||
MINI_PID=$!
|
||||
pids="$pids $MINI_PID"
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 1
|
||||
if ! kill -0 "$MINI_PID" 2>/dev/null; then
|
||||
echo "⚠️ mini-services 可能启动失败,但继续运行..."
|
||||
else
|
||||
echo "✅ mini-services 已启动 (PID: $MINI_PID)"
|
||||
fi
|
||||
elif [ -d "./mini-services-dist" ]; then
|
||||
echo "⚠️ 未找到 mini-services 启动脚本,但目录存在"
|
||||
else
|
||||
echo "ℹ️ mini-services 目录不存在,跳过"
|
||||
fi
|
||||
|
||||
# 启动 Caddy(如果存在 Caddyfile)
|
||||
echo "🚀 启动 Caddy..."
|
||||
|
||||
# Caddy 作为前台进程运行(主进程)
|
||||
echo "✅ Caddy 已启动(前台运行)"
|
||||
echo ""
|
||||
echo "🎉 所有服务已启动!"
|
||||
echo ""
|
||||
echo "💡 按 Ctrl+C 停止所有服务"
|
||||
echo ""
|
||||
|
||||
# Caddy 作为主进程运行
|
||||
exec caddy run --config Caddyfile --adapter caddyfile
|
||||
161
CHANGELOG.md
Normal file
161
CHANGELOG.md
Normal file
@@ -0,0 +1,161 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [1.0.0] - 2025-06-06
|
||||
|
||||
### Added
|
||||
|
||||
#### Core Trading Engine
|
||||
- **BybitClient**: Full Bybit API integration with authentication
|
||||
- Market data fetching (tickers, klines, order book)
|
||||
- Order management (place, cancel, query orders)
|
||||
- Position management (get positions, set leverage, close positions)
|
||||
- Wallet balance tracking
|
||||
- Testnet support for safe testing
|
||||
|
||||
#### Signal Generation Engine
|
||||
- **SignalEngine**: AI-powered trading signal generation
|
||||
- Technical analysis with 6+ indicators:
|
||||
- Simple Moving Average (SMA)
|
||||
- Exponential Moving Average (EMA)
|
||||
- Relative Strength Index (RSI)
|
||||
- MACD (Moving Average Convergence Divergence)
|
||||
- Support/Resistance detection
|
||||
- Candlestick pattern recognition
|
||||
- Fundamental analysis from news data
|
||||
- Sentiment analysis with keyword-based scoring
|
||||
- Risk assessment with position sizing
|
||||
- AI reasoning generation using z-ai-web-dev-sdk
|
||||
- Confidence scoring (0-1)
|
||||
- Target price, stop-loss, and take-profit calculation
|
||||
|
||||
#### News Aggregation System
|
||||
- **NewsAggregator**: Multi-source news collection
|
||||
- CryptoPanic integration
|
||||
- CoinGecko status updates
|
||||
- CryptoCompare news feed
|
||||
- Custom RSS feed support
|
||||
- Sentiment analysis for each article
|
||||
- Category detection and tag extraction
|
||||
- Importance scoring
|
||||
- Market-moving news detection
|
||||
|
||||
#### VectorDB Integration
|
||||
- **VectorStore**: Semantic search for news and signals
|
||||
- ChromaDB client integration
|
||||
- Fallback embedding generation
|
||||
- News article storage and retrieval
|
||||
- Signal analysis persistence
|
||||
- Similar signal search
|
||||
- Contextual sentiment analysis
|
||||
|
||||
#### Backtesting Engine
|
||||
- **BacktestEngine**: Strategy simulation on historical data
|
||||
- Historical data generation (can be replaced with real data)
|
||||
- Trade execution simulation
|
||||
- Slippage and fee modeling
|
||||
- Stop-loss and take-profit testing
|
||||
- Performance metrics calculation:
|
||||
- Total and annualized return
|
||||
- Sharpe and Sortino ratios
|
||||
- Maximum drawdown
|
||||
- Win rate and profit factor
|
||||
- Strategy optimization with parameter grid search
|
||||
- Backtest report generation
|
||||
|
||||
#### Demo Trading Mode
|
||||
- **DemoTrader**: Paper trading system
|
||||
- Virtual portfolio management
|
||||
- Order placement and execution
|
||||
- Position tracking with P&L
|
||||
- Stop-loss and take-profit monitoring
|
||||
- Trade statistics and history
|
||||
- Real-time price updates
|
||||
- Event-based notifications
|
||||
|
||||
#### WebSocket Service
|
||||
- **TradingWebSocketService**: Real-time data streaming
|
||||
- Socket.io server implementation
|
||||
- Live price updates
|
||||
- Portfolio sync
|
||||
- Signal subscriptions
|
||||
- Demo trading via WebSocket
|
||||
- News streaming
|
||||
|
||||
#### API Routes
|
||||
- `/api/trading/signals`: Signal generation and retrieval
|
||||
- `/api/trading/news`: News fetching and sentiment
|
||||
- `/api/trading/backtest`: Backtest execution and results
|
||||
- `/api/trading/demo`: Demo trading operations
|
||||
|
||||
#### Dashboard UI
|
||||
- Real-time trading dashboard
|
||||
- 4 main tabs: Signals, Positions, Backtest, News
|
||||
- Live price ticker
|
||||
- Portfolio visualization with charts
|
||||
- Signal generation interface
|
||||
- Position management
|
||||
- News feed with sentiment indicators
|
||||
- Backtesting interface
|
||||
|
||||
### Database Schema
|
||||
- **Signal**: Trading signals with analysis data
|
||||
- **Trade**: Trade execution records
|
||||
- **NewsArticle**: News storage with sentiment
|
||||
- **MarketData**: Cached market data
|
||||
- **BacktestSession**: Backtest configurations
|
||||
- **BacktestResult**: Individual backtest trades
|
||||
- **Portfolio**: Portfolio tracking
|
||||
- **Position**: Open positions
|
||||
- **UserSettings**: User configuration
|
||||
- **SignalRating**: Signal performance ratings
|
||||
- **SystemLog**: System event logging
|
||||
|
||||
### Technical Details
|
||||
- Next.js 16 with App Router
|
||||
- TypeScript 5
|
||||
- Tailwind CSS 4
|
||||
- shadcn/ui components
|
||||
- Prisma ORM with SQLite
|
||||
- Socket.io for real-time updates
|
||||
- Recharts for data visualization
|
||||
- z-ai-web-dev-sdk for AI capabilities
|
||||
|
||||
### Security
|
||||
- API key encryption support
|
||||
- Testnet-first approach
|
||||
- Rate limiting ready
|
||||
- Input validation with Zod
|
||||
|
||||
### Documentation
|
||||
- Comprehensive README
|
||||
- API documentation
|
||||
- Architecture overview
|
||||
- Code comments
|
||||
|
||||
---
|
||||
|
||||
## Upcoming Features
|
||||
|
||||
### [1.1.0] - Planned
|
||||
- CopilotKit integration for conversational trading
|
||||
- Telegram/Discord notifications
|
||||
- Advanced order types (OCO, trailing stop)
|
||||
- Multi-exchange support
|
||||
- Strategy marketplace
|
||||
- Social trading features
|
||||
|
||||
### [1.2.0] - Planned
|
||||
- Machine learning model training
|
||||
- Custom strategy builder
|
||||
- Advanced analytics dashboard
|
||||
- Mobile app support
|
||||
|
||||
---
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Description |
|
||||
|---------|------|-------------|
|
||||
| 1.0.0 | 2025-06-06 | Initial release for Mantle Hackathon |
|
||||
23
Caddyfile
Normal file
23
Caddyfile
Normal file
@@ -0,0 +1,23 @@
|
||||
:81 {
|
||||
@transform_port_query {
|
||||
query XTransformPort=*
|
||||
}
|
||||
|
||||
handle @transform_port_query {
|
||||
reverse_proxy localhost:{query.XTransformPort} {
|
||||
header_up Host {host}
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy localhost:3000 {
|
||||
header_up Host {host}
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
}
|
||||
}
|
||||
257
README.md
Normal file
257
README.md
Normal file
@@ -0,0 +1,257 @@
|
||||
# Mantle AI Trader
|
||||
|
||||
<div align="center">
|
||||
<img src="public/logo.svg" alt="Mantle AI Trader" width="200" />
|
||||
<h3>AI-Powered Fundamental News-Based Trading Bot</h3>
|
||||
<p>Built for Mantle Turing Test Hackathon</p>
|
||||
</div>
|
||||
|
||||
## 🚀 Features
|
||||
|
||||
### Core Trading Capabilities
|
||||
- **AI Signal Generation**: Advanced signal generation powered by AI with multi-factor analysis
|
||||
- **Fundamental News Analysis**: Real-time news aggregation from multiple sources with sentiment analysis
|
||||
- **Technical Analysis**: Comprehensive technical indicators (RSI, MACD, SMA, EMA) and pattern recognition
|
||||
- **Risk Assessment**: Intelligent risk scoring and position sizing recommendations
|
||||
|
||||
### Trading Modes
|
||||
- **Demo/Paper Trading**: Test strategies without real money
|
||||
- **Manual Mode**: Execute signals manually with full control
|
||||
- **Auto-Trading**: Automated signal execution (configurable)
|
||||
|
||||
### Analysis Tools
|
||||
- **Backtesting Engine**: Test strategies on historical data with performance metrics
|
||||
- **Signal Rating System**: Track and rate signal performance
|
||||
- **Portfolio Analytics**: Real-time P&L tracking and portfolio visualization
|
||||
|
||||
### Integration
|
||||
- **Bybit API**: Full integration with Bybit exchange (spot and futures)
|
||||
- **WebSocket Real-time Updates**: Live price feeds and portfolio sync
|
||||
- **VectorDB**: Semantic search for news and analysis
|
||||
|
||||
## 📊 Architecture
|
||||
|
||||
```
|
||||
mantle-ai-trader/
|
||||
├── src/
|
||||
│ ├── app/ # Next.js App Router
|
||||
│ │ ├── api/ # API Routes
|
||||
│ │ │ └── trading/ # Trading endpoints
|
||||
│ │ └── page.tsx # Main Dashboard
|
||||
│ ├── lib/
|
||||
│ │ ├── trading/
|
||||
│ │ │ ├── core/ # Core types & Bybit client
|
||||
│ │ │ ├── signals/ # Signal generation engine
|
||||
│ │ │ ├── news/ # News aggregation
|
||||
│ │ │ ├── backtest/ # Backtesting engine
|
||||
│ │ │ └── demo/ # Paper trading
|
||||
│ │ └── vector/ # VectorDB integration
|
||||
│ └── components/ui/ # shadcn/ui components
|
||||
├── mini-services/
|
||||
│ └── trading-service/ # WebSocket service
|
||||
├── prisma/
|
||||
│ └── schema.prisma # Database schema
|
||||
└── tests/ # Test files
|
||||
```
|
||||
|
||||
## 🛠 Installation
|
||||
|
||||
### Prerequisites
|
||||
- Node.js 18+ or Bun
|
||||
- SQLite (included)
|
||||
- Bybit API keys (optional for live trading)
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/yourusername/mantle-ai-trader.git
|
||||
cd mantle-ai-trader
|
||||
|
||||
# Install dependencies
|
||||
bun install
|
||||
|
||||
# Initialize database
|
||||
bun run db:push
|
||||
|
||||
# Start development server
|
||||
bun run dev
|
||||
|
||||
# Start WebSocket service (separate terminal)
|
||||
bun run trading-service
|
||||
```
|
||||
|
||||
## 📈 Usage
|
||||
|
||||
### Dashboard
|
||||
|
||||
Access the dashboard at `http://localhost:3000`
|
||||
|
||||
1. **Signals Tab**: Generate AI signals for any supported trading pair
|
||||
2. **Positions Tab**: View open positions and portfolio allocation
|
||||
3. **Backtest Tab**: Run strategy backtests on historical data
|
||||
4. **News Tab**: Browse latest market news with sentiment analysis
|
||||
|
||||
### API Endpoints
|
||||
|
||||
#### Signals
|
||||
```bash
|
||||
# Generate signal
|
||||
POST /api/trading/signals
|
||||
Body: { "symbol": "BTCUSDT", "timeframe": "1h", "demo": true }
|
||||
|
||||
# Get signals
|
||||
GET /api/trading/signals?symbol=BTCUSDT&limit=50
|
||||
```
|
||||
|
||||
#### Demo Trading
|
||||
```bash
|
||||
# Get portfolio
|
||||
GET /api/trading/demo?action=portfolio
|
||||
|
||||
# Place order
|
||||
POST /api/trading/demo
|
||||
Body: { "action": "place_order", "symbol": "BTCUSDT", "side": "BUY", "quantity": 0.01, "type": "MARKET" }
|
||||
|
||||
# Close position
|
||||
POST /api/trading/demo
|
||||
Body: { "action": "close_position", "symbol": "BTCUSDT" }
|
||||
```
|
||||
|
||||
#### Backtest
|
||||
```bash
|
||||
# Run backtest
|
||||
POST /api/trading/backtest
|
||||
Body: {
|
||||
"symbol": "BTCUSDT",
|
||||
"startDate": "2024-01-01",
|
||||
"endDate": "2024-06-01",
|
||||
"initialCapital": 10000
|
||||
}
|
||||
```
|
||||
|
||||
#### News
|
||||
```bash
|
||||
# Get news
|
||||
GET /api/trading/news?symbol=BTC&limit=20
|
||||
|
||||
# Get sentiment
|
||||
GET /api/trading/news/sentiment?symbol=BTC
|
||||
```
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Create a `.env` file:
|
||||
|
||||
```env
|
||||
# Bybit API (optional - for live trading)
|
||||
BYBIT_API_KEY=your_api_key
|
||||
BYBIT_API_SECRET=your_api_secret
|
||||
BYBIT_TESTNET=true
|
||||
|
||||
# News APIs (optional)
|
||||
CRYPTOPANIC_API_KEY=your_key
|
||||
CRYPTOCOMPARE_API_KEY=your_key
|
||||
|
||||
# ChromaDB (optional - for vector search)
|
||||
CHROMADB_URL=http://localhost:8000
|
||||
|
||||
# Database
|
||||
DATABASE_URL="file:./prisma/data/mantle-trader.db"
|
||||
```
|
||||
|
||||
### Risk Settings
|
||||
|
||||
Configure in UserSettings table or via API:
|
||||
- Risk Level: CONSERVATIVE, MODERATE, AGGRESSIVE
|
||||
- Max Position Size: Default $1,000
|
||||
- Max Leverage: Default 5x
|
||||
- Auto Trading: Enable/disable automatic execution
|
||||
|
||||
## 📊 Signal Analysis
|
||||
|
||||
Each signal includes:
|
||||
|
||||
### Technical Analysis
|
||||
- Trend direction and strength
|
||||
- Support and resistance levels
|
||||
- RSI, MACD, Moving Averages
|
||||
- Candlestick patterns (Doji, Hammer, Engulfing, etc.)
|
||||
|
||||
### Fundamental Analysis
|
||||
- News impact score
|
||||
- Market events summary
|
||||
- Economic factors
|
||||
|
||||
### Sentiment Analysis
|
||||
- Overall sentiment score (-1 to 1)
|
||||
- Sentiment label (Bullish/Bearish/Neutral)
|
||||
- Key topics and trending keywords
|
||||
|
||||
### Risk Assessment
|
||||
- Risk score and level
|
||||
- Suggested stop-loss and take-profit
|
||||
- Position sizing recommendations
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
```bash
|
||||
# Run unit tests
|
||||
bun test tests/unit/
|
||||
|
||||
# Run integration tests
|
||||
bun test tests/integration/
|
||||
|
||||
# Run all tests
|
||||
bun test
|
||||
```
|
||||
|
||||
## 📝 Documentation
|
||||
|
||||
- [API Documentation](./docs/API.md)
|
||||
- [Architecture Guide](./docs/ARCHITECTURE.md)
|
||||
- [Contributing Guide](./docs/CONTRIBUTING.md)
|
||||
|
||||
## 🔒 Security
|
||||
|
||||
- API keys are stored encrypted in the database
|
||||
- All exchange communications use HTTPS
|
||||
- WebSocket connections support authentication
|
||||
- Rate limiting on all API endpoints
|
||||
|
||||
## 📜 License
|
||||
|
||||
MIT License - See [LICENSE](LICENSE) for details.
|
||||
|
||||
## 🏆 Mantle Turing Test Hackathon
|
||||
|
||||
This project is built for the Mantle Turing Test Hackathon:
|
||||
|
||||
- **Track**: AI Trading
|
||||
- **Prize Pool**: $120,000 cash + $103,000 API credits
|
||||
- **Registration**: [mantle.to/Hackathon](https://mantle.to/Hackathon)
|
||||
|
||||
### Competition Tracks
|
||||
- ✅ AI Trading - Trading bots, strategy automation, Bybit API
|
||||
- ✅ AI Alpha & Data - Onchain analytics, anomaly detection
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch
|
||||
3. Commit your changes
|
||||
4. Push to the branch
|
||||
5. Open a Pull Request
|
||||
|
||||
## 📞 Support
|
||||
|
||||
- GitHub Issues: [Report a bug](https://github.com/yourusername/mantle-ai-trader/issues)
|
||||
- Telegram: [Mantle Hackathon Chat](https://t.me/MantleTuringTestHackathon)
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<p>Built with ❤️ for Mantle Turing Test Hackathon</p>
|
||||
</div>
|
||||
21
components.json
Normal file
21
components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
BIN
db/custom.db
Normal file
BIN
db/custom.db
Normal file
Binary file not shown.
50
eslint.config.mjs
Normal file
50
eslint.config.mjs
Normal file
@@ -0,0 +1,50 @@
|
||||
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTypescript from "eslint-config-next/typescript";
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const eslintConfig = [...nextCoreWebVitals, ...nextTypescript, {
|
||||
rules: {
|
||||
// TypeScript rules
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/prefer-as-const": "off",
|
||||
"@typescript-eslint/no-unused-disable-directive": "off",
|
||||
|
||||
// React rules
|
||||
"react-hooks/exhaustive-deps": "off",
|
||||
"react-hooks/purity": "off",
|
||||
"react/no-unescaped-entities": "off",
|
||||
"react/display-name": "off",
|
||||
"react/prop-types": "off",
|
||||
"react-compiler/react-compiler": "off",
|
||||
|
||||
// Next.js rules
|
||||
"@next/next/no-img-element": "off",
|
||||
"@next/next/no-html-link-for-pages": "off",
|
||||
|
||||
// General JavaScript rules
|
||||
"prefer-const": "off",
|
||||
"no-unused-vars": "off",
|
||||
"no-console": "off",
|
||||
"no-debugger": "off",
|
||||
"no-empty": "off",
|
||||
"no-irregular-whitespace": "off",
|
||||
"no-case-declarations": "off",
|
||||
"no-fallthrough": "off",
|
||||
"no-mixed-spaces-and-tabs": "off",
|
||||
"no-redeclare": "off",
|
||||
"no-undef": "off",
|
||||
"no-unreachable": "off",
|
||||
"no-useless-escape": "off",
|
||||
},
|
||||
}, {
|
||||
ignores: ["node_modules/**", ".next/**", "out/**", "build/**", "next-env.d.ts", "examples/**", "skills"]
|
||||
}];
|
||||
|
||||
export default eslintConfig;
|
||||
196
examples/websocket/frontend.tsx
Normal file
196
examples/websocket/frontend.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
type Message = {
|
||||
id: string;
|
||||
username: string;
|
||||
content: string;
|
||||
timestamp: Date | string;
|
||||
type: 'user' | 'system';
|
||||
}
|
||||
|
||||
export default function SocketDemo() {
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [inputMessage, setInputMessage] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [isUsernameSet, setIsUsernameSet] = useState(false);
|
||||
const [socket, setSocket] = useState<any>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
// Connect to websocket server
|
||||
// Never use PORT in the URL, alyways use XTransformPort
|
||||
// DO NOT change the path, it is used by Caddy to forward the request to the correct port
|
||||
const socketInstance = io('/?XTransformPort=3003', {
|
||||
transports: ['websocket', 'polling'],
|
||||
forceNew: true,
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
timeout: 10000
|
||||
})
|
||||
|
||||
setSocket(socketInstance);
|
||||
|
||||
socketInstance.on('connect', () => {
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
socketInstance.on('disconnect', () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
socketInstance.on('message', (msg: Message) => {
|
||||
setMessages(prev => [...prev, msg]);
|
||||
});
|
||||
|
||||
socketInstance.on('user-joined', (data: { user: User; message: Message }) => {
|
||||
setMessages(prev => [...prev, data.message]);
|
||||
setUsers(prev => {
|
||||
if (!prev.find(u => u.id === data.user.id)) {
|
||||
return [...prev, data.user];
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
});
|
||||
|
||||
socketInstance.on('user-left', (data: { user: User; message: Message }) => {
|
||||
setMessages(prev => [...prev, data.message]);
|
||||
setUsers(prev => prev.filter(u => u.id !== data.user.id));
|
||||
});
|
||||
|
||||
socketInstance.on('users-list', (data: { users: User[] }) => {
|
||||
setUsers(data.users);
|
||||
});
|
||||
|
||||
return () => {
|
||||
socketInstance.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleJoin = () => {
|
||||
if (socket && username.trim() && isConnected) {
|
||||
socket.emit('join', { username: username.trim() });
|
||||
setIsUsernameSet(true);
|
||||
}
|
||||
};
|
||||
|
||||
const sendMessage = () => {
|
||||
if (socket && inputMessage.trim() && username.trim()) {
|
||||
socket.emit('message', {
|
||||
content: inputMessage.trim(),
|
||||
username: username.trim()
|
||||
});
|
||||
setInputMessage('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
sendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
WebSocket Demo
|
||||
<span className={`text-sm px-2 py-1 rounded ${isConnected ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
|
||||
{isConnected ? 'Connected' : 'Disconnected'}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{!isUsernameSet ? (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
onKeyPress={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleJoin();
|
||||
}
|
||||
}}
|
||||
placeholder="Enter your username..."
|
||||
disabled={!isConnected}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleJoin}
|
||||
disabled={!isConnected || !username.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
Join Chat
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ScrollArea className="h-80 w-full border rounded-md p-4">
|
||||
<div className="space-y-2">
|
||||
{messages.length === 0 ? (
|
||||
<p className="text-gray-500 text-center">No messages yet</p>
|
||||
) : (
|
||||
messages.map((msg) => (
|
||||
<div key={msg.id} className="border-b pb-2 last:border-b-0">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<p className={`text-sm font-medium ${msg.type === 'system'
|
||||
? 'text-blue-600 italic'
|
||||
: 'text-gray-700'
|
||||
}`}>
|
||||
{msg.username}
|
||||
</p>
|
||||
<p className={`${msg.type === 'system'
|
||||
? 'text-blue-500 italic'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{msg.content}
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(msg.timestamp).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Input
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
placeholder="Type a message..."
|
||||
disabled={!isConnected}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={sendMessage}
|
||||
disabled={!isConnected || !inputMessage.trim()}
|
||||
>
|
||||
Send
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
examples/websocket/server.ts
Normal file
138
examples/websocket/server.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { createServer } from 'http'
|
||||
import { Server } from 'socket.io'
|
||||
|
||||
const httpServer = createServer()
|
||||
const io = new Server(httpServer, {
|
||||
// DO NOT change the path, it is used by Caddy to forward the request to the correct port
|
||||
path: '/',
|
||||
cors: {
|
||||
origin: "*",
|
||||
methods: ["GET", "POST"]
|
||||
},
|
||||
pingTimeout: 60000,
|
||||
pingInterval: 25000,
|
||||
})
|
||||
|
||||
interface User {
|
||||
id: string
|
||||
username: string
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string
|
||||
username: string
|
||||
content: string
|
||||
timestamp: Date
|
||||
type: 'user' | 'system'
|
||||
}
|
||||
|
||||
const users = new Map<string, User>()
|
||||
|
||||
const generateMessageId = () => Math.random().toString(36).substr(2, 9)
|
||||
|
||||
const createSystemMessage = (content: string): Message => ({
|
||||
id: generateMessageId(),
|
||||
username: 'System',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
type: 'system'
|
||||
})
|
||||
|
||||
const createUserMessage = (username: string, content: string): Message => ({
|
||||
id: generateMessageId(),
|
||||
username,
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
type: 'user'
|
||||
})
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log(`User connected: ${socket.id}`)
|
||||
|
||||
// Add test event handler
|
||||
socket.on('test', (data) => {
|
||||
console.log('Received test message:', data)
|
||||
socket.emit('test-response', {
|
||||
message: 'Server received test message',
|
||||
data: data,
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
})
|
||||
|
||||
socket.on('join', (data: { username: string }) => {
|
||||
const { username } = data
|
||||
|
||||
// Create user object
|
||||
const user: User = {
|
||||
id: socket.id,
|
||||
username
|
||||
}
|
||||
|
||||
// Add to user list
|
||||
users.set(socket.id, user)
|
||||
|
||||
// Send join message to all users
|
||||
const joinMessage = createSystemMessage(`${username} joined the chat room`)
|
||||
io.emit('user-joined', { user, message: joinMessage })
|
||||
|
||||
// Send current user list to new user
|
||||
const usersList = Array.from(users.values())
|
||||
socket.emit('users-list', { users: usersList })
|
||||
|
||||
console.log(`${username} joined the chat room, current online users: ${users.size}`)
|
||||
})
|
||||
|
||||
socket.on('message', (data: { content: string; username: string }) => {
|
||||
const { content, username } = data
|
||||
const user = users.get(socket.id)
|
||||
|
||||
if (user && user.username === username) {
|
||||
const message = createUserMessage(username, content)
|
||||
io.emit('message', message)
|
||||
console.log(`${username}: ${content}`)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
const user = users.get(socket.id)
|
||||
|
||||
if (user) {
|
||||
// Remove from user list
|
||||
users.delete(socket.id)
|
||||
|
||||
// Send leave message to all users
|
||||
const leaveMessage = createSystemMessage(`${user.username} left the chat room`)
|
||||
io.emit('user-left', { user: { id: socket.id, username: user.username }, message: leaveMessage })
|
||||
|
||||
console.log(`${user.username} left the chat room, current online users: ${users.size}`)
|
||||
} else {
|
||||
console.log(`User disconnected: ${socket.id}`)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('error', (error) => {
|
||||
console.error(`Socket error (${socket.id}):`, error)
|
||||
})
|
||||
})
|
||||
|
||||
const PORT = 3003
|
||||
httpServer.listen(PORT, () => {
|
||||
console.log(`WebSocket server running on port ${PORT}`)
|
||||
})
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('Received SIGTERM signal, shutting down server...')
|
||||
httpServer.close(() => {
|
||||
console.log('WebSocket server closed')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('Received SIGINT signal, shutting down server...')
|
||||
httpServer.close(() => {
|
||||
console.log('WebSocket server closed')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
0
mini-services/.gitkeep
Normal file
0
mini-services/.gitkeep
Normal file
57
mini-services/trading-service/bun.lock
Normal file
57
mini-services/trading-service/bun.lock
Normal file
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "trading-service",
|
||||
"dependencies": {
|
||||
"socket.io": "^4.8.3",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@socket.io/component-emitter": ["@socket.io/component-emitter@3.1.2", "", {}, "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="],
|
||||
|
||||
"@types/cors": ["@types/cors@2.8.19", "", { "dependencies": { "@types/node": "*" } }, "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg=="],
|
||||
|
||||
"@types/node": ["@types/node@25.9.2", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-G05zqtJhcDLb8uslf5EjCxXg9G1KQxiV8OS0R26IC//Eoyitzqe8z37I7cqvnZlrlSfgocQRfSn/AHBZJJFyGw=="],
|
||||
|
||||
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
|
||||
"accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],
|
||||
|
||||
"base64id": ["base64id@2.0.0", "", {}, "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog=="],
|
||||
|
||||
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
|
||||
|
||||
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"engine.io": ["engine.io@6.6.8", "", { "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", "@types/ws": "^8.5.12", "accepts": "~1.3.4", "base64id": "2.0.0", "cookie": "~0.7.2", "cors": "~2.8.5", "debug": "~4.4.1", "engine.io-parser": "~5.2.1", "ws": "~8.20.1" } }, "sha512-2agL3ueZhqxoVrfmntO8yuVj+uNSlIOnhykYHk3Cq0ShYPdUjjUiSJrQvXjq01I9jAuI0Zl2YO8Evv5Mqytm5g=="],
|
||||
|
||||
"engine.io-parser": ["engine.io-parser@5.2.3", "", {}, "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="],
|
||||
|
||||
"mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
|
||||
|
||||
"mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],
|
||||
|
||||
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
|
||||
|
||||
"socket.io": ["socket.io@4.8.3", "", { "dependencies": { "accepts": "~1.3.4", "base64id": "~2.0.0", "cors": "~2.8.5", "debug": "~4.4.1", "engine.io": "~6.6.0", "socket.io-adapter": "~2.5.2", "socket.io-parser": "~4.2.4" } }, "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A=="],
|
||||
|
||||
"socket.io-adapter": ["socket.io-adapter@2.5.7", "", { "dependencies": { "debug": "~4.4.1", "ws": "~8.20.1" } }, "sha512-e0LyK91f3cUxTmv95/KzoLg47+zF+s/sbxRGDNsyG4dmIP8ZSX8ax6byOxfJXeNNtS/8AZlfD+uP7gBeR7DLlg=="],
|
||||
|
||||
"socket.io-parser": ["socket.io-parser@4.2.6", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1" } }, "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg=="],
|
||||
|
||||
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
|
||||
|
||||
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
|
||||
|
||||
"ws": ["ws@8.20.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w=="],
|
||||
}
|
||||
}
|
||||
319
mini-services/trading-service/index.ts
Normal file
319
mini-services/trading-service/index.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* Trading WebSocket Service for Mantle AI Trading Bot
|
||||
* Real-time updates for signals, prices, and portfolio
|
||||
*/
|
||||
|
||||
import { Server as HttpServer } from 'http';
|
||||
import { Server as SocketIOServer, Socket } from 'socket.io';
|
||||
import { signalEngine } from '../../src/lib/trading/signals/signal-engine';
|
||||
import { demoTrader } from '../../src/lib/trading/demo/demo-trader';
|
||||
import { newsAggregator } from '../../src/lib/trading/news/news-aggregator';
|
||||
import { TradeAction, TimeFrame } from '../../src/lib/trading/core/types';
|
||||
|
||||
interface SignalSubscription {
|
||||
symbol: string;
|
||||
timeframe: TimeFrame;
|
||||
interval: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
export class TradingWebSocketService {
|
||||
private io: SocketIOServer;
|
||||
private subscriptions: Map<string, SignalSubscription> = new Map();
|
||||
private priceUpdateInterval: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(httpServer: HttpServer) {
|
||||
this.io = new SocketIOServer(httpServer, {
|
||||
cors: {
|
||||
origin: '*',
|
||||
methods: ['GET', 'POST']
|
||||
}
|
||||
});
|
||||
|
||||
this.setupEventHandlers();
|
||||
this.startBackgroundServices();
|
||||
}
|
||||
|
||||
private setupEventHandlers(): void {
|
||||
this.io.on('connection', (socket: Socket) => {
|
||||
console.log(`Client connected: ${socket.id}`);
|
||||
|
||||
// Send initial data
|
||||
this.sendInitialData(socket);
|
||||
|
||||
// Handle signal generation request
|
||||
socket.on('generate_signal', async (data: { symbol: string; timeframe: TimeFrame }) => {
|
||||
try {
|
||||
const signal = await this.generateSignal(data.symbol, data.timeframe);
|
||||
socket.emit('signal_generated', signal);
|
||||
} catch (error) {
|
||||
socket.emit('error', { message: 'Failed to generate signal', error: String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
// Handle signal subscription
|
||||
socket.on('subscribe_signals', (data: { symbol: string; timeframe: TimeFrame }) => {
|
||||
this.subscribeToSignals(socket, data.symbol, data.timeframe);
|
||||
});
|
||||
|
||||
// Handle unsubscribe
|
||||
socket.on('unsubscribe_signals', (data: { symbol: string }) => {
|
||||
this.unsubscribeFromSignals(socket.id, data.symbol);
|
||||
});
|
||||
|
||||
// Handle demo trading
|
||||
socket.on('place_demo_order', (data: {
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
quantity: number;
|
||||
type: 'MARKET' | 'LIMIT';
|
||||
price?: number;
|
||||
}) => {
|
||||
try {
|
||||
const order = demoTrader.placeOrder({
|
||||
symbol: data.symbol,
|
||||
side: data.side,
|
||||
type: data.type,
|
||||
quantity: data.quantity,
|
||||
price: data.price
|
||||
});
|
||||
socket.emit('demo_order_placed', order);
|
||||
this.broadcastPortfolio();
|
||||
} catch (error) {
|
||||
socket.emit('error', { message: 'Failed to place order', error: String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
// Handle close position
|
||||
socket.on('close_demo_position', (data: { symbol: string }) => {
|
||||
const order = demoTrader.closePosition(data.symbol);
|
||||
if (order) {
|
||||
socket.emit('demo_order_placed', order);
|
||||
this.broadcastPortfolio();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle get portfolio
|
||||
socket.on('get_portfolio', () => {
|
||||
socket.emit('portfolio_update', demoTrader.getPortfolio());
|
||||
});
|
||||
|
||||
// Handle get positions
|
||||
socket.on('get_positions', () => {
|
||||
socket.emit('positions_update', demoTrader.getPositions());
|
||||
});
|
||||
|
||||
// Handle get news
|
||||
socket.on('get_news', async (data: { symbol?: string; limit?: number }) => {
|
||||
try {
|
||||
const news = data.symbol
|
||||
? await newsAggregator.getNewsForSymbol(data.symbol, data.limit || 20)
|
||||
: await newsAggregator.fetchAllNews({ limit: data.limit || 50 });
|
||||
socket.emit('news_update', news);
|
||||
} catch (error) {
|
||||
socket.emit('error', { message: 'Failed to fetch news', error: String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
// Handle get sentiment
|
||||
socket.on('get_sentiment', async (data: { symbol: string }) => {
|
||||
try {
|
||||
const sentiment = await newsAggregator.getSymbolSentiment(data.symbol);
|
||||
socket.emit('sentiment_update', { symbol: data.symbol, ...sentiment });
|
||||
} catch (error) {
|
||||
socket.emit('error', { message: 'Failed to fetch sentiment', error: String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
// Handle reset demo
|
||||
socket.on('reset_demo', (data: { initialCapital?: number }) => {
|
||||
demoTrader.reset(data.initialCapital || 10000);
|
||||
this.broadcastPortfolio();
|
||||
socket.emit('demo_reset', { success: true });
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log(`Client disconnected: ${socket.id}`);
|
||||
// Clean up subscriptions
|
||||
for (const [key, sub] of this.subscriptions) {
|
||||
if (key.startsWith(socket.id)) {
|
||||
clearInterval(sub.interval);
|
||||
this.subscriptions.delete(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async sendInitialData(socket: Socket): Promise<void> {
|
||||
// Send current portfolio
|
||||
socket.emit('portfolio_update', demoTrader.getPortfolio());
|
||||
|
||||
// Send positions
|
||||
socket.emit('positions_update', demoTrader.getPositions());
|
||||
|
||||
// Send recent news
|
||||
try {
|
||||
const news = await newsAggregator.fetchAllNews({ limit: 20 });
|
||||
socket.emit('news_update', news);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch initial news:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private async generateSignal(symbol: string, timeframe: TimeFrame) {
|
||||
// Generate simulated market data for demo
|
||||
const marketData = this.generateDemoMarketData(symbol, 200);
|
||||
|
||||
// Fetch news for the symbol
|
||||
const news = await newsAggregator.getNewsForSymbol(symbol, 10);
|
||||
|
||||
const signalOutput = await signalEngine.generateSignal({
|
||||
symbol,
|
||||
timeframe,
|
||||
marketData,
|
||||
newsArticles: news
|
||||
});
|
||||
|
||||
return signalOutput;
|
||||
}
|
||||
|
||||
private subscribeToSignals(socket: Socket, symbol: string, timeframe: TimeFrame): void {
|
||||
const key = `${socket.id}-${symbol}`;
|
||||
|
||||
// Remove existing subscription
|
||||
const existing = this.subscriptions.get(key);
|
||||
if (existing) {
|
||||
clearInterval(existing.interval);
|
||||
}
|
||||
|
||||
// Create new subscription (check every 5 minutes)
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const signal = await this.generateSignal(symbol, timeframe);
|
||||
socket.emit('signal_update', { symbol, signal });
|
||||
} catch (error) {
|
||||
console.error(`Error generating signal for ${symbol}:`, error);
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
this.subscriptions.set(key, {
|
||||
symbol,
|
||||
timeframe,
|
||||
interval
|
||||
});
|
||||
|
||||
socket.emit('subscribed', { symbol, timeframe });
|
||||
}
|
||||
|
||||
private unsubscribeFromSignals(socketId: string, symbol: string): void {
|
||||
const key = `${socketId}-${symbol}`;
|
||||
const sub = this.subscriptions.get(key);
|
||||
|
||||
if (sub) {
|
||||
clearInterval(sub.interval);
|
||||
this.subscriptions.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private startBackgroundServices(): void {
|
||||
// Simulate price updates every 5 seconds
|
||||
this.priceUpdateInterval = setInterval(() => {
|
||||
this.simulatePriceUpdates();
|
||||
}, 5000);
|
||||
|
||||
// Subscribe to demo trader events
|
||||
demoTrader.subscribe((event, data) => {
|
||||
this.io.emit(event, data);
|
||||
});
|
||||
}
|
||||
|
||||
private simulatePriceUpdates(): void {
|
||||
const symbols = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'];
|
||||
const updates: Array<{ symbol: string; price: number; change: number }> = [];
|
||||
|
||||
symbols.forEach(symbol => {
|
||||
// Simulate price movement
|
||||
const basePrice = this.getBasePrice(symbol);
|
||||
const change = (Math.random() - 0.5) * basePrice * 0.002; // 0.2% max change
|
||||
const newPrice = basePrice + change;
|
||||
|
||||
demoTrader.updatePrice(symbol, newPrice);
|
||||
updates.push({ symbol, price: newPrice, change: change / basePrice * 100 });
|
||||
});
|
||||
|
||||
this.io.emit('price_updates', updates);
|
||||
this.broadcastPortfolio();
|
||||
}
|
||||
|
||||
private getBasePrice(symbol: string): number {
|
||||
const prices: Record<string, number> = {
|
||||
BTCUSDT: 45000,
|
||||
ETHUSDT: 2500,
|
||||
SOLUSDT: 100,
|
||||
BNBUSDT: 300,
|
||||
XRPUSDT: 0.5
|
||||
};
|
||||
return prices[symbol] || 100;
|
||||
}
|
||||
|
||||
private broadcastPortfolio(): void {
|
||||
this.io.emit('portfolio_update', demoTrader.getPortfolio());
|
||||
this.io.emit('positions_update', demoTrader.getPositions());
|
||||
}
|
||||
|
||||
private generateDemoMarketData(symbol: string, count: number) {
|
||||
const data = [];
|
||||
let price = this.getBasePrice(symbol);
|
||||
const now = Date.now();
|
||||
const hourMs = 60 * 60 * 1000;
|
||||
|
||||
for (let i = count; i >= 0; i--) {
|
||||
const change = (Math.random() - 0.5) * price * 0.02;
|
||||
const open = price;
|
||||
const close = price + change;
|
||||
const high = Math.max(open, close) + Math.random() * Math.abs(change) * 0.5;
|
||||
const low = Math.min(open, close) - Math.random() * Math.abs(change) * 0.5;
|
||||
const volume = 1000 + Math.random() * 5000;
|
||||
|
||||
data.push({
|
||||
symbol,
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
timestamp: new Date(now - i * hourMs),
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume
|
||||
});
|
||||
|
||||
price = close;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public getIO(): SocketIOServer {
|
||||
return this.io;
|
||||
}
|
||||
|
||||
public close(): void {
|
||||
if (this.priceUpdateInterval) {
|
||||
clearInterval(this.priceUpdateInterval);
|
||||
}
|
||||
for (const sub of this.subscriptions.values()) {
|
||||
clearInterval(sub.interval);
|
||||
}
|
||||
this.io.close();
|
||||
}
|
||||
}
|
||||
|
||||
// Create HTTP server and WebSocket service
|
||||
const httpServer = new HttpServer();
|
||||
const tradingService = new TradingWebSocketService(httpServer);
|
||||
|
||||
const PORT = 3003;
|
||||
httpServer.listen(PORT, () => {
|
||||
console.log(`Trading WebSocket Service running on port ${PORT}`);
|
||||
});
|
||||
|
||||
export default tradingService;
|
||||
11
mini-services/trading-service/package.json
Normal file
11
mini-services/trading-service/package.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "trading-service",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun --hot index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"socket.io": "^4.8.3"
|
||||
}
|
||||
}
|
||||
12
next.config.ts
Normal file
12
next.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
/* config options here */
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
reactStrictMode: false,
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
114
package.json
Normal file
114
package.json
Normal file
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"name": "mantle-ai-trader",
|
||||
"version": "1.0.0",
|
||||
"description": "AI-powered trading bot for Mantle Turing Test Hackathon - Fundamental news-based trading with signals, backtesting, and demo mode",
|
||||
"main": "src/app/page.tsx",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3000 2>&1 | tee dev.log",
|
||||
"build": "next build && cp -r .next/static .next/standalone/.next/ && cp -r public .next/standalone/",
|
||||
"start": "NODE_ENV=production bun .next/standalone/server.js 2>&1 | tee server.log",
|
||||
"lint": "eslint .",
|
||||
"test": "bun test tests/",
|
||||
"db:push": "prisma db push",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:reset": "prisma migrate reset",
|
||||
"trading-service": "cd mini-services/trading-service && bun run dev"
|
||||
},
|
||||
"keywords": [
|
||||
"trading-bot",
|
||||
"ai-trading",
|
||||
"cryptocurrency",
|
||||
"bybit",
|
||||
"signals",
|
||||
"backtesting",
|
||||
"mantle",
|
||||
"hackathon"
|
||||
],
|
||||
"author": "Mantle AI Trader Team",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.1.1",
|
||||
"@mdxeditor/editor": "^3.39.1",
|
||||
"@prisma/client": "^6.11.1",
|
||||
"@radix-ui/react-accordion": "^1.2.11",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.14",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.7",
|
||||
"@radix-ui/react-avatar": "^1.1.10",
|
||||
"@radix-ui/react-checkbox": "^1.3.2",
|
||||
"@radix-ui/react-collapsible": "^1.1.11",
|
||||
"@radix-ui/react-context-menu": "^2.2.15",
|
||||
"@radix-ui/react-dialog": "^1.1.14",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.15",
|
||||
"@radix-ui/react-hover-card": "^1.1.14",
|
||||
"@radix-ui/react-label": "^2.1.7",
|
||||
"@radix-ui/react-menubar": "^1.1.15",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.13",
|
||||
"@radix-ui/react-popover": "^1.1.14",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@radix-ui/react-radio-group": "^1.3.7",
|
||||
"@radix-ui/react-scroll-area": "^1.2.9",
|
||||
"@radix-ui/react-select": "^2.2.5",
|
||||
"@radix-ui/react-separator": "^1.1.7",
|
||||
"@radix-ui/react-slider": "^1.3.5",
|
||||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-switch": "^1.2.5",
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-toast": "^1.2.14",
|
||||
"@radix-ui/react-toggle": "^1.1.9",
|
||||
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@reactuses/core": "^6.0.5",
|
||||
"@tanstack/react-query": "^5.82.0",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"axios": "^1.17.0",
|
||||
"chromadb-client": "^2.4.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.4.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"framer-motion": "^12.23.2",
|
||||
"input-otp": "^1.4.2",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next": "^16.1.1",
|
||||
"next-auth": "^4.24.11",
|
||||
"next-intl": "^4.3.4",
|
||||
"next-themes": "^0.4.6",
|
||||
"prisma": "^6.11.1",
|
||||
"react": "^19.0.0",
|
||||
"react-day-picker": "^9.8.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.60.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^3.0.3",
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.15.4",
|
||||
"sharp": "^0.34.3",
|
||||
"socket.io": "^4.8.3",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"sonner": "^2.0.6",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"uuid": "^11.1.0",
|
||||
"vaul": "^1.1.2",
|
||||
"z-ai-web-dev-sdk": "^0.0.17",
|
||||
"zod": "^4.0.2",
|
||||
"zustand": "^5.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"bun-types": "^1.3.4",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "^16.1.1",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.3.5",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
5
postcss.config.mjs
Normal file
5
postcss.config.mjs
Normal file
@@ -0,0 +1,5 @@
|
||||
const config = {
|
||||
plugins: ["@tailwindcss/postcss"],
|
||||
};
|
||||
|
||||
export default config;
|
||||
BIN
prisma/data/mantle-trader.db
Normal file
BIN
prisma/data/mantle-trader.db
Normal file
Binary file not shown.
242
prisma/schema.prisma
Normal file
242
prisma/schema.prisma
Normal file
@@ -0,0 +1,242 @@
|
||||
// Prisma Schema for Mantle AI Trading Bot
|
||||
// Comprehensive database schema for signals, trades, backtests, and news
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./data/mantle-trader.db"
|
||||
}
|
||||
|
||||
// Signal Management
|
||||
model Signal {
|
||||
id String @id @default(uuid())
|
||||
symbol String // Trading pair e.g., "BTCUSDT"
|
||||
action String // "BUY" | "SELL" | "HOLD"
|
||||
confidence Float // 0.0 to 1.0
|
||||
rating Int @default(0) // User rating 1-5
|
||||
priceTarget Float?
|
||||
stopLoss Float?
|
||||
takeProfit Float?
|
||||
reasoning String // AI-generated reasoning
|
||||
newsSources String? // JSON array of source URLs
|
||||
sentimentScore Float? // -1 to 1
|
||||
technicalScore Float? // 0 to 1
|
||||
fundamentalScore Float? // 0 to 1
|
||||
status String @default("PENDING") // PENDING | EXECUTED | CANCELLED | EXPIRED
|
||||
executedAt DateTime?
|
||||
executedPrice Float?
|
||||
result String? // WIN | LOSS | NEUTRAL
|
||||
resultPnL Float? // Profit/Loss percentage
|
||||
demo Boolean @default(false) // Is this a demo signal?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
trades Trade[]
|
||||
backtestResults BacktestResult[]
|
||||
|
||||
@@index([symbol])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
// Trade Execution
|
||||
model Trade {
|
||||
id String @id @default(uuid())
|
||||
signalId String?
|
||||
signal Signal? @relation(fields: [signalId], references: [id])
|
||||
symbol String
|
||||
side String // "BUY" | "SELL"
|
||||
orderType String // "MARKET" | "LIMIT"
|
||||
quantity Float
|
||||
price Float
|
||||
leverage Float @default(1)
|
||||
stopLoss Float?
|
||||
takeProfit Float?
|
||||
status String @default("PENDING") // PENDING | FILLED | CANCELLED | FAILED
|
||||
orderId String? // Exchange order ID
|
||||
executedAt DateTime?
|
||||
closedAt DateTime?
|
||||
pnl Float?
|
||||
fees Float?
|
||||
demo Boolean @default(false)
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([symbol])
|
||||
@@index([status])
|
||||
}
|
||||
|
||||
// News Articles
|
||||
model NewsArticle {
|
||||
id String @id @default(uuid())
|
||||
title String
|
||||
content String?
|
||||
summary String?
|
||||
source String // e.g., "CryptoPanic", "CoinGecko"
|
||||
sourceUrl String?
|
||||
author String?
|
||||
category String? // e.g., "Bitcoin", "DeFi", "Regulation"
|
||||
sentiment Float? // -1 to 1
|
||||
importance Float? // 0 to 1
|
||||
tags String? // JSON array
|
||||
publishedAt DateTime?
|
||||
fetchedAt DateTime @default(now())
|
||||
processed Boolean @default(false)
|
||||
vectorId String? // ChromaDB vector ID
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([sourceUrl])
|
||||
@@index([source])
|
||||
@@index([category])
|
||||
@@index([publishedAt])
|
||||
}
|
||||
|
||||
// Market Data Cache
|
||||
model MarketData {
|
||||
id String @id @default(uuid())
|
||||
symbol String
|
||||
timeframe String // "1m", "5m", "15m", "1h", "4h", "1d"
|
||||
openPrice Float
|
||||
highPrice Float
|
||||
lowPrice Float
|
||||
closePrice Float
|
||||
volume Float
|
||||
timestamp DateTime
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([symbol, timeframe, timestamp])
|
||||
@@index([symbol, timeframe])
|
||||
}
|
||||
|
||||
// Backtest Sessions
|
||||
model BacktestSession {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
description String?
|
||||
symbol String
|
||||
startDate DateTime
|
||||
endDate DateTime
|
||||
initialCapital Float
|
||||
finalCapital Float?
|
||||
totalTrades Int @default(0)
|
||||
winRate Float?
|
||||
maxDrawdown Float?
|
||||
sharpeRatio Float?
|
||||
status String @default("PENDING") // PENDING | RUNNING | COMPLETED | FAILED
|
||||
config String? // JSON configuration
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
results BacktestResult[]
|
||||
|
||||
@@index([symbol])
|
||||
@@index([status])
|
||||
}
|
||||
|
||||
model BacktestResult {
|
||||
id String @id @default(uuid())
|
||||
sessionId String
|
||||
session BacktestSession @relation(fields: [sessionId], references: [id])
|
||||
signalId String?
|
||||
signal Signal? @relation(fields: [signalId], references: [id])
|
||||
symbol String
|
||||
action String
|
||||
entryPrice Float
|
||||
exitPrice Float?
|
||||
quantity Float
|
||||
pnl Float?
|
||||
pnlPercent Float?
|
||||
executedAt DateTime
|
||||
closedAt DateTime?
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([sessionId])
|
||||
}
|
||||
|
||||
// Portfolio Tracking
|
||||
model Portfolio {
|
||||
id String @id @default(uuid())
|
||||
name String @default("Main Portfolio")
|
||||
totalValue Float @default(0)
|
||||
cashBalance Float @default(0)
|
||||
realizedPnL Float @default(0)
|
||||
unrealizedPnL Float @default(0)
|
||||
demo Boolean @default(false)
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
positions Position[]
|
||||
|
||||
@@index([isActive])
|
||||
}
|
||||
|
||||
model Position {
|
||||
id String @id @default(uuid())
|
||||
portfolioId String
|
||||
portfolio Portfolio @relation(fields: [portfolioId], references: [id])
|
||||
symbol String
|
||||
side String // "LONG" | "SHORT"
|
||||
quantity Float
|
||||
avgEntryPrice Float
|
||||
currentPrice Float?
|
||||
marketValue Float?
|
||||
unrealizedPnL Float?
|
||||
leverage Float @default(1)
|
||||
liquidationPrice Float?
|
||||
openedAt DateTime @default(now())
|
||||
closedAt DateTime?
|
||||
status String @default("OPEN") // OPEN | CLOSED
|
||||
demo Boolean @default(false)
|
||||
|
||||
@@index([portfolioId])
|
||||
@@index([symbol])
|
||||
}
|
||||
|
||||
// User Settings & API Keys (Encrypted in production)
|
||||
model UserSettings {
|
||||
id String @id @default(uuid())
|
||||
bybitApiKey String?
|
||||
bybitApiSecret String?
|
||||
bybitTestnet Boolean @default(true)
|
||||
riskLevel String @default("MODERATE") // CONSERVATIVE | MODERATE | AGGRESSIVE
|
||||
maxPositionSize Float @default(1000)
|
||||
maxLeverage Float @default(5)
|
||||
autoTrading Boolean @default(false)
|
||||
notificationsEnabled Boolean @default(true)
|
||||
telegramChatId String?
|
||||
discordWebhook String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
// Signal Rating History
|
||||
model SignalRating {
|
||||
id String @id @default(uuid())
|
||||
signalId String
|
||||
rating Int // 1-5
|
||||
feedback String?
|
||||
userId String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([signalId])
|
||||
}
|
||||
|
||||
// System Logs
|
||||
model SystemLog {
|
||||
id String @id @default(uuid())
|
||||
level String // INFO | WARNING | ERROR | CRITICAL
|
||||
component String // e.g., "NewsAggregator", "SignalEngine"
|
||||
message String
|
||||
details String? // JSON additional data
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([level])
|
||||
@@index([component])
|
||||
@@index([createdAt])
|
||||
}
|
||||
29
public/logo.svg
Normal file
29
public/logo.svg
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 30 30" style="enable-background:new 0 0 30 30;" xml:space="preserve">
|
||||
<defs>
|
||||
<style type="text/css">
|
||||
.st194{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.6317;stroke-miterlimit:10;}
|
||||
.st23{fill:#FFFFFF;}
|
||||
|
||||
.z-breathe {
|
||||
animation: breathe 2.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
0%, 100% { opacity: 0.7; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g>
|
||||
<path class="st194" d="M24.51,28.51H5.49c-2.21,0-4-1.79-4-4V5.49c0-2.21,1.79-4,4-4h19.03c2.21,0,4,1.79,4,4v19.03
|
||||
C28.51,26.72,26.72,28.51,24.51,28.51z"/>
|
||||
<g class="z-breathe">
|
||||
<path class="st23" d="M15.47,7.1l-1.3,1.85c-0.2,0.29-0.54,0.47-0.9,0.47h-7.1V7.09C6.16,7.1,15.47,7.1,15.47,7.1z"/>
|
||||
<polygon class="st23" points="24.3,7.1 13.14,22.91 5.7,22.91 16.86,7.1"/>
|
||||
<path class="st23" d="M14.53,22.91l1.31-1.86c0.2-0.29,0.54-0.47,0.9-0.47h7.09v2.33H14.53z"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
14
public/robots.txt
Normal file
14
public/robots.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
User-agent: Googlebot
|
||||
Allow: /
|
||||
|
||||
User-agent: Bingbot
|
||||
Allow: /
|
||||
|
||||
User-agent: Twitterbot
|
||||
Allow: /
|
||||
|
||||
User-agent: facebookexternalhit
|
||||
Allow: /
|
||||
|
||||
User-agent: *
|
||||
Allow: /
|
||||
5
src/app/api/route.ts
Normal file
5
src/app/api/route.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({ message: "Hello, world!" });
|
||||
}
|
||||
124
src/app/api/trading/backtest/route.ts
Normal file
124
src/app/api/trading/backtest/route.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Backtest API Routes for Mantle AI Trading Bot
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { backtestEngine } from '@/lib/trading/backtest/backtest-engine';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/trading/backtest - Get backtest sessions
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const sessions = await db.backtestSession.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { results: true }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, data: sessions });
|
||||
} catch (error) {
|
||||
console.error('Error fetching backtest sessions:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to fetch backtest sessions' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/trading/backtest - Run backtest
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const {
|
||||
name,
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
initialCapital = 10000,
|
||||
riskPerTrade = 0.02,
|
||||
fees = 0.001,
|
||||
slippage = 0.001
|
||||
} = body;
|
||||
|
||||
if (!symbol || !startDate || !endDate) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Symbol, startDate, and endDate are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Create session record
|
||||
const session = await db.backtestSession.create({
|
||||
data: {
|
||||
name: name || `Backtest ${symbol}`,
|
||||
symbol,
|
||||
startDate: new Date(startDate),
|
||||
endDate: new Date(endDate),
|
||||
initialCapital,
|
||||
status: 'RUNNING'
|
||||
}
|
||||
});
|
||||
|
||||
// Run backtest asynchronously
|
||||
const result = await backtestEngine.runBacktest({
|
||||
name: session.name,
|
||||
symbol,
|
||||
startDate: new Date(startDate),
|
||||
endDate: new Date(endDate),
|
||||
initialCapital,
|
||||
strategy: 'default',
|
||||
parameters: { riskPerTrade },
|
||||
fees,
|
||||
slippage
|
||||
});
|
||||
|
||||
// Update session with results
|
||||
const updatedSession = await db.backtestSession.update({
|
||||
where: { id: session.id },
|
||||
data: {
|
||||
status: result.status,
|
||||
finalCapital: result.finalCapital,
|
||||
totalTrades: result.totalTrades,
|
||||
winRate: result.winRate,
|
||||
maxDrawdown: result.maxDrawdown,
|
||||
sharpeRatio: result.sharpeRatio
|
||||
}
|
||||
});
|
||||
|
||||
// Save results
|
||||
for (const trade of result.results) {
|
||||
await db.backtestResult.create({
|
||||
data: {
|
||||
sessionId: session.id,
|
||||
symbol: trade.symbol,
|
||||
action: trade.action,
|
||||
entryPrice: trade.entryPrice,
|
||||
exitPrice: trade.exitPrice,
|
||||
quantity: trade.quantity,
|
||||
pnl: trade.pnl,
|
||||
pnlPercent: trade.pnlPercent,
|
||||
executedAt: trade.executedAt,
|
||||
closedAt: trade.closedAt,
|
||||
notes: trade.notes
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Generate report
|
||||
const report = backtestEngine.generateReport(result);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
session: updatedSession,
|
||||
results: result,
|
||||
report
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error running backtest:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to run backtest' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
129
src/app/api/trading/demo/route.ts
Normal file
129
src/app/api/trading/demo/route.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Demo Trading API Routes for Mantle AI Trading Bot
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { demoTrader } from '@/lib/trading/demo/demo-trader';
|
||||
import { TradeAction, OrderType } from '@/lib/trading/core/types';
|
||||
|
||||
// GET /api/trading/demo/portfolio - Get portfolio
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action');
|
||||
|
||||
switch (action) {
|
||||
case 'portfolio':
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getPortfolio()
|
||||
});
|
||||
|
||||
case 'positions':
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getPositions()
|
||||
});
|
||||
|
||||
case 'orders':
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getOpenOrders()
|
||||
});
|
||||
|
||||
case 'history':
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getTradeHistory()
|
||||
});
|
||||
|
||||
case 'statistics':
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getStatistics()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
portfolio: demoTrader.getPortfolio(),
|
||||
positions: demoTrader.getPositions(),
|
||||
orders: demoTrader.getOpenOrders(),
|
||||
statistics: demoTrader.getStatistics()
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting demo data:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to get demo data' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/trading/demo - Execute demo trading actions
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, ...params } = body;
|
||||
|
||||
switch (action) {
|
||||
case 'place_order': {
|
||||
const order = demoTrader.placeOrder({
|
||||
symbol: params.symbol,
|
||||
side: params.side as TradeAction,
|
||||
type: params.type as OrderType,
|
||||
quantity: params.quantity,
|
||||
price: params.price,
|
||||
leverage: params.leverage,
|
||||
stopLoss: params.stopLoss,
|
||||
takeProfit: params.takeProfit
|
||||
});
|
||||
return NextResponse.json({ success: true, data: order });
|
||||
}
|
||||
|
||||
case 'close_position': {
|
||||
const order = demoTrader.closePosition(params.symbol, params.quantity);
|
||||
if (!order) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Position not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ success: true, data: order });
|
||||
}
|
||||
|
||||
case 'cancel_order': {
|
||||
const cancelled = demoTrader.cancelOrder(params.orderId);
|
||||
return NextResponse.json({ success: cancelled });
|
||||
}
|
||||
|
||||
case 'reset': {
|
||||
demoTrader.reset(params.initialCapital || 10000);
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: demoTrader.getPortfolio()
|
||||
});
|
||||
}
|
||||
|
||||
case 'update_price': {
|
||||
demoTrader.updatePrice(params.symbol, params.price);
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Invalid action' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error executing demo action:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: String(error) },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
82
src/app/api/trading/news/route.ts
Normal file
82
src/app/api/trading/news/route.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* News API Routes for Mantle AI Trading Bot
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { newsAggregator } from '@/lib/trading/news/news-aggregator';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/trading/news - Get news articles
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const symbol = searchParams.get('symbol');
|
||||
const source = searchParams.get('source');
|
||||
const limit = parseInt(searchParams.get('limit') || '50');
|
||||
|
||||
if (symbol) {
|
||||
const news = await newsAggregator.getNewsForSymbol(symbol, limit);
|
||||
return NextResponse.json({ success: true, data: news });
|
||||
}
|
||||
|
||||
const news = await newsAggregator.fetchAllNews({ limit });
|
||||
|
||||
// Save to database
|
||||
for (const article of news.slice(0, 20)) {
|
||||
try {
|
||||
await db.newsArticle.upsert({
|
||||
where: { sourceUrl: article.sourceUrl || `unknown-${Date.now()}` },
|
||||
update: {},
|
||||
create: {
|
||||
title: article.title,
|
||||
content: article.content || '',
|
||||
summary: article.summary,
|
||||
source: article.source,
|
||||
sourceUrl: article.sourceUrl || '',
|
||||
author: article.author,
|
||||
category: article.category,
|
||||
sentiment: article.sentiment,
|
||||
importance: article.importance,
|
||||
tags: article.tags || [],
|
||||
publishedAt: article.publishedAt,
|
||||
processed: article.processed
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
// Ignore duplicate errors
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, data: news });
|
||||
} catch (error) {
|
||||
console.error('Error fetching news:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to fetch news' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/trading/news/sentiment - Get sentiment for symbol
|
||||
export async function SENTIMENT(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const symbol = searchParams.get('symbol');
|
||||
|
||||
if (!symbol) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Symbol is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const sentiment = await newsAggregator.getSymbolSentiment(symbol);
|
||||
return NextResponse.json({ success: true, data: sentiment });
|
||||
} catch (error) {
|
||||
console.error('Error fetching sentiment:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to fetch sentiment' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
141
src/app/api/trading/signals/route.ts
Normal file
141
src/app/api/trading/signals/route.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Trading Signals API Routes for Mantle AI Trading Bot
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { signalEngine } from '@/lib/trading/signals/signal-engine';
|
||||
import { newsAggregator } from '@/lib/trading/news/news-aggregator';
|
||||
import { TimeFrame } from '@/lib/trading/core/types';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/trading/signals - Get signals
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const symbol = searchParams.get('symbol');
|
||||
const status = searchParams.get('status');
|
||||
const limit = parseInt(searchParams.get('limit') || '50');
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
if (symbol) where.symbol = symbol;
|
||||
if (status) where.status = status;
|
||||
|
||||
const signals = await db.signal.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: limit
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, data: signals });
|
||||
} catch (error) {
|
||||
console.error('Error fetching signals:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to fetch signals' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/trading/signals - Generate new signal
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { symbol, timeframe = '1h', demo = true } = body;
|
||||
|
||||
if (!symbol) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Symbol is required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Generate simulated market data (in production, fetch from Bybit)
|
||||
const marketData = generateDemoMarketData(symbol, 200);
|
||||
|
||||
// Fetch news for the symbol
|
||||
const news = await newsAggregator.getNewsForSymbol(symbol, 10);
|
||||
|
||||
// Generate signal
|
||||
const signalOutput = await signalEngine.generateSignal({
|
||||
symbol,
|
||||
timeframe: timeframe as TimeFrame,
|
||||
marketData,
|
||||
newsArticles: news
|
||||
});
|
||||
|
||||
// Save signal to database
|
||||
const savedSignal = await db.signal.create({
|
||||
data: {
|
||||
symbol: signalOutput.signal.symbol,
|
||||
action: signalOutput.signal.action,
|
||||
confidence: signalOutput.signal.confidence,
|
||||
rating: 0,
|
||||
priceTarget: signalOutput.signal.priceTarget,
|
||||
stopLoss: signalOutput.signal.stopLoss,
|
||||
takeProfit: signalOutput.signal.takeProfit,
|
||||
reasoning: signalOutput.signal.reasoning,
|
||||
newsSources: signalOutput.signal.newsSources || [],
|
||||
sentimentScore: signalOutput.signal.sentimentScore,
|
||||
technicalScore: signalOutput.signal.technicalScore,
|
||||
fundamentalScore: signalOutput.signal.fundamentalScore,
|
||||
status: 'PENDING',
|
||||
demo
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
signal: savedSignal,
|
||||
analysis: signalOutput.analysis,
|
||||
riskAssessment: signalOutput.riskAssessment
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error generating signal:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to generate signal' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to generate demo market data
|
||||
function generateDemoMarketData(symbol: string, count: number) {
|
||||
const prices: Record<string, number> = {
|
||||
BTCUSDT: 45000,
|
||||
ETHUSDT: 2500,
|
||||
SOLUSDT: 100,
|
||||
BNBUSDT: 300,
|
||||
XRPUSDT: 0.5
|
||||
};
|
||||
|
||||
const data = [];
|
||||
let price = prices[symbol] || 100;
|
||||
const now = Date.now();
|
||||
const hourMs = 60 * 60 * 1000;
|
||||
|
||||
for (let i = count; i >= 0; i--) {
|
||||
const change = (Math.random() - 0.5) * price * 0.02;
|
||||
const open = price;
|
||||
const close = price + change;
|
||||
const high = Math.max(open, close) + Math.random() * Math.abs(change) * 0.5;
|
||||
const low = Math.min(open, close) - Math.random() * Math.abs(change) * 0.5;
|
||||
const volume = 1000 + Math.random() * 5000;
|
||||
|
||||
data.push({
|
||||
symbol,
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
timestamp: new Date(now - i * hourMs),
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume
|
||||
});
|
||||
|
||||
price = close;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
122
src/app/globals.css
Normal file
122
src/app/globals.css
Normal file
@@ -0,0 +1,122 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
53
src/app/layout.tsx
Normal file
53
src/app/layout.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Z.ai Code Scaffold - AI-Powered Development",
|
||||
description: "Modern Next.js scaffold optimized for AI-powered development with Z.ai. Built with TypeScript, Tailwind CSS, and shadcn/ui.",
|
||||
keywords: ["Z.ai", "Next.js", "TypeScript", "Tailwind CSS", "shadcn/ui", "AI development", "React"],
|
||||
authors: [{ name: "Z.ai Team" }],
|
||||
icons: {
|
||||
icon: "https://z-cdn.chatglm.cn/z-ai/static/logo.svg",
|
||||
},
|
||||
openGraph: {
|
||||
title: "Z.ai Code Scaffold",
|
||||
description: "AI-powered development with modern React stack",
|
||||
url: "https://chat.z.ai",
|
||||
siteName: "Z.ai",
|
||||
type: "website",
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: "Z.ai Code Scaffold",
|
||||
description: "AI-powered development with modern React stack",
|
||||
},
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
|
||||
>
|
||||
{children}
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
714
src/app/page.tsx
Normal file
714
src/app/page.tsx
Normal file
@@ -0,0 +1,714 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
|
||||
AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell
|
||||
} from 'recharts';
|
||||
import {
|
||||
TrendingUp, TrendingDown, Activity, DollarSign, AlertTriangle,
|
||||
RefreshCw, Play, Square, BarChart3, Newspaper, Settings,
|
||||
Brain, Target, Shield, Zap, CheckCircle, XCircle, Clock
|
||||
} from 'lucide-react';
|
||||
|
||||
// Types
|
||||
interface Signal {
|
||||
id: string;
|
||||
symbol: string;
|
||||
action: 'BUY' | 'SELL' | 'HOLD';
|
||||
confidence: number;
|
||||
reasoning: string;
|
||||
priceTarget?: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
sentimentScore?: number;
|
||||
technicalScore?: number;
|
||||
fundamentalScore?: number;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface Position {
|
||||
id: string;
|
||||
symbol: string;
|
||||
side: 'LONG' | 'SHORT';
|
||||
quantity: number;
|
||||
avgEntryPrice: number;
|
||||
currentPrice: number;
|
||||
unrealizedPnL: number;
|
||||
unrealizedPnLPercent: number;
|
||||
}
|
||||
|
||||
interface Portfolio {
|
||||
totalValue: number;
|
||||
cashBalance: number;
|
||||
realizedPnL: number;
|
||||
unrealizedPnL: number;
|
||||
}
|
||||
|
||||
interface NewsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
source: string;
|
||||
sentiment?: number;
|
||||
publishedAt?: string;
|
||||
}
|
||||
|
||||
interface PriceUpdate {
|
||||
symbol: string;
|
||||
price: number;
|
||||
change: number;
|
||||
}
|
||||
|
||||
// Colors for charts
|
||||
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8'];
|
||||
|
||||
export default function TradingDashboard() {
|
||||
// State
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [portfolio, setPortfolio] = useState<Portfolio>({
|
||||
totalValue: 10000,
|
||||
cashBalance: 10000,
|
||||
realizedPnL: 0,
|
||||
unrealizedPnL: 0
|
||||
});
|
||||
const [positions, setPositions] = useState<Position[]>([]);
|
||||
const [signals, setSignals] = useState<Signal[]>([]);
|
||||
const [news, setNews] = useState<NewsItem[]>([]);
|
||||
const [prices, setPrices] = useState<Record<string, PriceUpdate>>({});
|
||||
const [selectedSymbol, setSelectedSymbol] = useState('BTCUSDT');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState('signals');
|
||||
|
||||
// Symbol options
|
||||
const symbols = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'];
|
||||
|
||||
// WebSocket connection
|
||||
useEffect(() => {
|
||||
const socket: Socket = io('/?XTransformPort=3003');
|
||||
|
||||
socket.on('connect', () => {
|
||||
setConnected(true);
|
||||
console.log('Connected to trading service');
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setConnected(false);
|
||||
console.log('Disconnected from trading service');
|
||||
});
|
||||
|
||||
socket.on('portfolio_update', (data: Portfolio) => {
|
||||
setPortfolio(data);
|
||||
});
|
||||
|
||||
socket.on('positions_update', (data: Position[]) => {
|
||||
setPositions(data);
|
||||
});
|
||||
|
||||
socket.on('price_updates', (data: PriceUpdate[]) => {
|
||||
const priceMap: Record<string, PriceUpdate> = {};
|
||||
data.forEach((p) => {
|
||||
priceMap[p.symbol] = p;
|
||||
});
|
||||
setPrices(priceMap);
|
||||
});
|
||||
|
||||
socket.on('signal_generated', (data: { signal: Signal; analysis: unknown }) => {
|
||||
setSignals((prev) => [data.signal, ...prev].slice(0, 50));
|
||||
});
|
||||
|
||||
socket.on('news_update', (data: NewsItem[]) => {
|
||||
setNews(data);
|
||||
});
|
||||
|
||||
// Fetch initial data
|
||||
fetchInitialData();
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const fetchInitialData = async () => {
|
||||
try {
|
||||
// Fetch news
|
||||
const newsRes = await fetch('/api/trading/news?limit=20');
|
||||
const newsData = await newsRes.json();
|
||||
if (newsData.success) {
|
||||
setNews(newsData.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching initial data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const generateSignal = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch('/api/trading/signals', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ symbol: selectedSymbol, timeframe: '1h', demo: true })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
setSignals((prev) => [data.data.signal, ...prev].slice(0, 50));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error generating signal:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [selectedSymbol]);
|
||||
|
||||
const placeDemoOrder = async (symbol: string, side: 'BUY' | 'SELL', quantity: number) => {
|
||||
try {
|
||||
await fetch('/api/trading/demo', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'place_order',
|
||||
symbol,
|
||||
side,
|
||||
type: 'MARKET',
|
||||
quantity
|
||||
})
|
||||
});
|
||||
// Refresh portfolio
|
||||
const res = await fetch('/api/trading/demo?action=portfolio');
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
setPortfolio(data.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error placing order:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const closePosition = async (symbol: string) => {
|
||||
try {
|
||||
await fetch('/api/trading/demo', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'close_position', symbol })
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error closing position:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const resetDemo = async () => {
|
||||
try {
|
||||
await fetch('/api/trading/demo', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'reset', initialCapital: 10000 })
|
||||
});
|
||||
setPositions([]);
|
||||
setSignals([]);
|
||||
} catch (error) {
|
||||
console.error('Error resetting demo:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Generate chart data for portfolio
|
||||
const portfolioChartData = [
|
||||
{ name: 'Cash', value: portfolio.cashBalance },
|
||||
{ name: 'Positions', value: portfolio.totalValue - portfolio.cashBalance }
|
||||
];
|
||||
|
||||
// Generate performance chart data
|
||||
const performanceData = Array.from({ length: 24 }, (_, i) => ({
|
||||
time: `${i}:00`,
|
||||
value: 10000 + Math.random() * 500 * (i / 24) * (Math.random() > 0.5 ? 1 : -1)
|
||||
}));
|
||||
|
||||
// Sentiment gauge data
|
||||
const sentimentValue = signals[0]?.sentimentScore || 0;
|
||||
const sentimentLabel = sentimentValue > 0.3 ? 'Bullish' : sentimentValue < -0.3 ? 'Bearish' : 'Neutral';
|
||||
const sentimentColor = sentimentValue > 0.3 ? 'text-green-500' : sentimentValue < -0.3 ? 'text-red-500' : 'text-yellow-500';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-4 md:p-6">
|
||||
<div className="max-w-7xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold flex items-center gap-2">
|
||||
<Brain className="h-8 w-8 text-primary" />
|
||||
Mantle AI Trader
|
||||
</h1>
|
||||
<p className="text-muted-foreground">Fundamental News-Based Trading Bot</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={connected ? 'default' : 'secondary'} className="flex items-center gap-1">
|
||||
<Activity className={`h-3 w-3 ${connected ? 'animate-pulse' : ''}`} />
|
||||
{connected ? 'Connected' : 'Disconnected'}
|
||||
</Badge>
|
||||
<Button variant="outline" size="sm" onClick={resetDemo}>
|
||||
<RefreshCw className="h-4 w-4 mr-1" />
|
||||
Reset Demo
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Portfolio Value</CardDescription>
|
||||
<CardTitle className="text-2xl flex items-center">
|
||||
<DollarSign className="h-5 w-5 text-green-500 mr-1" />
|
||||
${portfolio.totalValue.toLocaleString(undefined, { maximumFractionDigits: 2 })}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2">
|
||||
<Progress value={(portfolio.totalValue / 12000) * 100} className="h-2" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Realized P&L</CardDescription>
|
||||
<CardTitle className={`text-2xl ${portfolio.realizedPnL >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{portfolio.realizedPnL >= 0 ? '+' : ''}${portfolio.realizedPnL.toFixed(2)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Badge variant={portfolio.realizedPnL >= 0 ? 'default' : 'destructive'}>
|
||||
{portfolio.realizedPnL >= 0 ? <TrendingUp className="h-3 w-3 mr-1" /> : <TrendingDown className="h-3 w-3 mr-1" />}
|
||||
{((portfolio.realizedPnL / 10000) * 100).toFixed(2)}%
|
||||
</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Unrealized P&L</CardDescription>
|
||||
<CardTitle className={`text-2xl ${portfolio.unrealizedPnL >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{portfolio.unrealizedPnL >= 0 ? '+' : ''}${portfolio.unrealizedPnL.toFixed(2)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Badge variant="outline">Open Positions: {positions.length}</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Market Sentiment</CardDescription>
|
||||
<CardTitle className={`text-2xl ${sentimentColor}`}>
|
||||
{sentimentLabel}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Progress value={(sentimentValue + 1) * 50} className="h-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Price Ticker */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg">Live Prices</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{symbols.map((symbol) => {
|
||||
const priceData = prices[symbol];
|
||||
return (
|
||||
<div
|
||||
key={symbol}
|
||||
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
|
||||
selectedSymbol === symbol ? 'border-primary bg-primary/10' : 'hover:bg-muted'
|
||||
}`}
|
||||
onClick={() => setSelectedSymbol(symbol)}
|
||||
>
|
||||
<div className="font-semibold">{symbol.replace('USDT', '')}</div>
|
||||
<div className="text-lg font-mono">
|
||||
${priceData?.price?.toFixed(priceData?.price < 10 ? 4 : 2) || '---'}
|
||||
</div>
|
||||
<div className={`text-sm ${priceData?.change >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{priceData?.change >= 0 ? '+' : ''}{priceData?.change?.toFixed(2) || '0.00'}%
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Main Content Tabs */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className="grid grid-cols-4 w-full max-w-lg">
|
||||
<TabsTrigger value="signals">Signals</TabsTrigger>
|
||||
<TabsTrigger value="positions">Positions</TabsTrigger>
|
||||
<TabsTrigger value="backtest">Backtest</TabsTrigger>
|
||||
<TabsTrigger value="news">News</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Signals Tab */}
|
||||
<TabsContent value="signals" className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>AI Trading Signals</CardTitle>
|
||||
<CardDescription>AI-generated trading signals with analysis</CardDescription>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<select
|
||||
value={selectedSymbol}
|
||||
onChange={(e) => setSelectedSymbol(e.target.value)}
|
||||
className="px-3 py-2 rounded-md border bg-background"
|
||||
>
|
||||
{symbols.map((s) => (
|
||||
<option key={s} value={s}>{s}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button onClick={generateSignal} disabled={loading}>
|
||||
{loading ? (
|
||||
<RefreshCw className="h-4 w-4 animate-spin mr-1" />
|
||||
) : (
|
||||
<Brain className="h-4 w-4 mr-1" />
|
||||
)}
|
||||
Generate Signal
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ScrollArea className="h-[400px]">
|
||||
{signals.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground py-8">
|
||||
<Target className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No signals yet. Generate one to get started!</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{signals.map((signal) => (
|
||||
<Card key={signal.id} className="p-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge
|
||||
variant={signal.action === 'BUY' ? 'default' : signal.action === 'SELL' ? 'destructive' : 'secondary'}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
{signal.action === 'BUY' ? (
|
||||
<TrendingUp className="h-4 w-4 mr-1" />
|
||||
) : signal.action === 'SELL' ? (
|
||||
<TrendingDown className="h-4 w-4 mr-1" />
|
||||
) : null}
|
||||
{signal.action}
|
||||
</Badge>
|
||||
<div>
|
||||
<div className="font-semibold">{signal.symbol}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Confidence: {(signal.confidence * 100).toFixed(0)}%
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{new Date(signal.createdAt).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-3" />
|
||||
|
||||
<p className="text-sm mb-3">{signal.reasoning}</p>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Technical:</span>
|
||||
<Progress value={(signal.technicalScore || 0) * 100} className="h-2 mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Sentiment:</span>
|
||||
<Progress value={((signal.sentimentScore || 0) + 1) * 50} className="h-2 mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Fundamental:</span>
|
||||
<Progress value={(signal.fundamentalScore || 0) * 100} className="h-2 mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{signal.action !== 'HOLD' && (
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={() => placeDemoOrder(signal.symbol, signal.action, 0.01)}
|
||||
>
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Execute
|
||||
</Button>
|
||||
<Button size="sm" variant="outline">
|
||||
<Shield className="h-3 w-3 mr-1" />
|
||||
Set Alerts
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Positions Tab */}
|
||||
<TabsContent value="positions" className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Portfolio Allocation</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={portfolioChartData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={60}
|
||||
outerRadius={80}
|
||||
fill="#8884d8"
|
||||
paddingAngle={5}
|
||||
dataKey="value"
|
||||
>
|
||||
{portfolioChartData.map((_, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="flex justify-center gap-4 mt-2">
|
||||
<Badge variant="outline">Cash: ${portfolio.cashBalance.toFixed(2)}</Badge>
|
||||
<Badge variant="outline">Positions: ${(portfolio.totalValue - portfolio.cashBalance).toFixed(2)}</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Performance</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<AreaChart data={performanceData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="time" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Area type="monotone" dataKey="value" stroke="#8884d8" fill="#8884d8" fillOpacity={0.3} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Open Positions</CardTitle>
|
||||
<CardDescription>Current trading positions</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{positions.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground py-8">
|
||||
<Activity className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No open positions</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{positions.map((position) => (
|
||||
<div key={position.id} className="flex items-center justify-between p-3 rounded-lg border">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant={position.side === 'LONG' ? 'default' : 'secondary'}>
|
||||
{position.side}
|
||||
</Badge>
|
||||
<div>
|
||||
<div className="font-semibold">{position.symbol}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Qty: {position.quantity} @ ${position.avgEntryPrice.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className={position.unrealizedPnL >= 0 ? 'text-green-500' : 'text-red-500'}>
|
||||
{position.unrealizedPnL >= 0 ? '+' : ''}${position.unrealizedPnL.toFixed(2)}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{position.unrealizedPnLPercent >= 0 ? '+' : ''}{position.unrealizedPnLPercent.toFixed(2)}%
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
onClick={() => closePosition(position.symbol)}
|
||||
>
|
||||
<Square className="h-3 w-3 mr-1" />
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Backtest Tab */}
|
||||
<TabsContent value="backtest" className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Backtesting Engine</CardTitle>
|
||||
<CardDescription>Test strategies on historical data</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Symbol</label>
|
||||
<select className="w-full mt-1 px-3 py-2 rounded-md border bg-background">
|
||||
{symbols.map((s) => (
|
||||
<option key={s} value={s}>{s}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Start Date</label>
|
||||
<Input type="date" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">End Date</label>
|
||||
<Input type="date" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Initial Capital</label>
|
||||
<Input type="number" defaultValue={10000} className="mt-1" />
|
||||
</div>
|
||||
<Button className="w-full">
|
||||
<BarChart3 className="h-4 w-4 mr-2" />
|
||||
Run Backtest
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Card className="p-4 bg-muted/50">
|
||||
<h3 className="font-semibold mb-2">Expected Metrics</h3>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>Total Return:</span>
|
||||
<span className="font-mono">--</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Win Rate:</span>
|
||||
<span className="font-mono">--</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Sharpe Ratio:</span>
|
||||
<span className="font-mono">--</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Max Drawdown:</span>
|
||||
<span className="font-mono">--</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
<Alert>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Info</AlertTitle>
|
||||
<AlertDescription>
|
||||
Backtesting uses simulated data. Connect to Bybit API for real historical data.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* News Tab */}
|
||||
<TabsContent value="news" className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Market News</CardTitle>
|
||||
<CardDescription>Latest news and sentiment analysis</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={fetchInitialData}>
|
||||
<RefreshCw className="h-4 w-4 mr-1" />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ScrollArea className="h-[500px]">
|
||||
{news.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground py-8">
|
||||
<Newspaper className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No news available</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{news.map((item) => (
|
||||
<div key={item.id} className="p-3 rounded-lg border hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1">
|
||||
<h3 className="font-medium text-sm">{item.title}</h3>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{item.source}
|
||||
</Badge>
|
||||
{item.sentiment !== undefined && (
|
||||
<Badge
|
||||
variant={item.sentiment > 0.2 ? 'default' : item.sentiment < -0.2 ? 'destructive' : 'secondary'}
|
||||
className="text-xs"
|
||||
>
|
||||
{item.sentiment > 0.2 ? 'Bullish' : item.sentiment < -0.2 ? 'Bearish' : 'Neutral'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{item.publishedAt && (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{new Date(item.publishedAt).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="text-center text-sm text-muted-foreground py-4">
|
||||
<p>Mantle AI Trader - Fundamental News-Based Trading Bot</p>
|
||||
<p className="mt-1">Built for Mantle Turing Test Hackathon</p>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
66
src/components/ui/accordion.tsx
Normal file
66
src/components/ui/accordion.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Accordion({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
)
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
157
src/components/ui/alert-dialog.tsx
Normal file
157
src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Action
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
66
src/components/ui/alert.tsx
Normal file
66
src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const alertVariants = cva(
|
||||
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive:
|
||||
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Alert({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert"
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
11
src/components/ui/aspect-ratio.tsx
Normal file
11
src/components/ui/aspect-ratio.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||
|
||||
function AspectRatio({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||
}
|
||||
|
||||
export { AspectRatio }
|
||||
53
src/components/ui/avatar.tsx
Normal file
53
src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback }
|
||||
46
src/components/ui/badge.tsx
Normal file
46
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
109
src/components/ui/breadcrumb.tsx
Normal file
109
src/components/ui/breadcrumb.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-item"
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
asChild,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="breadcrumb-link"
|
||||
className={cn("hover:text-foreground transition-colors", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("text-foreground font-normal", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-separator"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:size-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
59
src/components/ui/button.tsx
Normal file
59
src/components/ui/button.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
213
src/components/ui/calendar.tsx
Normal file
213
src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"flex gap-4 flex-col md:flex-row relative",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"select-none w-(--cell-size)",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] select-none text-muted-foreground",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
92
src/components/ui/card.tsx
Normal file
92
src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
241
src/components/ui/carousel.tsx
Normal file
241
src/components/ui/carousel.tsx
Normal file
@@ -0,0 +1,241 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Carousel({
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) return
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) return
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
data-slot="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={carouselRef}
|
||||
className="overflow-hidden"
|
||||
data-slot="carousel-content"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
data-slot="carousel-item"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselPrevious({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-previous"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -left-12 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselNext({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-next"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -right-12 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
353
src/components/ui/chart.tsx
Normal file
353
src/components/ui/chart.tsx
Normal file
@@ -0,0 +1,353 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RechartsPrimitive from "recharts"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: "", dark: ".dark" } as const
|
||||
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: React.ReactNode
|
||||
icon?: React.ComponentType
|
||||
} & (
|
||||
| { color?: string; theme?: never }
|
||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||
)
|
||||
}
|
||||
|
||||
type ChartContextProps = {
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||
|
||||
function useChart() {
|
||||
const context = React.useContext(ChartContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useChart must be used within a <ChartContainer />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function ChartContainer({
|
||||
id,
|
||||
className,
|
||||
children,
|
||||
config,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
config: ChartConfig
|
||||
children: React.ComponentProps<
|
||||
typeof RechartsPrimitive.ResponsiveContainer
|
||||
>["children"]
|
||||
}) {
|
||||
const uniqueId = React.useId()
|
||||
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
|
||||
|
||||
return (
|
||||
<ChartContext.Provider value={{ config }}>
|
||||
<div
|
||||
data-slot="chart"
|
||||
data-chart={chartId}
|
||||
className={cn(
|
||||
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
</ChartContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
const colorConfig = Object.entries(config).filter(
|
||||
([, config]) => config.theme || config.color
|
||||
)
|
||||
|
||||
if (!colorConfig.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: Object.entries(THEMES)
|
||||
.map(
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join("\n")}
|
||||
}
|
||||
`
|
||||
)
|
||||
.join("\n"),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||
|
||||
function ChartTooltipContent({
|
||||
active,
|
||||
payload,
|
||||
className,
|
||||
indicator = "dot",
|
||||
hideLabel = false,
|
||||
hideIndicator = false,
|
||||
label,
|
||||
labelFormatter,
|
||||
labelClassName,
|
||||
formatter,
|
||||
color,
|
||||
nameKey,
|
||||
labelKey,
|
||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||
React.ComponentProps<"div"> & {
|
||||
hideLabel?: boolean
|
||||
hideIndicator?: boolean
|
||||
indicator?: "line" | "dot" | "dashed"
|
||||
nameKey?: string
|
||||
labelKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [item] = payload
|
||||
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const value =
|
||||
!labelKey && typeof label === "string"
|
||||
? config[label as keyof typeof config]?.label || label
|
||||
: itemConfig?.label
|
||||
|
||||
if (labelFormatter) {
|
||||
return (
|
||||
<div className={cn("font-medium", labelClassName)}>
|
||||
{labelFormatter(value, payload)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
||||
}, [
|
||||
label,
|
||||
labelFormatter,
|
||||
payload,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
config,
|
||||
labelKey,
|
||||
])
|
||||
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nestLabel = payload.length === 1 && indicator !== "dot"
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{!nestLabel ? tooltipLabel : null}
|
||||
<div className="grid gap-1.5">
|
||||
{payload.map((item, index) => {
|
||||
const key = `${nameKey || item.name || item.dataKey || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const indicatorColor = color || item.payload.fill || item.color
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.dataKey}
|
||||
className={cn(
|
||||
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
|
||||
indicator === "dot" && "items-center"
|
||||
)}
|
||||
>
|
||||
{formatter && item?.value !== undefined && item.name ? (
|
||||
formatter(item.value, item.name, item, index, item.payload)
|
||||
) : (
|
||||
<>
|
||||
{itemConfig?.icon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
!hideIndicator && (
|
||||
<div
|
||||
className={cn(
|
||||
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
||||
{
|
||||
"h-2.5 w-2.5": indicator === "dot",
|
||||
"w-1": indicator === "line",
|
||||
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||
indicator === "dashed",
|
||||
"my-0.5": nestLabel && indicator === "dashed",
|
||||
}
|
||||
)}
|
||||
style={
|
||||
{
|
||||
"--color-bg": indicatorColor,
|
||||
"--color-border": indicatorColor,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-1 justify-between leading-none",
|
||||
nestLabel ? "items-end" : "items-center"
|
||||
)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
{nestLabel ? tooltipLabel : null}
|
||||
<span className="text-muted-foreground">
|
||||
{itemConfig?.label || item.name}
|
||||
</span>
|
||||
</div>
|
||||
{item.value && (
|
||||
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||
{item.value.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartLegend = RechartsPrimitive.Legend
|
||||
|
||||
function ChartLegendContent({
|
||||
className,
|
||||
hideIcon = false,
|
||||
payload,
|
||||
verticalAlign = "bottom",
|
||||
nameKey,
|
||||
}: React.ComponentProps<"div"> &
|
||||
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
|
||||
hideIcon?: boolean
|
||||
nameKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
if (!payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-4",
|
||||
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{payload.map((item) => {
|
||||
const key = `${nameKey || item.dataKey || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.value}
|
||||
className={cn(
|
||||
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
|
||||
)}
|
||||
>
|
||||
{itemConfig?.icon && !hideIcon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
<div
|
||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||
style={{
|
||||
backgroundColor: item.color,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{itemConfig?.label}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to extract item config from a payload.
|
||||
function getPayloadConfigFromPayload(
|
||||
config: ChartConfig,
|
||||
payload: unknown,
|
||||
key: string
|
||||
) {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadPayload =
|
||||
"payload" in payload &&
|
||||
typeof payload.payload === "object" &&
|
||||
payload.payload !== null
|
||||
? payload.payload
|
||||
: undefined
|
||||
|
||||
let configLabelKey: string = key
|
||||
|
||||
if (
|
||||
key in payload &&
|
||||
typeof payload[key as keyof typeof payload] === "string"
|
||||
) {
|
||||
configLabelKey = payload[key as keyof typeof payload] as string
|
||||
} else if (
|
||||
payloadPayload &&
|
||||
key in payloadPayload &&
|
||||
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||
) {
|
||||
configLabelKey = payloadPayload[
|
||||
key as keyof typeof payloadPayload
|
||||
] as string
|
||||
}
|
||||
|
||||
return configLabelKey in config
|
||||
? config[configLabelKey]
|
||||
: config[key as keyof typeof config]
|
||||
}
|
||||
|
||||
export {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartStyle,
|
||||
}
|
||||
32
src/components/ui/checkbox.tsx
Normal file
32
src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
33
src/components/ui/collapsible.tsx
Normal file
33
src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
184
src/components/ui/command.tsx
Normal file
184
src/components/ui/command.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
252
src/components/ui/context-menu.tsx
Normal file
252
src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,252 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
143
src/components/ui/dialog.tsx
Normal file
143
src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
135
src/components/ui/drawer.tsx
Normal file
135
src/components/ui/drawer.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Drawer({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||
}
|
||||
|
||||
function DrawerTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DrawerPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||
}
|
||||
|
||||
function DrawerClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||
return (
|
||||
<DrawerPrimitive.Overlay
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal">
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||
return (
|
||||
<DrawerPrimitive.Title
|
||||
data-slot="drawer-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||
return (
|
||||
<DrawerPrimitive.Description
|
||||
data-slot="drawer-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
257
src/components/ui/dropdown-menu.tsx
Normal file
257
src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,257 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
167
src/components/ui/form.tsx
Normal file
167
src/components/ui/form.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
44
src/components/ui/hover-card.tsx
Normal file
44
src/components/ui/hover-card.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function HoverCard({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||
}
|
||||
|
||||
function HoverCardTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function HoverCardContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
|
||||
<HoverCardPrimitive.Content
|
||||
data-slot="hover-card-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</HoverCardPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||
77
src/components/ui/input-otp.tsx
Normal file
77
src/components/ui/input-otp.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { OTPInput, OTPInputContext } from "input-otp"
|
||||
import { MinusIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function InputOTP({
|
||||
className,
|
||||
containerClassName,
|
||||
...props
|
||||
}: React.ComponentProps<typeof OTPInput> & {
|
||||
containerClassName?: string
|
||||
}) {
|
||||
return (
|
||||
<OTPInput
|
||||
data-slot="input-otp"
|
||||
containerClassName={cn(
|
||||
"flex items-center gap-2 has-disabled:opacity-50",
|
||||
containerClassName
|
||||
)}
|
||||
className={cn("disabled:cursor-not-allowed", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-group"
|
||||
className={cn("flex items-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSlot({
|
||||
index,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
index: number
|
||||
}) {
|
||||
const inputOTPContext = React.useContext(OTPInputContext)
|
||||
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-slot"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{char}
|
||||
{hasFakeCaret && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||
<MinusIcon />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
|
||||
21
src/components/ui/input.tsx
Normal file
21
src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
24
src/components/ui/label.tsx
Normal file
24
src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
276
src/components/ui/menubar.tsx
Normal file
276
src/components/ui/menubar.tsx
Normal file
@@ -0,0 +1,276 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as MenubarPrimitive from "@radix-ui/react-menubar"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Menubar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||
return (
|
||||
<MenubarPrimitive.Root
|
||||
data-slot="menubar"
|
||||
className={cn(
|
||||
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
|
||||
}
|
||||
|
||||
function MenubarGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
|
||||
}
|
||||
|
||||
function MenubarPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
|
||||
}
|
||||
|
||||
function MenubarRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||
return (
|
||||
<MenubarPrimitive.Trigger
|
||||
data-slot="menubar-trigger"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarContent({
|
||||
className,
|
||||
align = "start",
|
||||
alignOffset = -4,
|
||||
sideOffset = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||
return (
|
||||
<MenubarPortal>
|
||||
<MenubarPrimitive.Content
|
||||
data-slot="menubar-content"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</MenubarPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Item
|
||||
data-slot="menubar-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.CheckboxItem
|
||||
data-slot="menubar-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioItem
|
||||
data-slot="menubar-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Label
|
||||
data-slot="menubar-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||
return (
|
||||
<MenubarPrimitive.Separator
|
||||
data-slot="menubar-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="menubar-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
|
||||
}
|
||||
|
||||
function MenubarSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.SubTrigger
|
||||
data-slot="menubar-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||
</MenubarPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||
return (
|
||||
<MenubarPrimitive.SubContent
|
||||
data-slot="menubar-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Menubar,
|
||||
MenubarPortal,
|
||||
MenubarMenu,
|
||||
MenubarTrigger,
|
||||
MenubarContent,
|
||||
MenubarGroup,
|
||||
MenubarSeparator,
|
||||
MenubarLabel,
|
||||
MenubarItem,
|
||||
MenubarShortcut,
|
||||
MenubarCheckboxItem,
|
||||
MenubarRadioGroup,
|
||||
MenubarRadioItem,
|
||||
MenubarSub,
|
||||
MenubarSubTrigger,
|
||||
MenubarSubContent,
|
||||
}
|
||||
168
src/components/ui/navigation-menu.tsx
Normal file
168
src/components/ui/navigation-menu.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import * as React from "react"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function NavigationMenu({
|
||||
className,
|
||||
children,
|
||||
viewport = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||
viewport?: boolean
|
||||
}) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Root
|
||||
data-slot="navigation-menu"
|
||||
data-viewport={viewport}
|
||||
className={cn(
|
||||
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{viewport && <NavigationMenuViewport />}
|
||||
</NavigationMenuPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.List
|
||||
data-slot="navigation-menu-list"
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Item
|
||||
data-slot="navigation-menu-item"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
)
|
||||
|
||||
function NavigationMenuTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
data-slot="navigation-menu-trigger"
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDownIcon
|
||||
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Content
|
||||
data-slot="navigation-menu-content"
|
||||
className={cn(
|
||||
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuViewport({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||
)}
|
||||
>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
data-slot="navigation-menu-viewport"
|
||||
className={cn(
|
||||
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuLink({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Link
|
||||
data-slot="navigation-menu-link"
|
||||
className={cn(
|
||||
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuIndicator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
data-slot="navigation-menu-indicator"
|
||||
className={cn(
|
||||
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
navigationMenuTriggerStyle,
|
||||
}
|
||||
127
src/components/ui/pagination.tsx
Normal file
127
src/components/ui/pagination.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
MoreHorizontalIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
|
||||
return (
|
||||
<nav
|
||||
role="navigation"
|
||||
aria-label="pagination"
|
||||
data-slot="pagination"
|
||||
className={cn("mx-auto flex w-full justify-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="pagination-content"
|
||||
className={cn("flex flex-row items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
|
||||
return <li data-slot="pagination-item" {...props} />
|
||||
}
|
||||
|
||||
type PaginationLinkProps = {
|
||||
isActive?: boolean
|
||||
} & Pick<React.ComponentProps<typeof Button>, "size"> &
|
||||
React.ComponentProps<"a">
|
||||
|
||||
function PaginationLink({
|
||||
className,
|
||||
isActive,
|
||||
size = "icon",
|
||||
...props
|
||||
}: PaginationLinkProps) {
|
||||
return (
|
||||
<a
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
data-slot="pagination-link"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
buttonVariants({
|
||||
variant: isActive ? "outline" : "ghost",
|
||||
size,
|
||||
}),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationPrevious({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to previous page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
<span className="hidden sm:block">Previous</span>
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationNext({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to next page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="hidden sm:block">Next</span>
|
||||
<ChevronRightIcon />
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
data-slot="pagination-ellipsis"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-4" />
|
||||
<span className="sr-only">More pages</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationLink,
|
||||
PaginationItem,
|
||||
PaginationPrevious,
|
||||
PaginationNext,
|
||||
PaginationEllipsis,
|
||||
}
|
||||
48
src/components/ui/popover.tsx
Normal file
48
src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
31
src/components/ui/progress.tsx
Normal file
31
src/components/ui/progress.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
45
src/components/ui/radio-group.tsx
Normal file
45
src/components/ui/radio-group.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
|
||||
import { CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator
|
||||
data-slot="radio-group-indicator"
|
||||
className="relative flex items-center justify-center"
|
||||
>
|
||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem }
|
||||
56
src/components/ui/resizable.tsx
Normal file
56
src/components/ui/resizable.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) {
|
||||
return (
|
||||
<ResizablePrimitive.PanelGroup
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ResizablePanel({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
withHandle,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
|
||||
withHandle?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.PanelResizeHandle
|
||||
data-slot="resizable-handle"
|
||||
className={cn(
|
||||
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{withHandle && (
|
||||
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
|
||||
<GripVerticalIcon className="size-2.5" />
|
||||
</div>
|
||||
)}
|
||||
</ResizablePrimitive.PanelResizeHandle>
|
||||
)
|
||||
}
|
||||
|
||||
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
|
||||
58
src/components/ui/scroll-area.tsx
Normal file
58
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
185
src/components/ui/select.tsx
Normal file
185
src/components/ui/select.tsx
Normal file
@@ -0,0 +1,185 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
28
src/components/ui/separator.tsx
Normal file
28
src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
139
src/components/ui/sheet.tsx
Normal file
139
src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
726
src/components/ui/sidebar.tsx
Normal file
726
src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,726 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
13
src/components/ui/skeleton.tsx
Normal file
13
src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
63
src/components/ui/slider.tsx
Normal file
63
src/components/ui/slider.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SliderPrimitive from "@radix-ui/react-slider"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Slider({
|
||||
className,
|
||||
defaultValue,
|
||||
value,
|
||||
min = 0,
|
||||
max = 100,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
|
||||
const _values = React.useMemo(
|
||||
() =>
|
||||
Array.isArray(value)
|
||||
? value
|
||||
: Array.isArray(defaultValue)
|
||||
? defaultValue
|
||||
: [min, max],
|
||||
[value, defaultValue, min, max]
|
||||
)
|
||||
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
data-slot="slider"
|
||||
defaultValue={defaultValue}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
className={cn(
|
||||
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track
|
||||
data-slot="slider-track"
|
||||
className={cn(
|
||||
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
|
||||
)}
|
||||
>
|
||||
<SliderPrimitive.Range
|
||||
data-slot="slider-range"
|
||||
className={cn(
|
||||
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
|
||||
)}
|
||||
/>
|
||||
</SliderPrimitive.Track>
|
||||
{Array.from({ length: _values.length }, (_, index) => (
|
||||
<SliderPrimitive.Thumb
|
||||
data-slot="slider-thumb"
|
||||
key={index}
|
||||
className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
|
||||
/>
|
||||
))}
|
||||
</SliderPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Slider }
|
||||
25
src/components/ui/sonner.tsx
Normal file
25
src/components/ui/sonner.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
31
src/components/ui/switch.tsx
Normal file
31
src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
116
src/components/ui/table.tsx
Normal file
116
src/components/ui/table.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
66
src/components/ui/tabs.tsx
Normal file
66
src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
18
src/components/ui/textarea.tsx
Normal file
18
src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
129
src/components/ui/toast.tsx
Normal file
129
src/components/ui/toast.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
|
||||
const toastVariants = cva(
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border bg-background text-foreground",
|
||||
destructive:
|
||||
"destructive group border-destructive bg-destructive text-destructive-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
||||
VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root
|
||||
ref={ref}
|
||||
className={cn(toastVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
|
||||
className
|
||||
)}
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title
|
||||
ref={ref}
|
||||
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm opacity-90", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
|
||||
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
|
||||
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
|
||||
export {
|
||||
type ToastProps,
|
||||
type ToastActionElement,
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
}
|
||||
35
src/components/ui/toaster.tsx
Normal file
35
src/components/ui/toaster.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client"
|
||||
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import {
|
||||
Toast,
|
||||
ToastClose,
|
||||
ToastDescription,
|
||||
ToastProvider,
|
||||
ToastTitle,
|
||||
ToastViewport,
|
||||
} from "@/components/ui/toast"
|
||||
|
||||
export function Toaster() {
|
||||
const { toasts } = useToast()
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
{toasts.map(function ({ id, title, description, action, ...props }) {
|
||||
return (
|
||||
<Toast key={id} {...props}>
|
||||
<div className="grid gap-1">
|
||||
{title && <ToastTitle>{title}</ToastTitle>}
|
||||
{description && (
|
||||
<ToastDescription>{description}</ToastDescription>
|
||||
)}
|
||||
</div>
|
||||
{action}
|
||||
<ToastClose />
|
||||
</Toast>
|
||||
)
|
||||
})}
|
||||
<ToastViewport />
|
||||
</ToastProvider>
|
||||
)
|
||||
}
|
||||
73
src/components/ui/toggle-group.tsx
Normal file
73
src/components/ui/toggle-group.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants>
|
||||
>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
})
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive.Root
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ variant, size }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext)
|
||||
|
||||
return (
|
||||
<ToggleGroupPrimitive.Item
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
className={cn(
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem }
|
||||
47
src/components/ui/toggle.tsx
Normal file
47
src/components/ui/toggle.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TogglePrimitive from "@radix-ui/react-toggle"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-2 min-w-9",
|
||||
sm: "h-8 px-1.5 min-w-8",
|
||||
lg: "h-10 px-2.5 min-w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive.Root
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
61
src/components/ui/tooltip.tsx
Normal file
61
src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
19
src/hooks/use-mobile.ts
Normal file
19
src/hooks/use-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
194
src/hooks/use-toast.ts
Normal file
194
src/hooks/use-toast.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
"use client"
|
||||
|
||||
// Inspired by react-hot-toast library
|
||||
import * as React from "react"
|
||||
|
||||
import type {
|
||||
ToastActionElement,
|
||||
ToastProps,
|
||||
} from "@/components/ui/toast"
|
||||
|
||||
const TOAST_LIMIT = 1
|
||||
const TOAST_REMOVE_DELAY = 1000000
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
}
|
||||
|
||||
const actionTypes = {
|
||||
ADD_TOAST: "ADD_TOAST",
|
||||
UPDATE_TOAST: "UPDATE_TOAST",
|
||||
DISMISS_TOAST: "DISMISS_TOAST",
|
||||
REMOVE_TOAST: "REMOVE_TOAST",
|
||||
} as const
|
||||
|
||||
let count = 0
|
||||
|
||||
function genId() {
|
||||
count = (count + 1) % Number.MAX_SAFE_INTEGER
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
type ActionType = typeof actionTypes
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: ActionType["ADD_TOAST"]
|
||||
toast: ToasterToast
|
||||
}
|
||||
| {
|
||||
type: ActionType["UPDATE_TOAST"]
|
||||
toast: Partial<ToasterToast>
|
||||
}
|
||||
| {
|
||||
type: ActionType["DISMISS_TOAST"]
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
| {
|
||||
type: ActionType["REMOVE_TOAST"]
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
|
||||
interface State {
|
||||
toasts: ToasterToast[]
|
||||
}
|
||||
|
||||
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
const addToRemoveQueue = (toastId: string) => {
|
||||
if (toastTimeouts.has(toastId)) {
|
||||
return
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
toastTimeouts.delete(toastId)
|
||||
dispatch({
|
||||
type: "REMOVE_TOAST",
|
||||
toastId: toastId,
|
||||
})
|
||||
}, TOAST_REMOVE_DELAY)
|
||||
|
||||
toastTimeouts.set(toastId, timeout)
|
||||
}
|
||||
|
||||
export const reducer = (state: State, action: Action): State => {
|
||||
switch (action.type) {
|
||||
case "ADD_TOAST":
|
||||
return {
|
||||
...state,
|
||||
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
|
||||
}
|
||||
|
||||
case "UPDATE_TOAST":
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((t) =>
|
||||
t.id === action.toast.id ? { ...t, ...action.toast } : t
|
||||
),
|
||||
}
|
||||
|
||||
case "DISMISS_TOAST": {
|
||||
const { toastId } = action
|
||||
|
||||
// ! Side effects ! - This could be extracted into a dismissToast() action,
|
||||
// but I'll keep it here for simplicity
|
||||
if (toastId) {
|
||||
addToRemoveQueue(toastId)
|
||||
} else {
|
||||
state.toasts.forEach((toast) => {
|
||||
addToRemoveQueue(toast.id)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((t) =>
|
||||
t.id === toastId || toastId === undefined
|
||||
? {
|
||||
...t,
|
||||
open: false,
|
||||
}
|
||||
: t
|
||||
),
|
||||
}
|
||||
}
|
||||
case "REMOVE_TOAST":
|
||||
if (action.toastId === undefined) {
|
||||
return {
|
||||
...state,
|
||||
toasts: [],
|
||||
}
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.filter((t) => t.id !== action.toastId),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const listeners: Array<(state: State) => void> = []
|
||||
|
||||
let memoryState: State = { toasts: [] }
|
||||
|
||||
function dispatch(action: Action) {
|
||||
memoryState = reducer(memoryState, action)
|
||||
listeners.forEach((listener) => {
|
||||
listener(memoryState)
|
||||
})
|
||||
}
|
||||
|
||||
type Toast = Omit<ToasterToast, "id">
|
||||
|
||||
function toast({ ...props }: Toast) {
|
||||
const id = genId()
|
||||
|
||||
const update = (props: ToasterToast) =>
|
||||
dispatch({
|
||||
type: "UPDATE_TOAST",
|
||||
toast: { ...props, id },
|
||||
})
|
||||
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
|
||||
|
||||
dispatch({
|
||||
type: "ADD_TOAST",
|
||||
toast: {
|
||||
...props,
|
||||
id,
|
||||
open: true,
|
||||
onOpenChange: (open) => {
|
||||
if (!open) dismiss()
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
id: id,
|
||||
dismiss,
|
||||
update,
|
||||
}
|
||||
}
|
||||
|
||||
function useToast() {
|
||||
const [state, setState] = React.useState<State>(memoryState)
|
||||
|
||||
React.useEffect(() => {
|
||||
listeners.push(setState)
|
||||
return () => {
|
||||
const index = listeners.indexOf(setState)
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}, [state])
|
||||
|
||||
return {
|
||||
...state,
|
||||
toast,
|
||||
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
|
||||
}
|
||||
}
|
||||
|
||||
export { useToast, toast }
|
||||
13
src/lib/db.ts
Normal file
13
src/lib/db.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
export const db =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
log: ['query'],
|
||||
})
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db
|
||||
466
src/lib/trading/backtest/backtest-engine.ts
Normal file
466
src/lib/trading/backtest/backtest-engine.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
/**
|
||||
* Backtesting Engine for Mantle AI Trading Bot
|
||||
* Simulates trading strategies on historical data
|
||||
*/
|
||||
|
||||
import {
|
||||
BacktestConfig,
|
||||
BacktestResult,
|
||||
BacktestSession,
|
||||
PerformanceMetrics,
|
||||
Signal,
|
||||
TradeAction,
|
||||
OrderType,
|
||||
MarketDataPoint,
|
||||
TimeFrame
|
||||
} from '../core/types';
|
||||
import { signalEngine } from '../signals/signal-engine';
|
||||
|
||||
export class BacktestEngine {
|
||||
private trades: BacktestResult[] = [];
|
||||
private equityCurve: number[] = [];
|
||||
private currentCapital: number = 0;
|
||||
|
||||
/**
|
||||
* Run a backtest session
|
||||
*/
|
||||
async runBacktest(config: BacktestConfig): Promise<BacktestSession> {
|
||||
const session: BacktestSession = {
|
||||
id: `backtest-${Date.now()}`,
|
||||
name: config.name,
|
||||
symbol: config.symbol,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
totalTrades: 0,
|
||||
status: 'RUNNING',
|
||||
results: []
|
||||
};
|
||||
|
||||
this.trades = [];
|
||||
this.equityCurve = [];
|
||||
this.currentCapital = config.initialCapital;
|
||||
|
||||
try {
|
||||
// Generate simulated historical data (in production, fetch from API)
|
||||
const historicalData = await this.generateHistoricalData(
|
||||
config.symbol,
|
||||
config.startDate,
|
||||
config.endDate
|
||||
);
|
||||
|
||||
// Process each data point
|
||||
for (let i = 50; i < historicalData.length; i++) {
|
||||
const windowData = historicalData.slice(0, i);
|
||||
const currentPrice = historicalData[i].close;
|
||||
|
||||
// Generate signal
|
||||
const signalOutput = await signalEngine.generateSignal({
|
||||
symbol: config.symbol,
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
marketData: windowData,
|
||||
newsArticles: []
|
||||
});
|
||||
|
||||
// Check if we should trade
|
||||
if (signalOutput.signal.action !== TradeAction.HOLD) {
|
||||
await this.processSignal(
|
||||
signalOutput.signal,
|
||||
currentPrice,
|
||||
config,
|
||||
historicalData.slice(i)
|
||||
);
|
||||
}
|
||||
|
||||
// Update equity curve
|
||||
this.equityCurve.push(this.currentCapital);
|
||||
}
|
||||
|
||||
// Calculate final metrics
|
||||
const metrics = this.calculatePerformanceMetrics(
|
||||
config.initialCapital,
|
||||
this.currentCapital
|
||||
);
|
||||
|
||||
// Update session with results
|
||||
session.status = 'COMPLETED';
|
||||
session.finalCapital = this.currentCapital;
|
||||
session.totalTrades = this.trades.length;
|
||||
session.winRate = metrics.winRate;
|
||||
session.maxDrawdown = metrics.maxDrawdown;
|
||||
session.sharpeRatio = metrics.sharpeRatio;
|
||||
session.results = this.trades;
|
||||
|
||||
return session;
|
||||
} catch (error) {
|
||||
session.status = 'FAILED';
|
||||
console.error('Backtest failed:', error);
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a trading signal in backtest
|
||||
*/
|
||||
private async processSignal(
|
||||
signal: Omit<Signal, 'id' | 'createdAt' | 'updatedAt'>,
|
||||
currentPrice: number,
|
||||
config: BacktestConfig,
|
||||
futureData: MarketDataPoint[]
|
||||
): Promise<void> {
|
||||
// Calculate position size
|
||||
const riskPerTrade = config.parameters.riskPerTrade || 0.02; // 2% risk
|
||||
const maxPosition = this.currentCapital * riskPerTrade;
|
||||
const quantity = maxPosition / currentPrice;
|
||||
|
||||
// Apply slippage
|
||||
const slippage = config.slippage || 0.001;
|
||||
const entryPrice = signal.action === TradeAction.BUY
|
||||
? currentPrice * (1 + slippage)
|
||||
: currentPrice * (1 - slippage);
|
||||
|
||||
// Find exit point
|
||||
let exitPrice: number | undefined;
|
||||
let exitTime: Date | undefined;
|
||||
let exitReason = 'Manual';
|
||||
|
||||
const stopLoss = signal.stopLoss || entryPrice * 0.95;
|
||||
const takeProfit = signal.takeProfit || entryPrice * 1.05;
|
||||
|
||||
for (const dataPoint of futureData) {
|
||||
const high = dataPoint.high;
|
||||
const low = dataPoint.low;
|
||||
|
||||
// Check stop loss
|
||||
if (signal.action === TradeAction.BUY && low <= stopLoss) {
|
||||
exitPrice = stopLoss * (1 - slippage);
|
||||
exitTime = dataPoint.timestamp;
|
||||
exitReason = 'Stop Loss';
|
||||
break;
|
||||
}
|
||||
|
||||
if (signal.action === TradeAction.SELL && high >= stopLoss) {
|
||||
exitPrice = stopLoss * (1 + slippage);
|
||||
exitTime = dataPoint.timestamp;
|
||||
exitReason = 'Stop Loss';
|
||||
break;
|
||||
}
|
||||
|
||||
// Check take profit
|
||||
if (signal.action === TradeAction.BUY && high >= takeProfit) {
|
||||
exitPrice = takeProfit * (1 - slippage);
|
||||
exitTime = dataPoint.timestamp;
|
||||
exitReason = 'Take Profit';
|
||||
break;
|
||||
}
|
||||
|
||||
if (signal.action === TradeAction.SELL && low <= takeProfit) {
|
||||
exitPrice = takeProfit * (1 + slippage);
|
||||
exitTime = dataPoint.timestamp;
|
||||
exitReason = 'Take Profit';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If no exit found, close at last price
|
||||
if (!exitPrice && futureData.length > 0) {
|
||||
const lastCandle = futureData[futureData.length - 1];
|
||||
exitPrice = lastCandle.close;
|
||||
exitTime = lastCandle.timestamp;
|
||||
exitReason = 'End of Period';
|
||||
}
|
||||
|
||||
// Calculate PnL
|
||||
if (exitPrice) {
|
||||
const fees = config.fees || 0.001;
|
||||
const feeAmount = (entryPrice * quantity * fees) + (exitPrice * quantity * fees);
|
||||
|
||||
let pnl: number;
|
||||
if (signal.action === TradeAction.BUY) {
|
||||
pnl = (exitPrice - entryPrice) * quantity - feeAmount;
|
||||
} else {
|
||||
pnl = (entryPrice - exitPrice) * quantity - feeAmount;
|
||||
}
|
||||
|
||||
const pnlPercent = pnl / (entryPrice * quantity);
|
||||
|
||||
// Update capital
|
||||
this.currentCapital += pnl;
|
||||
|
||||
// Record trade
|
||||
this.trades.push({
|
||||
id: `trade-${this.trades.length}`,
|
||||
sessionId: '',
|
||||
symbol: signal.symbol,
|
||||
action: signal.action,
|
||||
entryPrice,
|
||||
exitPrice,
|
||||
quantity,
|
||||
pnl,
|
||||
pnlPercent,
|
||||
executedAt: new Date(),
|
||||
closedAt: exitTime,
|
||||
notes: exitReason
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate simulated historical data
|
||||
* In production, this would fetch real data from Bybit API
|
||||
*/
|
||||
private async generateHistoricalData(
|
||||
symbol: string,
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<MarketDataPoint[]> {
|
||||
const data: MarketDataPoint[] = [];
|
||||
const start = startDate.getTime();
|
||||
const end = endDate.getTime();
|
||||
const hour = 60 * 60 * 1000;
|
||||
|
||||
// Generate realistic price movements
|
||||
let price = 40000 + Math.random() * 10000; // Starting price
|
||||
|
||||
for (let timestamp = start; timestamp <= end; timestamp += hour) {
|
||||
// Random walk with drift
|
||||
const change = (Math.random() - 0.48) * price * 0.02; // Slight upward bias
|
||||
const open = price;
|
||||
const close = price + change;
|
||||
const high = Math.max(open, close) + Math.random() * Math.abs(change) * 0.5;
|
||||
const low = Math.min(open, close) - Math.random() * Math.abs(change) * 0.5;
|
||||
const volume = 1000 + Math.random() * 5000;
|
||||
|
||||
data.push({
|
||||
symbol,
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
timestamp: new Date(timestamp),
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume
|
||||
});
|
||||
|
||||
price = close;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate performance metrics
|
||||
*/
|
||||
private calculatePerformanceMetrics(
|
||||
initialCapital: number,
|
||||
finalCapital: number
|
||||
): PerformanceMetrics {
|
||||
const winningTrades = this.trades.filter(t => (t.pnl || 0) > 0);
|
||||
const losingTrades = this.trades.filter(t => (t.pnl || 0) <= 0);
|
||||
|
||||
const totalReturn = ((finalCapital - initialCapital) / initialCapital) * 100;
|
||||
|
||||
// Calculate annualized return (assuming 365 days)
|
||||
const days = 365;
|
||||
const annualizedReturn = ((Math.pow(finalCapital / initialCapital, 365 / days) - 1) * 100);
|
||||
|
||||
// Calculate Sharpe Ratio
|
||||
const returns = this.trades.map(t => t.pnlPercent || 0);
|
||||
const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length || 0;
|
||||
const stdDev = Math.sqrt(
|
||||
returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length
|
||||
) || 0;
|
||||
const sharpeRatio = stdDev > 0 ? (avgReturn / stdDev) * Math.sqrt(252) : 0;
|
||||
|
||||
// Calculate Sortino Ratio (downside deviation)
|
||||
const downsideReturns = returns.filter(r => r < 0);
|
||||
const downsideDev = Math.sqrt(
|
||||
downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) / downsideReturns.length
|
||||
) || 0;
|
||||
const sortinoRatio = downsideDev > 0 ? (avgReturn / downsideDev) * Math.sqrt(252) : 0;
|
||||
|
||||
// Calculate max drawdown
|
||||
let maxDrawdown = 0;
|
||||
let peak = this.equityCurve[0] || initialCapital;
|
||||
|
||||
for (const equity of this.equityCurve) {
|
||||
if (equity > peak) {
|
||||
peak = equity;
|
||||
}
|
||||
const drawdown = (peak - equity) / peak;
|
||||
if (drawdown > maxDrawdown) {
|
||||
maxDrawdown = drawdown;
|
||||
}
|
||||
}
|
||||
|
||||
// Win rate
|
||||
const winRate = this.trades.length > 0
|
||||
? winningTrades.length / this.trades.length
|
||||
: 0;
|
||||
|
||||
// Profit factor
|
||||
const grossProfit = winningTrades.reduce((sum, t) => sum + (t.pnl || 0), 0);
|
||||
const grossLoss = Math.abs(losingTrades.reduce((sum, t) => sum + (t.pnl || 0), 0));
|
||||
const profitFactor = grossLoss > 0 ? grossProfit / grossLoss : 0;
|
||||
|
||||
// Average win/loss
|
||||
const averageWin = winningTrades.length > 0
|
||||
? grossProfit / winningTrades.length
|
||||
: 0;
|
||||
const averageLoss = losingTrades.length > 0
|
||||
? grossLoss / losingTrades.length
|
||||
: 0;
|
||||
|
||||
return {
|
||||
totalReturn,
|
||||
annualizedReturn,
|
||||
sharpeRatio,
|
||||
sortinoRatio,
|
||||
maxDrawdown: maxDrawdown * 100,
|
||||
winRate: winRate * 100,
|
||||
profitFactor,
|
||||
averageWin,
|
||||
averageLoss,
|
||||
totalTrades: this.trades.length,
|
||||
winningTrades: winningTrades.length,
|
||||
losingTrades: losingTrades.length
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimize strategy parameters
|
||||
*/
|
||||
async optimizeStrategy(
|
||||
symbol: string,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
parameterRanges: Record<string, number[]>
|
||||
): Promise<{
|
||||
bestParameters: Record<string, number>;
|
||||
bestPerformance: PerformanceMetrics;
|
||||
allResults: Array<{ parameters: Record<string, number>; metrics: PerformanceMetrics }>;
|
||||
}> {
|
||||
const results: Array<{ parameters: Record<string, number>; metrics: PerformanceMetrics }> = [];
|
||||
|
||||
// Generate all parameter combinations
|
||||
const combinations = this.generateCombinations(parameterRanges);
|
||||
|
||||
for (const params of combinations) {
|
||||
const config: BacktestConfig = {
|
||||
name: `Optimization ${JSON.stringify(params)}`,
|
||||
symbol,
|
||||
startDate,
|
||||
endDate,
|
||||
initialCapital: 10000,
|
||||
strategy: 'default',
|
||||
parameters: params,
|
||||
fees: 0.001,
|
||||
slippage: 0.001
|
||||
};
|
||||
|
||||
const session = await this.runBacktest(config);
|
||||
|
||||
if (session.status === 'COMPLETED') {
|
||||
const metrics = this.calculatePerformanceMetrics(
|
||||
config.initialCapital,
|
||||
session.finalCapital || config.initialCapital
|
||||
);
|
||||
|
||||
results.push({ parameters: params, metrics });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by Sharpe ratio
|
||||
results.sort((a, b) => b.metrics.sharpeRatio - a.metrics.sharpeRatio);
|
||||
|
||||
return {
|
||||
bestParameters: results[0]?.parameters || {},
|
||||
bestPerformance: results[0]?.metrics || this.getEmptyMetrics(),
|
||||
allResults: results
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate parameter combinations
|
||||
*/
|
||||
private generateCombinations(
|
||||
ranges: Record<string, number[]>
|
||||
): Record<string, number>[] {
|
||||
const keys = Object.keys(ranges);
|
||||
if (keys.length === 0) return [{}];
|
||||
|
||||
const result: Record<string, number>[] = [];
|
||||
const [firstKey, ...restKeys] = keys;
|
||||
|
||||
for (const value of ranges[firstKey]) {
|
||||
const restCombinations = this.generateCombinations(
|
||||
Object.fromEntries(restKeys.map(k => [k, ranges[k]]))
|
||||
);
|
||||
|
||||
for (const rest of restCombinations) {
|
||||
result.push({ [firstKey]: value, ...rest });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get empty metrics
|
||||
*/
|
||||
private getEmptyMetrics(): PerformanceMetrics {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
annualizedReturn: 0,
|
||||
sharpeRatio: 0,
|
||||
sortinoRatio: 0,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
profitFactor: 0,
|
||||
averageWin: 0,
|
||||
averageLoss: 0,
|
||||
totalTrades: 0,
|
||||
winningTrades: 0,
|
||||
losingTrades: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate backtest report
|
||||
*/
|
||||
generateReport(session: BacktestSession): string {
|
||||
const metrics = this.calculatePerformanceMetrics(
|
||||
session.initialCapital,
|
||||
session.finalCapital || session.initialCapital
|
||||
);
|
||||
|
||||
return `
|
||||
# Backtest Report: ${session.name}
|
||||
|
||||
## Summary
|
||||
- Symbol: ${session.symbol}
|
||||
- Period: ${session.startDate.toDateString()} - ${session.endDate.toDateString()}
|
||||
- Initial Capital: $${session.initialCapital.toLocaleString()}
|
||||
- Final Capital: $${(session.finalCapital || session.initialCapital).toLocaleString()}
|
||||
|
||||
## Performance Metrics
|
||||
- Total Return: ${metrics.totalReturn.toFixed(2)}%
|
||||
- Annualized Return: ${metrics.annualizedReturn.toFixed(2)}%
|
||||
- Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)}
|
||||
- Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)}
|
||||
- Max Drawdown: ${metrics.maxDrawdown.toFixed(2)}%
|
||||
- Win Rate: ${metrics.winRate.toFixed(2)}%
|
||||
- Profit Factor: ${metrics.profitFactor.toFixed(2)}
|
||||
|
||||
## Trade Statistics
|
||||
- Total Trades: ${metrics.totalTrades}
|
||||
- Winning Trades: ${metrics.winningTrades}
|
||||
- Losing Trades: ${metrics.losingTrades}
|
||||
- Average Win: $${metrics.averageWin.toFixed(2)}
|
||||
- Average Loss: $${metrics.averageLoss.toFixed(2)}
|
||||
`.trim();
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const backtestEngine = new BacktestEngine();
|
||||
654
src/lib/trading/core/trading-engine.ts
Normal file
654
src/lib/trading/core/trading-engine.ts
Normal file
@@ -0,0 +1,654 @@
|
||||
/**
|
||||
* Bybit Trading Client for Mantle AI Trading Bot
|
||||
* Handles all exchange interactions including orders, positions, and market data
|
||||
*/
|
||||
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import crypto from 'crypto';
|
||||
import {
|
||||
TradingConfig,
|
||||
Order,
|
||||
Position,
|
||||
Ticker,
|
||||
MarketDataPoint,
|
||||
OrderBook,
|
||||
TradeAction,
|
||||
OrderType,
|
||||
OrderStatus,
|
||||
TimeFrame,
|
||||
BybitTickerResponse,
|
||||
BybitKlineResponse,
|
||||
BybitOrderResponse,
|
||||
BybitPositionResponse,
|
||||
APIResponse
|
||||
} from './types';
|
||||
|
||||
// Bybit API endpoints
|
||||
const BYBIT_ENDPOINTS = {
|
||||
mainnet: {
|
||||
spot: 'https://api.bybit.com',
|
||||
futures: 'https://api.bybit.com'
|
||||
},
|
||||
testnet: {
|
||||
spot: 'https://api-testnet.bybit.com',
|
||||
futures: 'https://api-testnet.bybit.com'
|
||||
}
|
||||
};
|
||||
|
||||
export class BybitClient {
|
||||
private client: AxiosInstance;
|
||||
private config: TradingConfig;
|
||||
private baseUrl: string;
|
||||
|
||||
constructor(config: TradingConfig) {
|
||||
this.config = config;
|
||||
this.baseUrl = config.testnet
|
||||
? BYBIT_ENDPOINTS.testnet.futures
|
||||
: BYBIT_ENDPOINTS.mainnet.futures;
|
||||
|
||||
this.client = axios.create({
|
||||
baseURL: this.baseUrl,
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate signature for authenticated requests
|
||||
*/
|
||||
private generateSignature(params: Record<string, unknown>, timestamp: number): string {
|
||||
const queryString = Object.keys(params)
|
||||
.sort()
|
||||
.map(key => `${key}=${params[key]}`)
|
||||
.join('&');
|
||||
|
||||
const signString = `${timestamp}${this.config.apiKey}5000${queryString}`;
|
||||
return crypto
|
||||
.createHmac('sha256', this.config.apiSecret)
|
||||
.update(signString)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Make authenticated request to Bybit API
|
||||
*/
|
||||
private async authenticatedRequest<T>(
|
||||
method: 'GET' | 'POST',
|
||||
endpoint: string,
|
||||
params: Record<string, unknown> = {}
|
||||
): Promise<APIResponse<T>> {
|
||||
const timestamp = Date.now();
|
||||
const signature = this.generateSignature(params, timestamp);
|
||||
|
||||
const headers = {
|
||||
'X-BAPI-API-KEY': this.config.apiKey,
|
||||
'X-BAPI-TIMESTAMP': timestamp,
|
||||
'X-BAPI-SIGN': signature,
|
||||
'X-BAPI-RECV-WINDOW': '5000'
|
||||
};
|
||||
|
||||
try {
|
||||
const response = method === 'GET'
|
||||
? await this.client.get(endpoint, { params, headers })
|
||||
: await this.client.post(endpoint, params, { headers });
|
||||
|
||||
return {
|
||||
success: response.data.retCode === 0,
|
||||
data: response.data.result,
|
||||
message: response.data.retMsg
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make public request to Bybit API
|
||||
*/
|
||||
private async publicRequest<T>(
|
||||
method: 'GET' | 'POST',
|
||||
endpoint: string,
|
||||
params: Record<string, unknown> = {}
|
||||
): Promise<APIResponse<T>> {
|
||||
try {
|
||||
const response = method === 'GET'
|
||||
? await this.client.get(endpoint, { params })
|
||||
: await this.client.post(endpoint, params);
|
||||
|
||||
return {
|
||||
success: response.data.retCode === 0,
|
||||
data: response.data.result,
|
||||
message: response.data.retMsg
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== MARKET DATA ====================
|
||||
|
||||
/**
|
||||
* Get ticker information for a symbol
|
||||
*/
|
||||
async getTicker(symbol: string): Promise<Ticker | null> {
|
||||
const response = await this.publicRequest<BybitTickerResponse[]>(
|
||||
'GET',
|
||||
'/v5/market/tickers',
|
||||
{ category: 'linear', symbol }
|
||||
);
|
||||
|
||||
if (!response.success || !response.data?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = response.data[0];
|
||||
return {
|
||||
symbol: data.symbol,
|
||||
lastPrice: parseFloat(data.lastPrice),
|
||||
bidPrice: parseFloat(data.bid1Price),
|
||||
askPrice: parseFloat(data.ask1Price),
|
||||
bidQty: parseFloat(data.bid1Size),
|
||||
askQty: parseFloat(data.ask1Size),
|
||||
volume24h: parseFloat(data.volume24h),
|
||||
priceChange24h: parseFloat(data.price24hPcnt) * parseFloat(data.lastPrice),
|
||||
priceChangePercent24h: parseFloat(data.price24hPcnt) * 100,
|
||||
highPrice24h: parseFloat(data.highPrice24h),
|
||||
lowPrice24h: parseFloat(data.lowPrice24h),
|
||||
timestamp: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get multiple tickers
|
||||
*/
|
||||
async getTickers(symbols: string[]): Promise<Ticker[]> {
|
||||
const tickers: Ticker[] = [];
|
||||
|
||||
for (const symbol of symbols) {
|
||||
const ticker = await this.getTicker(symbol);
|
||||
if (ticker) tickers.push(ticker);
|
||||
}
|
||||
|
||||
return tickers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get kline/candlestick data
|
||||
*/
|
||||
async getKlines(
|
||||
symbol: string,
|
||||
timeframe: TimeFrame,
|
||||
limit: number = 200,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
): Promise<MarketDataPoint[]> {
|
||||
const intervalMap: Record<TimeFrame, string> = {
|
||||
[TimeFrame.ONE_MINUTE]: '1',
|
||||
[TimeFrame.FIVE_MINUTES]: '5',
|
||||
[TimeFrame.FIFTEEN_MINUTES]: '15',
|
||||
[TimeFrame.ONE_HOUR]: '60',
|
||||
[TimeFrame.FOUR_HOURS]: '240',
|
||||
[TimeFrame.ONE_DAY]: 'D',
|
||||
[TimeFrame.ONE_WEEK]: 'W'
|
||||
};
|
||||
|
||||
const params: Record<string, unknown> = {
|
||||
category: 'linear',
|
||||
symbol,
|
||||
interval: intervalMap[timeframe],
|
||||
limit
|
||||
};
|
||||
|
||||
if (startTime) params.start = startTime;
|
||||
if (endTime) params.end = endTime;
|
||||
|
||||
const response = await this.publicRequest<BybitKlineResponse[]>(
|
||||
'GET',
|
||||
'/v5/market/kline',
|
||||
params
|
||||
);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.map((kline): MarketDataPoint => ({
|
||||
symbol,
|
||||
timeframe,
|
||||
timestamp: new Date(kline.startTime),
|
||||
open: parseFloat(kline.openPrice),
|
||||
high: parseFloat(kline.highPrice),
|
||||
low: parseFloat(kline.lowPrice),
|
||||
close: parseFloat(kline.closePrice),
|
||||
volume: parseFloat(kline.volume)
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get order book
|
||||
*/
|
||||
async getOrderBook(symbol: string, limit: number = 50): Promise<OrderBook | null> {
|
||||
const response = await this.publicRequest<{
|
||||
b: [string, string][];
|
||||
a: [string, string][];
|
||||
}>(
|
||||
'GET',
|
||||
'/v5/market/orderbook',
|
||||
{ category: 'linear', symbol, limit }
|
||||
);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
symbol,
|
||||
bids: response.data.b.map(([price, qty]) => ({
|
||||
price: parseFloat(price),
|
||||
quantity: parseFloat(qty)
|
||||
})),
|
||||
asks: response.data.a.map(([price, qty]) => ({
|
||||
price: parseFloat(price),
|
||||
quantity: parseFloat(qty)
|
||||
})),
|
||||
timestamp: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== ORDER MANAGEMENT ====================
|
||||
|
||||
/**
|
||||
* Place a new order
|
||||
*/
|
||||
async placeOrder(params: {
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
orderType: OrderType;
|
||||
quantity: number;
|
||||
price?: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
leverage?: number;
|
||||
positionIdx?: number;
|
||||
}): Promise<Order | null> {
|
||||
const sideMap: Record<TradeAction, string> = {
|
||||
[TradeAction.BUY]: 'Buy',
|
||||
[TradeAction.SELL]: 'Sell',
|
||||
[TradeAction.HOLD]: 'Buy', // Should not be used
|
||||
[TradeAction.CLOSE]: 'Sell' // Close position
|
||||
};
|
||||
|
||||
const orderTypeMap: Record<OrderType, string> = {
|
||||
[OrderType.MARKET]: 'Market',
|
||||
[OrderType.LIMIT]: 'Limit',
|
||||
[OrderType.STOP_MARKET]: 'Market',
|
||||
[OrderType.STOP_LIMIT]: 'Limit'
|
||||
};
|
||||
|
||||
const requestParams: Record<string, unknown> = {
|
||||
category: 'linear',
|
||||
symbol: params.symbol,
|
||||
side: sideMap[params.side],
|
||||
orderType: orderTypeMap[params.orderType],
|
||||
qty: params.quantity.toString(),
|
||||
positionIdx: params.positionIdx || 0
|
||||
};
|
||||
|
||||
if (params.price && params.orderType !== OrderType.MARKET) {
|
||||
requestParams.price = params.price.toString();
|
||||
}
|
||||
|
||||
if (params.stopLoss) {
|
||||
requestParams.stopLoss = params.stopLoss.toString();
|
||||
}
|
||||
|
||||
if (params.takeProfit) {
|
||||
requestParams.takeProfit = params.takeProfit.toString();
|
||||
}
|
||||
|
||||
// Set leverage if specified
|
||||
if (params.leverage && params.leverage !== 1) {
|
||||
await this.setLeverage(params.symbol, params.leverage);
|
||||
}
|
||||
|
||||
const response = await this.authenticatedRequest<BybitOrderResponse>(
|
||||
'POST',
|
||||
'/v5/order/create',
|
||||
requestParams
|
||||
);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
console.error('Order placement failed:', response.error);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = response.data;
|
||||
return {
|
||||
id: data.orderId,
|
||||
symbol: data.symbol,
|
||||
side: params.side,
|
||||
type: params.orderType,
|
||||
quantity: params.quantity,
|
||||
price: params.price,
|
||||
status: OrderStatus.PENDING,
|
||||
leverage: params.leverage || 1,
|
||||
stopLoss: params.stopLoss,
|
||||
takeProfit: params.takeProfit,
|
||||
orderId: data.orderId,
|
||||
filledQuantity: 0,
|
||||
fees: 0,
|
||||
demo: false,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an order
|
||||
*/
|
||||
async cancelOrder(symbol: string, orderId: string): Promise<boolean> {
|
||||
const response = await this.authenticatedRequest(
|
||||
'POST',
|
||||
'/v5/order/cancel',
|
||||
{
|
||||
category: 'linear',
|
||||
symbol,
|
||||
orderId
|
||||
}
|
||||
);
|
||||
|
||||
return response.success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all orders for a symbol
|
||||
*/
|
||||
async cancelAllOrders(symbol?: string): Promise<boolean> {
|
||||
const params: Record<string, unknown> = {
|
||||
category: 'linear'
|
||||
};
|
||||
|
||||
if (symbol) {
|
||||
params.symbol = symbol;
|
||||
}
|
||||
|
||||
const response = await this.authenticatedRequest(
|
||||
'POST',
|
||||
'/v5/order/cancel-all',
|
||||
params
|
||||
);
|
||||
|
||||
return response.success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get order details
|
||||
*/
|
||||
async getOrder(symbol: string, orderId: string): Promise<Order | null> {
|
||||
const response = await this.authenticatedRequest<BybitOrderResponse>(
|
||||
'GET',
|
||||
'/v5/order/realtime',
|
||||
{
|
||||
category: 'linear',
|
||||
symbol,
|
||||
orderId
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = response.data;
|
||||
return {
|
||||
id: data.orderId,
|
||||
symbol: data.symbol,
|
||||
side: data.side === 'Buy' ? TradeAction.BUY : TradeAction.SELL,
|
||||
type: data.orderType === 'Market' ? OrderType.MARKET : OrderType.LIMIT,
|
||||
quantity: parseFloat(data.qty),
|
||||
price: parseFloat(data.price),
|
||||
status: this.mapOrderStatus(data.orderStatus),
|
||||
leverage: 1,
|
||||
orderId: data.orderId,
|
||||
executedPrice: parseFloat(data.avgPrice || '0') || undefined,
|
||||
executedAt: data.updatedTime ? new Date(parseInt(data.updatedTime)) : undefined,
|
||||
filledQuantity: parseFloat(data.cumExecQty),
|
||||
fees: parseFloat(data.cumExecFee || '0'),
|
||||
demo: false,
|
||||
createdAt: new Date(parseInt(data.createdTime)),
|
||||
updatedAt: new Date(parseInt(data.updatedTime))
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get open orders
|
||||
*/
|
||||
async getOpenOrders(symbol?: string): Promise<Order[]> {
|
||||
const params: Record<string, unknown> = {
|
||||
category: 'linear',
|
||||
openOnly: 0
|
||||
};
|
||||
|
||||
if (symbol) {
|
||||
params.symbol = symbol;
|
||||
}
|
||||
|
||||
const response = await this.authenticatedRequest<{ list: BybitOrderResponse[] }>(
|
||||
'GET',
|
||||
'/v5/order/realtime',
|
||||
params
|
||||
);
|
||||
|
||||
if (!response.success || !response.data?.list) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.list.map(data => ({
|
||||
id: data.orderId,
|
||||
symbol: data.symbol,
|
||||
side: data.side === 'Buy' ? TradeAction.BUY : TradeAction.SELL,
|
||||
type: data.orderType === 'Market' ? OrderType.MARKET : OrderType.LIMIT,
|
||||
quantity: parseFloat(data.qty),
|
||||
price: parseFloat(data.price),
|
||||
status: this.mapOrderStatus(data.orderStatus),
|
||||
leverage: 1,
|
||||
orderId: data.orderId,
|
||||
filledQuantity: parseFloat(data.cumExecQty),
|
||||
fees: parseFloat(data.cumExecFee || '0'),
|
||||
demo: false,
|
||||
createdAt: new Date(parseInt(data.createdTime)),
|
||||
updatedAt: new Date(parseInt(data.updatedTime))
|
||||
}));
|
||||
}
|
||||
|
||||
// ==================== POSITION MANAGEMENT ====================
|
||||
|
||||
/**
|
||||
* Get positions
|
||||
*/
|
||||
async getPositions(symbol?: string): Promise<Position[]> {
|
||||
const params: Record<string, unknown> = {
|
||||
category: 'linear'
|
||||
};
|
||||
|
||||
if (symbol) {
|
||||
params.symbol = symbol;
|
||||
}
|
||||
|
||||
const response = await this.authenticatedRequest<{ list: BybitPositionResponse[] }>(
|
||||
'GET',
|
||||
'/v5/position/list',
|
||||
params
|
||||
);
|
||||
|
||||
if (!response.success || !response.data?.list) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.list
|
||||
.filter(pos => parseFloat(pos.size) > 0)
|
||||
.map(data => ({
|
||||
id: `${data.symbol}-${data.side}`,
|
||||
symbol: data.symbol,
|
||||
side: data.side === 'Buy' ? 'LONG' as const : 'SHORT' as const,
|
||||
quantity: parseFloat(data.size),
|
||||
avgEntryPrice: parseFloat(data.avgPrice),
|
||||
currentPrice: parseFloat(data.avgPrice), // Would need to fetch current price separately
|
||||
marketValue: parseFloat(data.positionValue),
|
||||
unrealizedPnL: parseFloat(data.unrealisedPnl),
|
||||
unrealizedPnLPercent: (parseFloat(data.unrealisedPnl) / parseFloat(data.positionValue)) * 100,
|
||||
leverage: parseFloat(data.leverage),
|
||||
liquidationPrice: parseFloat(data.liqPrice) || undefined,
|
||||
stopLoss: parseFloat(data.stopLoss) || undefined,
|
||||
takeProfit: parseFloat(data.takeProfit) || undefined,
|
||||
openedAt: new Date(parseInt(data.createdTime)),
|
||||
demo: false
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set leverage for a symbol
|
||||
*/
|
||||
async setLeverage(symbol: string, leverage: number): Promise<boolean> {
|
||||
const response = await this.authenticatedRequest(
|
||||
'POST',
|
||||
'/v5/position/set-leverage',
|
||||
{
|
||||
category: 'linear',
|
||||
symbol,
|
||||
buyLeverage: leverage.toString(),
|
||||
sellLeverage: leverage.toString()
|
||||
}
|
||||
);
|
||||
|
||||
return response.success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set trading stop (TP/SL) for a position
|
||||
*/
|
||||
async setTradingStop(params: {
|
||||
symbol: string;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
trailingStop?: number;
|
||||
}): Promise<boolean> {
|
||||
const requestParams: Record<string, unknown> = {
|
||||
category: 'linear',
|
||||
symbol: params.symbol,
|
||||
positionIdx: 0
|
||||
};
|
||||
|
||||
if (params.stopLoss) {
|
||||
requestParams.stopLoss = params.stopLoss.toString();
|
||||
}
|
||||
|
||||
if (params.takeProfit) {
|
||||
requestParams.takeProfit = params.takeProfit.toString();
|
||||
}
|
||||
|
||||
if (params.trailingStop) {
|
||||
requestParams.trailingStop = params.trailingStop.toString();
|
||||
}
|
||||
|
||||
const response = await this.authenticatedRequest(
|
||||
'POST',
|
||||
'/v5/position/trading-stop',
|
||||
requestParams
|
||||
);
|
||||
|
||||
return response.success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close position
|
||||
*/
|
||||
async closePosition(symbol: string, side?: 'LONG' | 'SHORT'): Promise<Order | null> {
|
||||
const positions = await this.getPositions(symbol);
|
||||
const position = positions.find(p => !side || p.side === side);
|
||||
|
||||
if (!position) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.placeOrder({
|
||||
symbol,
|
||||
side: position.side === 'LONG' ? TradeAction.SELL : TradeAction.BUY,
|
||||
orderType: OrderType.MARKET,
|
||||
quantity: position.quantity
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== WALLET ====================
|
||||
|
||||
/**
|
||||
* Get wallet balance
|
||||
*/
|
||||
async getWalletBalance(accountType: 'UNIFIED' | 'CONTRACT' = 'UNIFIED'): Promise<{
|
||||
totalEquity: number;
|
||||
totalAvailableBalance: number;
|
||||
coins: Array<{ coin: string; walletBalance: number; availableToWithdraw: number }>;
|
||||
} | null> {
|
||||
const response = await this.authenticatedRequest<{
|
||||
coin: Array<{
|
||||
coin: string;
|
||||
walletBalance: string;
|
||||
availableToWithdraw: string;
|
||||
equity: string;
|
||||
}>;
|
||||
}>(
|
||||
'GET',
|
||||
'/v5/account/wallet-balance',
|
||||
{ accountType }
|
||||
);
|
||||
|
||||
if (!response.success || !response.data?.coin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const coins = response.data.coin.map(c => ({
|
||||
coin: c.coin,
|
||||
walletBalance: parseFloat(c.walletBalance),
|
||||
availableToWithdraw: parseFloat(c.availableToWithdraw)
|
||||
}));
|
||||
|
||||
const totalEquity = response.data.coin.reduce(
|
||||
(sum, c) => sum + parseFloat(c.equity),
|
||||
0
|
||||
);
|
||||
|
||||
return {
|
||||
totalEquity,
|
||||
totalAvailableBalance: totalEquity,
|
||||
coins
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== HELPERS ====================
|
||||
|
||||
private mapOrderStatus(status: string): OrderStatus {
|
||||
const statusMap: Record<string, OrderStatus> = {
|
||||
'New': OrderStatus.OPEN,
|
||||
'PartiallyFilled': OrderStatus.PARTIALLY_FILLED,
|
||||
'Filled': OrderStatus.FILLED,
|
||||
'Cancelled': OrderStatus.CANCELLED,
|
||||
'Rejected': OrderStatus.FAILED,
|
||||
'Deactivated': OrderStatus.EXPIRED
|
||||
};
|
||||
|
||||
return statusMap[status] || OrderStatus.PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance factory
|
||||
export function createBybitClient(config: TradingConfig): BybitClient {
|
||||
return new BybitClient(config);
|
||||
}
|
||||
510
src/lib/trading/core/types.ts
Normal file
510
src/lib/trading/core/types.ts
Normal file
@@ -0,0 +1,510 @@
|
||||
/**
|
||||
* Core Trading Types and Interfaces for Mantle AI Trading Bot
|
||||
* Comprehensive type definitions for the entire trading system
|
||||
*/
|
||||
|
||||
// ==================== ENUMS ====================
|
||||
|
||||
export enum TradeAction {
|
||||
BUY = 'BUY',
|
||||
SELL = 'SELL',
|
||||
HOLD = 'HOLD',
|
||||
CLOSE = 'CLOSE'
|
||||
}
|
||||
|
||||
export enum OrderType {
|
||||
MARKET = 'MARKET',
|
||||
LIMIT = 'LIMIT',
|
||||
STOP_MARKET = 'STOP_MARKET',
|
||||
STOP_LIMIT = 'STOP_LIMIT'
|
||||
}
|
||||
|
||||
export enum OrderStatus {
|
||||
PENDING = 'PENDING',
|
||||
OPEN = 'OPEN',
|
||||
FILLED = 'FILLED',
|
||||
PARTIALLY_FILLED = 'PARTIALLY_FILLED',
|
||||
CANCELLED = 'CANCELLED',
|
||||
FAILED = 'FAILED',
|
||||
EXPIRED = 'EXPIRED'
|
||||
}
|
||||
|
||||
export enum SignalStatus {
|
||||
PENDING = 'PENDING',
|
||||
ACTIVE = 'ACTIVE',
|
||||
EXECUTED = 'EXECUTED',
|
||||
CANCELLED = 'CANCELLED',
|
||||
EXPIRED = 'EXPIRED'
|
||||
}
|
||||
|
||||
export enum SignalResult {
|
||||
WIN = 'WIN',
|
||||
LOSS = 'LOSS',
|
||||
NEUTRAL = 'NEUTRAL',
|
||||
PENDING = 'PENDING'
|
||||
}
|
||||
|
||||
export enum RiskLevel {
|
||||
CONSERVATIVE = 'CONSERVATIVE',
|
||||
MODERATE = 'MODERATE',
|
||||
AGGRESSIVE = 'AGGRESSIVE'
|
||||
}
|
||||
|
||||
export enum PositionSide {
|
||||
LONG = 'LONG',
|
||||
SHORT = 'SHORT'
|
||||
}
|
||||
|
||||
export enum TimeFrame {
|
||||
ONE_MINUTE = '1m',
|
||||
FIVE_MINUTES = '5m',
|
||||
FIFTEEN_MINUTES = '15m',
|
||||
ONE_HOUR = '1h',
|
||||
FOUR_HOURS = '4h',
|
||||
ONE_DAY = '1d',
|
||||
ONE_WEEK = '1w'
|
||||
}
|
||||
|
||||
export enum NewsSource {
|
||||
CRYPTOPANIC = 'CryptoPanic',
|
||||
COINGECKO = 'CoinGecko',
|
||||
CRYPTOCOMPARE = 'CryptoCompare',
|
||||
BINANCE_NEWS = 'BinanceNews',
|
||||
TWITTER = 'Twitter',
|
||||
REDDIT = 'Reddit',
|
||||
CUSTOM_RSS = 'CustomRSS'
|
||||
}
|
||||
|
||||
export enum SentimentLabel {
|
||||
VERY_BEARISH = 'VERY_BEARISH',
|
||||
BEARISH = 'BEARISH',
|
||||
NEUTRAL = 'NEUTRAL',
|
||||
BULLISH = 'BULLISH',
|
||||
VERY_BULLISH = 'VERY_BULLISH'
|
||||
}
|
||||
|
||||
// ==================== INTERFACES ====================
|
||||
|
||||
export interface TradingConfig {
|
||||
apiKey: string;
|
||||
apiSecret: string;
|
||||
testnet: boolean;
|
||||
riskLevel: RiskLevel;
|
||||
maxPositionSize: number;
|
||||
maxLeverage: number;
|
||||
autoTrading: boolean;
|
||||
defaultStopLossPercent: number;
|
||||
defaultTakeProfitPercent: number;
|
||||
}
|
||||
|
||||
export interface Signal {
|
||||
id: string;
|
||||
symbol: string;
|
||||
action: TradeAction;
|
||||
confidence: number;
|
||||
rating: number;
|
||||
priceTarget?: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
reasoning: string;
|
||||
newsSources?: string[];
|
||||
sentimentScore?: number;
|
||||
technicalScore?: number;
|
||||
fundamentalScore?: number;
|
||||
status: SignalStatus;
|
||||
executedAt?: Date;
|
||||
executedPrice?: number;
|
||||
result?: SignalResult;
|
||||
resultPnL?: number;
|
||||
demo: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface SignalGenerationInput {
|
||||
symbol: string;
|
||||
timeframe: TimeFrame;
|
||||
marketData: MarketDataPoint[];
|
||||
newsArticles: NewsArticle[];
|
||||
additionalContext?: string;
|
||||
}
|
||||
|
||||
export interface SignalGenerationOutput {
|
||||
signal: Omit<Signal, 'id' | 'createdAt' | 'updatedAt'>;
|
||||
analysis: SignalAnalysis;
|
||||
riskAssessment: RiskAssessment;
|
||||
}
|
||||
|
||||
export interface SignalAnalysis {
|
||||
technicalAnalysis: TechnicalAnalysis;
|
||||
fundamentalAnalysis: FundamentalAnalysis;
|
||||
sentimentAnalysis: SentimentAnalysis;
|
||||
overallScore: number;
|
||||
keyFactors: string[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface TechnicalAnalysis {
|
||||
trend: 'BULLISH' | 'BEARISH' | 'SIDEWAYS';
|
||||
trendStrength: number;
|
||||
supportLevels: number[];
|
||||
resistanceLevels: number[];
|
||||
indicators: Record<string, number>;
|
||||
patterns: string[];
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface FundamentalAnalysis {
|
||||
newsImpact: number;
|
||||
marketEvents: string[];
|
||||
economicFactors: string[];
|
||||
tokenomics?: TokenomicsData;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface TokenomicsData {
|
||||
circulatingSupply?: number;
|
||||
totalSupply?: number;
|
||||
marketCap?: number;
|
||||
volume24h?: number;
|
||||
priceChange24h?: number;
|
||||
priceChange7d?: number;
|
||||
}
|
||||
|
||||
export interface SentimentAnalysis {
|
||||
overallSentiment: number;
|
||||
sentimentLabel: SentimentLabel;
|
||||
newsSentiment: number;
|
||||
socialSentiment: number;
|
||||
fearGreedIndex?: number;
|
||||
keyTopics: string[];
|
||||
trendingKeywords: string[];
|
||||
}
|
||||
|
||||
export interface RiskAssessment {
|
||||
riskScore: number;
|
||||
riskLevel: RiskLevel;
|
||||
maxRecommendedPosition: number;
|
||||
suggestedStopLoss: number;
|
||||
suggestedTakeProfit: number;
|
||||
riskFactors: string[];
|
||||
marketVolatility: number;
|
||||
liquidityRisk: number;
|
||||
}
|
||||
|
||||
export interface MarketDataPoint {
|
||||
symbol: string;
|
||||
timeframe: TimeFrame;
|
||||
timestamp: Date;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
export interface OrderBook {
|
||||
symbol: string;
|
||||
bids: OrderBookLevel[];
|
||||
asks: OrderBookLevel[];
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface OrderBookLevel {
|
||||
price: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export interface Ticker {
|
||||
symbol: string;
|
||||
lastPrice: number;
|
||||
bidPrice: number;
|
||||
askPrice: number;
|
||||
bidQty: number;
|
||||
askQty: number;
|
||||
volume24h: number;
|
||||
priceChange24h: number;
|
||||
priceChangePercent24h: number;
|
||||
highPrice24h: number;
|
||||
lowPrice24h: number;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
id: string;
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
type: OrderType;
|
||||
quantity: number;
|
||||
price?: number;
|
||||
stopPrice?: number;
|
||||
status: OrderStatus;
|
||||
leverage: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
orderId?: string;
|
||||
executedAt?: Date;
|
||||
executedPrice?: number;
|
||||
filledQuantity: number;
|
||||
fees: number;
|
||||
demo: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
id: string;
|
||||
symbol: string;
|
||||
side: PositionSide;
|
||||
quantity: number;
|
||||
avgEntryPrice: number;
|
||||
currentPrice: number;
|
||||
marketValue: number;
|
||||
unrealizedPnL: number;
|
||||
unrealizedPnLPercent: number;
|
||||
leverage: number;
|
||||
liquidationPrice?: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
openedAt: Date;
|
||||
demo: boolean;
|
||||
}
|
||||
|
||||
export interface Portfolio {
|
||||
id: string;
|
||||
name: string;
|
||||
totalValue: number;
|
||||
cashBalance: number;
|
||||
realizedPnL: number;
|
||||
unrealizedPnL: number;
|
||||
positions: Position[];
|
||||
demo: boolean;
|
||||
}
|
||||
|
||||
export interface Trade {
|
||||
id: string;
|
||||
signalId?: string;
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
orderType: OrderType;
|
||||
quantity: number;
|
||||
price: number;
|
||||
leverage: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
status: OrderStatus;
|
||||
orderId?: string;
|
||||
executedAt?: Date;
|
||||
closedAt?: Date;
|
||||
pnl?: number;
|
||||
fees?: number;
|
||||
demo: boolean;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface NewsArticle {
|
||||
id: string;
|
||||
title: string;
|
||||
content?: string;
|
||||
summary?: string;
|
||||
source: string;
|
||||
sourceUrl?: string;
|
||||
author?: string;
|
||||
category?: string;
|
||||
sentiment?: number;
|
||||
importance?: number;
|
||||
tags?: string[];
|
||||
publishedAt?: Date;
|
||||
fetchedAt: Date;
|
||||
processed: boolean;
|
||||
vectorId?: string;
|
||||
}
|
||||
|
||||
export interface NewsQuery {
|
||||
sources?: NewsSource[];
|
||||
categories?: string[];
|
||||
symbols?: string[];
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
limit?: number;
|
||||
minImportance?: number;
|
||||
}
|
||||
|
||||
export interface BacktestConfig {
|
||||
name: string;
|
||||
symbol: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
strategy: string;
|
||||
parameters: Record<string, unknown>;
|
||||
fees: number; // Fee percentage per trade
|
||||
slippage: number; // Slippage percentage
|
||||
}
|
||||
|
||||
export interface BacktestResult {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
signalId?: string;
|
||||
symbol: string;
|
||||
action: TradeAction;
|
||||
entryPrice: number;
|
||||
exitPrice?: number;
|
||||
quantity: number;
|
||||
pnl?: number;
|
||||
pnlPercent?: number;
|
||||
executedAt: Date;
|
||||
closedAt?: Date;
|
||||
}
|
||||
|
||||
export interface BacktestSession {
|
||||
id: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
finalCapital?: number;
|
||||
totalTrades: number;
|
||||
winRate?: number;
|
||||
maxDrawdown?: number;
|
||||
sharpeRatio?: number;
|
||||
status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED';
|
||||
results: BacktestResult[];
|
||||
}
|
||||
|
||||
export interface PerformanceMetrics {
|
||||
totalReturn: number;
|
||||
annualizedReturn: number;
|
||||
sharpeRatio: number;
|
||||
sortinoRatio: number;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
profitFactor: number;
|
||||
averageWin: number;
|
||||
averageLoss: number;
|
||||
totalTrades: number;
|
||||
winningTrades: number;
|
||||
losingTrades: number;
|
||||
}
|
||||
|
||||
// ==================== API RESPONSE TYPES ====================
|
||||
|
||||
export interface BybitTickerResponse {
|
||||
symbol: string;
|
||||
lastPrice: string;
|
||||
bid1Price: string;
|
||||
ask1Price: string;
|
||||
bid1Size: string;
|
||||
ask1Size: string;
|
||||
volume24h: string;
|
||||
price24hPcnt: string;
|
||||
highPrice24h: string;
|
||||
lowPrice24h: string;
|
||||
}
|
||||
|
||||
export interface BybitKlineResponse {
|
||||
startTime: number;
|
||||
openPrice: string;
|
||||
highPrice: string;
|
||||
lowPrice: string;
|
||||
closePrice: string;
|
||||
volume: string;
|
||||
turnover: string;
|
||||
}
|
||||
|
||||
export interface BybitOrderResponse {
|
||||
orderId: string;
|
||||
orderLinkId: string;
|
||||
symbol: string;
|
||||
side: string;
|
||||
orderType: string;
|
||||
price: string;
|
||||
qty: string;
|
||||
orderStatus: string;
|
||||
cumExecQty: string;
|
||||
cumExecFee: string;
|
||||
createdTime: string;
|
||||
updatedTime: string;
|
||||
}
|
||||
|
||||
export interface BybitPositionResponse {
|
||||
symbol: string;
|
||||
side: string;
|
||||
size: string;
|
||||
avgPrice: string;
|
||||
positionValue: string;
|
||||
unrealisedPnl: string;
|
||||
leverage: string;
|
||||
liqPrice: string;
|
||||
stopLoss: string;
|
||||
takeProfit: string;
|
||||
createdTime: string;
|
||||
updatedTime: string;
|
||||
}
|
||||
|
||||
// ==================== WEBSOCKET TYPES ====================
|
||||
|
||||
export interface WSMessage<T = unknown> {
|
||||
type: string;
|
||||
data: T;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface WSTickerMessage {
|
||||
symbol: string;
|
||||
ticker: Ticker;
|
||||
}
|
||||
|
||||
export interface WSSignalMessage {
|
||||
signal: Signal;
|
||||
analysis: SignalAnalysis;
|
||||
}
|
||||
|
||||
export interface WSOrderMessage {
|
||||
order: Order;
|
||||
status: OrderStatus;
|
||||
}
|
||||
|
||||
export interface WSPortfolioMessage {
|
||||
portfolio: Portfolio;
|
||||
changes: Partial<Portfolio>;
|
||||
}
|
||||
|
||||
export interface WSNotificationMessage {
|
||||
level: 'INFO' | 'WARNING' | 'ERROR' | 'SUCCESS';
|
||||
title: string;
|
||||
message: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// ==================== UTILITY TYPES ====================
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export interface APIResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface DateRange {
|
||||
start: Date;
|
||||
end: Date;
|
||||
}
|
||||
|
||||
export interface OHLCV {
|
||||
timestamp: Date;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
552
src/lib/trading/demo/demo-trader.ts
Normal file
552
src/lib/trading/demo/demo-trader.ts
Normal file
@@ -0,0 +1,552 @@
|
||||
/**
|
||||
* Demo Trading Mode for Mantle AI Trading Bot
|
||||
* Paper trading system for testing signals without real money
|
||||
*/
|
||||
|
||||
import {
|
||||
Signal,
|
||||
Position,
|
||||
Order,
|
||||
Portfolio,
|
||||
TradeAction,
|
||||
OrderType,
|
||||
OrderStatus,
|
||||
Ticker
|
||||
} from '../core/types';
|
||||
|
||||
export interface DemoOrder {
|
||||
id: string;
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
type: OrderType;
|
||||
quantity: number;
|
||||
price: number;
|
||||
leverage: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
status: OrderStatus;
|
||||
filledAt?: Date;
|
||||
closedAt?: Date;
|
||||
pnl?: number;
|
||||
signalId?: string;
|
||||
}
|
||||
|
||||
export interface DemoPosition {
|
||||
id: string;
|
||||
symbol: string;
|
||||
side: 'LONG' | 'SHORT';
|
||||
quantity: number;
|
||||
avgEntryPrice: number;
|
||||
currentPrice: number;
|
||||
marketValue: number;
|
||||
unrealizedPnL: number;
|
||||
unrealizedPnLPercent: number;
|
||||
leverage: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
openedAt: Date;
|
||||
signalId?: string;
|
||||
}
|
||||
|
||||
export class DemoTrader {
|
||||
private portfolio: Portfolio;
|
||||
private positions: Map<string, DemoPosition> = new Map();
|
||||
private orders: DemoOrder[] = [];
|
||||
private tradeHistory: DemoOrder[] = [];
|
||||
private currentPrices: Map<string, number> = new Map();
|
||||
private listeners: Set<(event: string, data: unknown) => void> = new Set();
|
||||
|
||||
constructor(initialCapital: number = 10000) {
|
||||
this.portfolio = {
|
||||
id: 'demo-portfolio',
|
||||
name: 'Demo Portfolio',
|
||||
totalValue: initialCapital,
|
||||
cashBalance: initialCapital,
|
||||
realizedPnL: 0,
|
||||
unrealizedPnL: 0,
|
||||
positions: [],
|
||||
demo: true
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to events
|
||||
*/
|
||||
subscribe(callback: (event: string, data: unknown) => void): () => void {
|
||||
this.listeners.add(callback);
|
||||
return () => this.listeners.delete(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event
|
||||
*/
|
||||
private emit(event: string, data: unknown): void {
|
||||
this.listeners.forEach(cb => cb(event, data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current portfolio state
|
||||
*/
|
||||
getPortfolio(): Portfolio {
|
||||
this.updatePortfolioValue();
|
||||
return { ...this.portfolio };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all positions
|
||||
*/
|
||||
getPositions(): DemoPosition[] {
|
||||
return Array.from(this.positions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get open orders
|
||||
*/
|
||||
getOpenOrders(): DemoOrder[] {
|
||||
return this.orders.filter(o => o.status === OrderStatus.OPEN || o.status === OrderStatus.PENDING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trade history
|
||||
*/
|
||||
getTradeHistory(): DemoOrder[] {
|
||||
return [...this.tradeHistory];
|
||||
}
|
||||
|
||||
/**
|
||||
* Update current price for a symbol
|
||||
*/
|
||||
updatePrice(symbol: string, price: number): void {
|
||||
this.currentPrices.set(symbol, price);
|
||||
|
||||
// Update position values
|
||||
const position = this.positions.get(symbol);
|
||||
if (position) {
|
||||
position.currentPrice = price;
|
||||
position.marketValue = position.quantity * price;
|
||||
|
||||
if (position.side === 'LONG') {
|
||||
position.unrealizedPnL = (price - position.avgEntryPrice) * position.quantity;
|
||||
} else {
|
||||
position.unrealizedPnL = (position.avgEntryPrice - price) * position.quantity;
|
||||
}
|
||||
|
||||
position.unrealizedPnLPercent = (position.unrealizedPnL / (position.avgEntryPrice * position.quantity)) * 100;
|
||||
|
||||
// Check stop loss and take profit
|
||||
this.checkStopLevels(position);
|
||||
}
|
||||
|
||||
// Check pending orders
|
||||
this.checkPendingOrders(symbol, price);
|
||||
|
||||
this.emit('price_update', { symbol, price });
|
||||
}
|
||||
|
||||
/**
|
||||
* Update multiple prices at once
|
||||
*/
|
||||
updatePrices(tickers: Ticker[]): void {
|
||||
tickers.forEach(ticker => {
|
||||
this.updatePrice(ticker.symbol, ticker.lastPrice);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Place a demo order
|
||||
*/
|
||||
placeOrder(params: {
|
||||
symbol: string;
|
||||
side: TradeAction;
|
||||
type: OrderType;
|
||||
quantity: number;
|
||||
price?: number;
|
||||
leverage?: number;
|
||||
stopLoss?: number;
|
||||
takeProfit?: number;
|
||||
signalId?: string;
|
||||
}): DemoOrder {
|
||||
const currentPrice = this.currentPrices.get(params.symbol) || 0;
|
||||
const executionPrice = params.type === OrderType.LIMIT && params.price
|
||||
? params.price
|
||||
: currentPrice;
|
||||
|
||||
// Check if we have enough capital
|
||||
const requiredCapital = executionPrice * params.quantity * (params.leverage || 1);
|
||||
if (params.side === TradeAction.BUY && requiredCapital > this.portfolio.cashBalance) {
|
||||
throw new Error('Insufficient capital for this order');
|
||||
}
|
||||
|
||||
const order: DemoOrder = {
|
||||
id: `demo-order-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
symbol: params.symbol,
|
||||
side: params.side,
|
||||
type: params.type,
|
||||
quantity: params.quantity,
|
||||
price: executionPrice,
|
||||
leverage: params.leverage || 1,
|
||||
stopLoss: params.stopLoss,
|
||||
takeProfit: params.takeProfit,
|
||||
status: params.type === OrderType.MARKET ? OrderStatus.FILLED : OrderStatus.PENDING,
|
||||
signalId: params.signalId
|
||||
};
|
||||
|
||||
// Execute market orders immediately
|
||||
if (params.type === OrderType.MARKET) {
|
||||
this.executeOrder(order);
|
||||
} else {
|
||||
this.orders.push(order);
|
||||
}
|
||||
|
||||
this.emit('order_placed', order);
|
||||
return order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a signal
|
||||
*/
|
||||
async executeSignal(signal: Signal): Promise<DemoOrder | null> {
|
||||
if (signal.action === TradeAction.HOLD) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// Calculate position size based on confidence
|
||||
const baseRisk = 0.02; // 2% risk per trade
|
||||
const riskMultiplier = signal.confidence * 2; // Scale with confidence
|
||||
const riskAmount = this.portfolio.totalValue * baseRisk * riskMultiplier;
|
||||
|
||||
const currentPrice = this.currentPrices.get(signal.symbol) || signal.priceTarget || 0;
|
||||
if (currentPrice === 0) {
|
||||
throw new Error('No price available for this symbol');
|
||||
}
|
||||
|
||||
const quantity = riskAmount / currentPrice;
|
||||
|
||||
return this.placeOrder({
|
||||
symbol: signal.symbol,
|
||||
side: signal.action,
|
||||
type: OrderType.MARKET,
|
||||
quantity: Math.floor(quantity * 100000000) / 100000000, // Round to 8 decimals
|
||||
stopLoss: signal.stopLoss,
|
||||
takeProfit: signal.takeProfit,
|
||||
signalId: signal.id
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error executing signal:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close a position
|
||||
*/
|
||||
closePosition(symbol: string, quantity?: number): DemoOrder | null {
|
||||
const position = this.positions.get(symbol);
|
||||
if (!position) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const closeQuantity = quantity || position.quantity;
|
||||
const closeSide = position.side === 'LONG' ? TradeAction.SELL : TradeAction.BUY;
|
||||
|
||||
const order = this.placeOrder({
|
||||
symbol,
|
||||
side: closeSide,
|
||||
type: OrderType.MARKET,
|
||||
quantity: closeQuantity
|
||||
});
|
||||
|
||||
return order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an order
|
||||
*/
|
||||
cancelOrder(orderId: string): boolean {
|
||||
const orderIndex = this.orders.findIndex(o => o.id === orderId);
|
||||
if (orderIndex === -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const order = this.orders[orderIndex];
|
||||
if (order.status !== OrderStatus.PENDING) {
|
||||
return false;
|
||||
}
|
||||
|
||||
order.status = OrderStatus.CANCELLED;
|
||||
this.orders.splice(orderIndex, 1);
|
||||
this.tradeHistory.push(order);
|
||||
|
||||
this.emit('order_cancelled', order);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an order
|
||||
*/
|
||||
private executeOrder(order: DemoOrder): void {
|
||||
const existingPosition = this.positions.get(order.symbol);
|
||||
|
||||
if (order.side === TradeAction.BUY) {
|
||||
if (existingPosition && existingPosition.side === 'LONG') {
|
||||
// Add to existing long position
|
||||
const newQuantity = existingPosition.quantity + order.quantity;
|
||||
const newAvgPrice = (
|
||||
(existingPosition.avgEntryPrice * existingPosition.quantity) +
|
||||
(order.price * order.quantity)
|
||||
) / newQuantity;
|
||||
|
||||
existingPosition.quantity = newQuantity;
|
||||
existingPosition.avgEntryPrice = newAvgPrice;
|
||||
existingPosition.marketValue = newQuantity * order.price;
|
||||
} else if (existingPosition && existingPosition.side === 'SHORT') {
|
||||
// Close short position
|
||||
this.closeExistingPosition(existingPosition, order);
|
||||
} else {
|
||||
// Create new long position
|
||||
const newPosition: DemoPosition = {
|
||||
id: `pos-${order.symbol}`,
|
||||
symbol: order.symbol,
|
||||
side: 'LONG',
|
||||
quantity: order.quantity,
|
||||
avgEntryPrice: order.price,
|
||||
currentPrice: order.price,
|
||||
marketValue: order.quantity * order.price,
|
||||
unrealizedPnL: 0,
|
||||
unrealizedPnLPercent: 0,
|
||||
leverage: order.leverage,
|
||||
stopLoss: order.stopLoss,
|
||||
takeProfit: order.takeProfit,
|
||||
openedAt: new Date(),
|
||||
signalId: order.signalId
|
||||
};
|
||||
this.positions.set(order.symbol, newPosition);
|
||||
}
|
||||
|
||||
// Deduct from cash
|
||||
this.portfolio.cashBalance -= order.price * order.quantity;
|
||||
} else if (order.side === TradeAction.SELL) {
|
||||
if (existingPosition && existingPosition.side === 'SHORT') {
|
||||
// Add to existing short position
|
||||
const newQuantity = existingPosition.quantity + order.quantity;
|
||||
const newAvgPrice = (
|
||||
(existingPosition.avgEntryPrice * existingPosition.quantity) +
|
||||
(order.price * order.quantity)
|
||||
) / newQuantity;
|
||||
|
||||
existingPosition.quantity = newQuantity;
|
||||
existingPosition.avgEntryPrice = newAvgPrice;
|
||||
} else if (existingPosition && existingPosition.side === 'LONG') {
|
||||
// Close long position
|
||||
this.closeExistingPosition(existingPosition, order);
|
||||
} else {
|
||||
// Create new short position
|
||||
const newPosition: DemoPosition = {
|
||||
id: `pos-${order.symbol}`,
|
||||
symbol: order.symbol,
|
||||
side: 'SHORT',
|
||||
quantity: order.quantity,
|
||||
avgEntryPrice: order.price,
|
||||
currentPrice: order.price,
|
||||
marketValue: order.quantity * order.price,
|
||||
unrealizedPnL: 0,
|
||||
unrealizedPnLPercent: 0,
|
||||
leverage: order.leverage,
|
||||
stopLoss: order.stopLoss,
|
||||
takeProfit: order.takeProfit,
|
||||
openedAt: new Date(),
|
||||
signalId: order.signalId
|
||||
};
|
||||
this.positions.set(order.symbol, newPosition);
|
||||
}
|
||||
|
||||
// Add to cash (for shorts, we receive cash)
|
||||
this.portfolio.cashBalance += order.price * order.quantity;
|
||||
}
|
||||
|
||||
order.status = OrderStatus.FILLED;
|
||||
order.filledAt = new Date();
|
||||
this.tradeHistory.push(order);
|
||||
|
||||
this.emit('order_filled', order);
|
||||
this.emit('position_updated', this.positions.get(order.symbol));
|
||||
}
|
||||
|
||||
/**
|
||||
* Close existing position
|
||||
*/
|
||||
private closeExistingPosition(position: DemoPosition, order: DemoOrder): void {
|
||||
const closeQuantity = Math.min(position.quantity, order.quantity);
|
||||
|
||||
// Calculate realized PnL
|
||||
let pnl: number;
|
||||
if (position.side === 'LONG') {
|
||||
pnl = (order.price - position.avgEntryPrice) * closeQuantity;
|
||||
} else {
|
||||
pnl = (position.avgEntryPrice - order.price) * closeQuantity;
|
||||
}
|
||||
|
||||
// Update order PnL
|
||||
order.pnl = pnl;
|
||||
order.closedAt = new Date();
|
||||
|
||||
// Update portfolio
|
||||
this.portfolio.realizedPnL += pnl;
|
||||
if (position.side === 'LONG') {
|
||||
this.portfolio.cashBalance += order.price * closeQuantity;
|
||||
}
|
||||
|
||||
// Update or remove position
|
||||
if (closeQuantity >= position.quantity) {
|
||||
this.positions.delete(position.symbol);
|
||||
this.emit('position_closed', position);
|
||||
} else {
|
||||
position.quantity -= closeQuantity;
|
||||
position.marketValue = position.quantity * order.price;
|
||||
}
|
||||
|
||||
// Update signal result if applicable
|
||||
if (position.signalId) {
|
||||
this.emit('signal_result', {
|
||||
signalId: position.signalId,
|
||||
pnl,
|
||||
result: pnl > 0 ? 'WIN' : pnl < 0 ? 'LOSS' : 'NEUTRAL'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check stop loss and take profit levels
|
||||
*/
|
||||
private checkStopLevels(position: DemoPosition): void {
|
||||
if (position.stopLoss && position.currentPrice <= position.stopLoss && position.side === 'LONG') {
|
||||
this.closePosition(position.symbol);
|
||||
this.emit('stop_loss_triggered', position);
|
||||
}
|
||||
|
||||
if (position.stopLoss && position.currentPrice >= position.stopLoss && position.side === 'SHORT') {
|
||||
this.closePosition(position.symbol);
|
||||
this.emit('stop_loss_triggered', position);
|
||||
}
|
||||
|
||||
if (position.takeProfit && position.currentPrice >= position.takeProfit && position.side === 'LONG') {
|
||||
this.closePosition(position.symbol);
|
||||
this.emit('take_profit_triggered', position);
|
||||
}
|
||||
|
||||
if (position.takeProfit && position.currentPrice <= position.takeProfit && position.side === 'SHORT') {
|
||||
this.closePosition(position.symbol);
|
||||
this.emit('take_profit_triggered', position);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check pending limit orders
|
||||
*/
|
||||
private checkPendingOrders(symbol: string, price: number): void {
|
||||
this.orders.forEach(order => {
|
||||
if (order.symbol !== symbol || order.status !== OrderStatus.PENDING) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (order.type === OrderType.LIMIT) {
|
||||
// For buy limit, execute when price drops to or below limit price
|
||||
if (order.side === TradeAction.BUY && price <= order.price) {
|
||||
this.executeOrder(order);
|
||||
}
|
||||
// For sell limit, execute when price rises to or above limit price
|
||||
if (order.side === TradeAction.SELL && price >= order.price) {
|
||||
this.executeOrder(order);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update portfolio value
|
||||
*/
|
||||
private updatePortfolioValue(): void {
|
||||
let totalUnrealizedPnL = 0;
|
||||
|
||||
this.positions.forEach(position => {
|
||||
totalUnrealizedPnL += position.unrealizedPnL;
|
||||
});
|
||||
|
||||
this.portfolio.unrealizedPnL = totalUnrealizedPnL;
|
||||
this.portfolio.totalValue = this.portfolio.cashBalance + totalUnrealizedPnL;
|
||||
this.portfolio.positions = Array.from(this.positions.values()).map(p => ({
|
||||
id: p.id,
|
||||
symbol: p.symbol,
|
||||
side: p.side,
|
||||
quantity: p.quantity,
|
||||
avgEntryPrice: p.avgEntryPrice,
|
||||
currentPrice: p.currentPrice,
|
||||
marketValue: p.marketValue,
|
||||
unrealizedPnL: p.unrealizedPnL,
|
||||
unrealizedPnLPercent: p.unrealizedPnLPercent,
|
||||
leverage: p.leverage,
|
||||
openedAt: p.openedAt,
|
||||
demo: true
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset demo account
|
||||
*/
|
||||
reset(initialCapital: number = 10000): void {
|
||||
this.positions.clear();
|
||||
this.orders = [];
|
||||
this.tradeHistory = [];
|
||||
this.portfolio = {
|
||||
id: 'demo-portfolio',
|
||||
name: 'Demo Portfolio',
|
||||
totalValue: initialCapital,
|
||||
cashBalance: initialCapital,
|
||||
realizedPnL: 0,
|
||||
unrealizedPnL: 0,
|
||||
positions: [],
|
||||
demo: true
|
||||
};
|
||||
|
||||
this.emit('portfolio_reset', this.portfolio);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get performance statistics
|
||||
*/
|
||||
getStatistics(): {
|
||||
totalTrades: number;
|
||||
winningTrades: number;
|
||||
losingTrades: number;
|
||||
winRate: number;
|
||||
totalPnL: number;
|
||||
averagePnL: number;
|
||||
bestTrade: number;
|
||||
worstTrade: number;
|
||||
profitFactor: number;
|
||||
} {
|
||||
const trades = this.tradeHistory.filter(t => t.pnl !== undefined);
|
||||
const wins = trades.filter(t => (t.pnl || 0) > 0);
|
||||
const losses = trades.filter(t => (t.pnl || 0) <= 0);
|
||||
|
||||
const totalPnL = trades.reduce((sum, t) => sum + (t.pnl || 0), 0);
|
||||
const grossProfit = wins.reduce((sum, t) => sum + (t.pnl || 0), 0);
|
||||
const grossLoss = Math.abs(losses.reduce((sum, t) => sum + (t.pnl || 0), 0));
|
||||
|
||||
return {
|
||||
totalTrades: trades.length,
|
||||
winningTrades: wins.length,
|
||||
losingTrades: losses.length,
|
||||
winRate: trades.length > 0 ? (wins.length / trades.length) * 100 : 0,
|
||||
totalPnL,
|
||||
averagePnL: trades.length > 0 ? totalPnL / trades.length : 0,
|
||||
bestTrade: trades.length > 0 ? Math.max(...trades.map(t => t.pnl || 0)) : 0,
|
||||
worstTrade: trades.length > 0 ? Math.min(...trades.map(t => t.pnl || 0)) : 0,
|
||||
profitFactor: grossLoss > 0 ? grossProfit / grossLoss : 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const demoTrader = new DemoTrader();
|
||||
561
src/lib/trading/news/news-aggregator.ts
Normal file
561
src/lib/trading/news/news-aggregator.ts
Normal file
@@ -0,0 +1,561 @@
|
||||
/**
|
||||
* News Aggregation Service for Mantle AI Trading Bot
|
||||
* Aggregates news from multiple sources for fundamental analysis
|
||||
*/
|
||||
|
||||
import axios from 'axios';
|
||||
import {
|
||||
NewsArticle,
|
||||
NewsSource,
|
||||
NewsQuery,
|
||||
SentimentLabel,
|
||||
APIResponse
|
||||
} from '../core/types';
|
||||
|
||||
// News API configurations
|
||||
const NEWS_APIS = {
|
||||
cryptopanic: {
|
||||
baseUrl: 'https://cryptopanic.com/api/v1',
|
||||
requiresAuth: true
|
||||
},
|
||||
coingecko: {
|
||||
baseUrl: 'https://api.coingecko.com/api/v3',
|
||||
requiresAuth: false
|
||||
},
|
||||
cryptocompare: {
|
||||
baseUrl: 'https://min-api.cryptocompare.com/data/v2',
|
||||
requiresAuth: true
|
||||
}
|
||||
};
|
||||
|
||||
// Sentiment keywords for analysis
|
||||
const SENTIMENT_KEYWORDS = {
|
||||
bullish: [
|
||||
'bullish', 'surge', 'rally', 'breakout', 'gain', 'rise', 'soar', 'pump',
|
||||
'positive', 'growth', 'adoption', 'partnership', 'launch', 'upgrade',
|
||||
'milestone', 'achievement', 'success', 'profit', 'bull run', 'moon',
|
||||
'institutional', 'investment', 'buy', 'accumulate', 'support', 'hold'
|
||||
],
|
||||
bearish: [
|
||||
'bearish', 'crash', 'dump', 'decline', 'fall', 'drop', 'sell-off',
|
||||
'negative', 'loss', 'risk', 'warning', 'concern', 'hack', 'exploit',
|
||||
'regulation', 'ban', 'restrict', 'fraud', 'scam', 'bear market',
|
||||
'liquidation', 'bankruptcy', 'investigation', 'lawsuit', 'fine'
|
||||
]
|
||||
};
|
||||
|
||||
// Category mappings
|
||||
const CATEGORIES: Record<string, string[]> = {
|
||||
'BTC': ['bitcoin', 'btc', 'satoshi', 'lightning network'],
|
||||
'ETH': ['ethereum', 'eth', 'vitalik', 'smart contract', 'defi', 'nft'],
|
||||
'DeFi': ['defi', 'yield', 'liquidity', 'staking', 'amm', 'dex'],
|
||||
'NFT': ['nft', 'opensea', 'collectible', 'digital art'],
|
||||
'Regulation': ['sec', 'regulation', 'law', 'compliance', 'government', 'ban'],
|
||||
'Exchange': ['exchange', 'binance', 'coinbase', 'kraken', 'ftx'],
|
||||
'Adoption': ['adoption', 'institutional', 'payment', 'merchant', 'country']
|
||||
};
|
||||
|
||||
export class NewsAggregator {
|
||||
private cryptopanicApiKey?: string;
|
||||
private cryptocompareApiKey?: string;
|
||||
private cache: Map<string, { data: NewsArticle[]; timestamp: number }>;
|
||||
private cacheTimeout = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
constructor(config?: {
|
||||
cryptopanicApiKey?: string;
|
||||
cryptocompareApiKey?: string;
|
||||
}) {
|
||||
this.cryptopanicApiKey = config?.cryptopanicApiKey;
|
||||
this.cryptocompareApiKey = config?.cryptocompareApiKey;
|
||||
this.cache = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch news from all configured sources
|
||||
*/
|
||||
async fetchAllNews(query: NewsQuery = {}): Promise<NewsArticle[]> {
|
||||
const cacheKey = JSON.stringify(query);
|
||||
const cached = this.cache.get(cacheKey);
|
||||
|
||||
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
|
||||
return cached.data;
|
||||
}
|
||||
|
||||
const articles: NewsArticle[] = [];
|
||||
const sources = query.sources || Object.values(NewsSource);
|
||||
|
||||
// Fetch from all sources in parallel
|
||||
const fetchPromises = sources.map(source => this.fetchFromSource(source, query));
|
||||
const results = await Promise.allSettled(fetchPromises);
|
||||
|
||||
results.forEach((result) => {
|
||||
if (result.status === 'fulfilled' && result.value) {
|
||||
articles.push(...result.value);
|
||||
}
|
||||
});
|
||||
|
||||
// Deduplicate by URL
|
||||
const uniqueArticles = this.deduplicateArticles(articles);
|
||||
|
||||
// Sort by published date
|
||||
uniqueArticles.sort((a, b) => {
|
||||
const dateA = a.publishedAt?.getTime() || 0;
|
||||
const dateB = b.publishedAt?.getTime() || 0;
|
||||
return dateB - dateA;
|
||||
});
|
||||
|
||||
// Apply limit
|
||||
const limited = query.limit ? uniqueArticles.slice(0, query.limit) : uniqueArticles;
|
||||
|
||||
// Cache results
|
||||
this.cache.set(cacheKey, { data: limited, timestamp: Date.now() });
|
||||
|
||||
return limited;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch news from a specific source
|
||||
*/
|
||||
private async fetchFromSource(
|
||||
source: NewsSource,
|
||||
query: NewsQuery
|
||||
): Promise<NewsArticle[]> {
|
||||
switch (source) {
|
||||
case NewsSource.CRYPTOPANIC:
|
||||
return this.fetchCryptoPanic(query);
|
||||
case NewsSource.COINGECKO:
|
||||
return this.fetchCoinGecko(query);
|
||||
case NewsSource.CRYPTOCOMPARE:
|
||||
return this.fetchCryptoCompare(query);
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch from CryptoPanic API
|
||||
*/
|
||||
private async fetchCryptoPanic(query: NewsQuery): Promise<NewsArticle[]> {
|
||||
if (!this.cryptopanicApiKey) {
|
||||
console.warn('CryptoPanic API key not configured');
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const params: Record<string, string> = {
|
||||
auth_token: this.cryptopanicApiKey,
|
||||
public: 'true'
|
||||
};
|
||||
|
||||
if (query.symbols?.length) {
|
||||
params.currencies = query.symbols.join(',');
|
||||
}
|
||||
|
||||
const response = await axios.get(`${NEWS_APIS.cryptopanic.baseUrl}/posts/`, {
|
||||
params,
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
if (!response.data?.results) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.results.map((post: Record<string, unknown>): NewsArticle => ({
|
||||
id: `cp-${post.id}`,
|
||||
title: post.title as string,
|
||||
content: post.body as string || undefined,
|
||||
source: NewsSource.CRYPTOPANIC,
|
||||
sourceUrl: post.url as string,
|
||||
author: post.source?.domain as string || undefined,
|
||||
category: this.categorizeArticle(post.title as string),
|
||||
sentiment: this.analyzeSentiment(`${post.title} ${post.body || ''}`),
|
||||
importance: this.calculateImportance(post),
|
||||
tags: this.extractTags(`${post.title} ${post.body || ''}`),
|
||||
publishedAt: post.published_at ? new Date(post.published_at as string) : undefined,
|
||||
fetchedAt: new Date(),
|
||||
processed: false
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('CryptoPanic fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch from CoinGecko API (status updates)
|
||||
*/
|
||||
private async fetchCoinGecko(query: NewsQuery): Promise<NewsArticle[]> {
|
||||
try {
|
||||
const params: Record<string, string | number> = {
|
||||
per_page: query.limit || 25,
|
||||
page: 1
|
||||
};
|
||||
|
||||
// CoinGecko status updates endpoint
|
||||
const response = await axios.get(
|
||||
`${NEWS_APIS.coingecko.baseUrl}/status_updates`,
|
||||
{ params, timeout: 10000 }
|
||||
);
|
||||
|
||||
if (!response.data?.status_updates) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.status_updates.map((update: Record<string, unknown>): NewsArticle => ({
|
||||
id: `cg-${update.id}`,
|
||||
title: (update.project?.name as string) + ' Status Update',
|
||||
content: update.description as string,
|
||||
source: NewsSource.COINGECKO,
|
||||
sourceUrl: `https://www.coingecko.com/en/coins/${update.project?.id}`,
|
||||
author: update.project?.name as string || 'CoinGecko',
|
||||
category: 'Project Updates',
|
||||
sentiment: this.analyzeSentiment(update.description as string),
|
||||
importance: 0.6,
|
||||
tags: [update.project?.symbol as string, 'status-update'],
|
||||
publishedAt: new Date(update.created_at as string),
|
||||
fetchedAt: new Date(),
|
||||
processed: false
|
||||
}));
|
||||
} catch (error) {
|
||||
// CoinGecko might have changed their API, return empty array
|
||||
console.error('CoinGecko fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch from CryptoCompare API
|
||||
*/
|
||||
private async fetchCryptoCompare(query: NewsQuery): Promise<NewsArticle[]> {
|
||||
if (!this.cryptocompareApiKey) {
|
||||
// Try without API key (limited rate)
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${NEWS_APIS.cryptocompare.baseUrl}/news/?lang=EN`,
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
|
||||
if (!response.data?.Data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.Data.map((article: Record<string, unknown>): NewsArticle => ({
|
||||
id: `cc-${article.id}`,
|
||||
title: article.title as string,
|
||||
content: article.body as string,
|
||||
source: NewsSource.CRYPTOCOMPARE,
|
||||
sourceUrl: article.url as string,
|
||||
author: article.source as string || 'CryptoCompare',
|
||||
category: article.category as string || 'General',
|
||||
sentiment: this.analyzeSentiment(`${article.title} ${article.body}`),
|
||||
importance: this.calculateCryptoCompareImportance(article),
|
||||
tags: (article.categories as string || '').split('|').filter(Boolean),
|
||||
publishedAt: new Date(article.published_on as number * 1000),
|
||||
fetchedAt: new Date(),
|
||||
processed: false
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('CryptoCompare fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${NEWS_APIS.cryptocompare.baseUrl}/news/?lang=EN&api_key=${this.cryptocompareApiKey}`,
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
|
||||
if (!response.data?.Data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let articles = response.data.Data.map((article: Record<string, unknown>): NewsArticle => ({
|
||||
id: `cc-${article.id}`,
|
||||
title: article.title as string,
|
||||
content: article.body as string,
|
||||
source: NewsSource.CRYPTOCOMPARE,
|
||||
sourceUrl: article.url as string,
|
||||
author: article.source as string || 'CryptoCompare',
|
||||
category: article.category as string || 'General',
|
||||
sentiment: this.analyzeSentiment(`${article.title} ${article.body}`),
|
||||
importance: this.calculateCryptoCompareImportance(article),
|
||||
tags: (article.categories as string || '').split('|').filter(Boolean),
|
||||
publishedAt: new Date(article.published_on as number * 1000),
|
||||
fetchedAt: new Date(),
|
||||
processed: false
|
||||
}));
|
||||
|
||||
// Filter by symbols if specified
|
||||
if (query.symbols?.length) {
|
||||
const symbolsLower = query.symbols.map(s => s.toLowerCase());
|
||||
articles = articles.filter(a =>
|
||||
symbolsLower.some(s =>
|
||||
a.title.toLowerCase().includes(s) ||
|
||||
a.tags?.some(t => t.toLowerCase().includes(s))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return articles;
|
||||
} catch (error) {
|
||||
console.error('CryptoCompare fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch news from custom RSS feeds
|
||||
*/
|
||||
async fetchFromRSS(feedUrl: string): Promise<NewsArticle[]> {
|
||||
try {
|
||||
// Use a simple RSS parser approach
|
||||
const response = await axios.get(feedUrl, {
|
||||
timeout: 10000,
|
||||
responseType: 'text'
|
||||
});
|
||||
|
||||
// Parse RSS XML (simplified - in production use a proper RSS parser)
|
||||
const articles: NewsArticle[] = [];
|
||||
const itemMatches = response.data.match(/<item>([\s\S]*?)<\/item>/g) || [];
|
||||
|
||||
itemMatches.forEach((item: string, index: number) => {
|
||||
const titleMatch = item.match(/<title><!\[CDATA\[(.*?)\]\]><\/title>|<title>(.*?)<\/title>/);
|
||||
const linkMatch = item.match(/<link>(.*?)<\/link>/);
|
||||
const descMatch = item.match(/<description><!\[CDATA\[(.*?)\]\]><\/description>|<description>(.*?)<\/description>/);
|
||||
const dateMatch = item.match(/<pubDate>(.*?)<\/pubDate>/);
|
||||
|
||||
if (titleMatch) {
|
||||
const title = titleMatch[1] || titleMatch[2];
|
||||
articles.push({
|
||||
id: `rss-${Date.now()}-${index}`,
|
||||
title,
|
||||
content: descMatch?.[1] || descMatch?.[2] || undefined,
|
||||
source: NewsSource.CUSTOM_RSS,
|
||||
sourceUrl: linkMatch?.[1] || feedUrl,
|
||||
category: 'RSS Feed',
|
||||
sentiment: this.analyzeSentiment(title),
|
||||
importance: 0.5,
|
||||
tags: this.extractTags(title),
|
||||
publishedAt: dateMatch ? new Date(dateMatch[1]) : undefined,
|
||||
fetchedAt: new Date(),
|
||||
processed: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return articles;
|
||||
} catch (error) {
|
||||
console.error('RSS fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze sentiment of text
|
||||
*/
|
||||
analyzeSentiment(text: string): number {
|
||||
if (!text) return 0;
|
||||
|
||||
const lowerText = text.toLowerCase();
|
||||
let bullishCount = 0;
|
||||
let bearishCount = 0;
|
||||
|
||||
// Count keyword occurrences
|
||||
SENTIMENT_KEYWORDS.bullish.forEach(keyword => {
|
||||
const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
|
||||
const matches = lowerText.match(regex);
|
||||
if (matches) bullishCount += matches.length;
|
||||
});
|
||||
|
||||
SENTIMENT_KEYWORDS.bearish.forEach(keyword => {
|
||||
const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
|
||||
const matches = lowerText.match(regex);
|
||||
if (matches) bearishCount += matches.length;
|
||||
});
|
||||
|
||||
// Calculate sentiment score (-1 to 1)
|
||||
const total = bullishCount + bearishCount;
|
||||
if (total === 0) return 0;
|
||||
|
||||
return (bullishCount - bearishCount) / total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sentiment label from score
|
||||
*/
|
||||
getSentimentLabel(score: number): SentimentLabel {
|
||||
if (score >= 0.6) return SentimentLabel.VERY_BULLISH;
|
||||
if (score >= 0.2) return SentimentLabel.BULLISH;
|
||||
if (score <= -0.6) return SentimentLabel.VERY_BEARISH;
|
||||
if (score <= -0.2) return SentimentLabel.BEARISH;
|
||||
return SentimentLabel.NEUTRAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorize article based on content
|
||||
*/
|
||||
private categorizeArticle(title: string): string {
|
||||
const lowerTitle = title.toLowerCase();
|
||||
|
||||
for (const [category, keywords] of Object.entries(CATEGORIES)) {
|
||||
if (keywords.some(keyword => lowerTitle.includes(keyword))) {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
|
||||
return 'General';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate article importance score
|
||||
*/
|
||||
private calculateImportance(article: Record<string, unknown>): number {
|
||||
let score = 0.5;
|
||||
|
||||
// Positive votes increase importance
|
||||
if (article.votes) {
|
||||
score += Math.min((article.votes as number) / 100, 0.3);
|
||||
}
|
||||
|
||||
// Comments indicate engagement
|
||||
if (article.comments) {
|
||||
score += Math.min((article.comments as number) / 50, 0.2);
|
||||
}
|
||||
|
||||
return Math.min(score, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate CryptoCompare article importance
|
||||
*/
|
||||
private calculateCryptoCompareImportance(article: Record<string, unknown>): number {
|
||||
let score = 0.5;
|
||||
|
||||
if (article.upvotes) {
|
||||
score += Math.min((article.upvotes as number) / 100, 0.3);
|
||||
}
|
||||
|
||||
if (article.downvotes) {
|
||||
score -= Math.min((article.downvotes as number) / 100, 0.2);
|
||||
}
|
||||
|
||||
return Math.max(0, Math.min(score, 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract tags from text
|
||||
*/
|
||||
private extractTags(text: string): string[] {
|
||||
const tags: string[] = [];
|
||||
const lowerText = text.toLowerCase();
|
||||
|
||||
// Extract mentioned cryptocurrencies
|
||||
const cryptoPatterns = [
|
||||
/\b(btc|bitcoin|eth|ethereum|sol|solana|ada|cardano|dot|polkadot|avax|avalanche)\b/gi,
|
||||
/\$[A-Z]{2,10}/g // Ticker symbols like $BTC, $ETH
|
||||
];
|
||||
|
||||
cryptoPatterns.forEach(pattern => {
|
||||
const matches = text.match(pattern);
|
||||
if (matches) {
|
||||
matches.forEach(m => tags.push(m.toUpperCase().replace('$', '')));
|
||||
}
|
||||
});
|
||||
|
||||
// Check for category keywords
|
||||
Object.entries(CATEGORIES).forEach(([category, keywords]) => {
|
||||
if (keywords.some(kw => lowerText.includes(kw))) {
|
||||
tags.push(category);
|
||||
}
|
||||
});
|
||||
|
||||
return [...new Set(tags)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicate articles by URL
|
||||
*/
|
||||
private deduplicateArticles(articles: NewsArticle[]): NewsArticle[] {
|
||||
const seen = new Map<string, NewsArticle>();
|
||||
|
||||
articles.forEach(article => {
|
||||
const key = article.sourceUrl || article.title;
|
||||
if (!seen.has(key)) {
|
||||
seen.set(key, article);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(seen.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get market-moving news (high importance)
|
||||
*/
|
||||
async getMarketMovingNews(limit: number = 10): Promise<NewsArticle[]> {
|
||||
const articles = await this.fetchAllNews({ limit: limit * 2 });
|
||||
|
||||
return articles
|
||||
.filter(a => (a.importance || 0) >= 0.7 || Math.abs(a.sentiment || 0) >= 0.5)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get news for specific trading pair
|
||||
*/
|
||||
async getNewsForSymbol(symbol: string, limit: number = 20): Promise<NewsArticle[]> {
|
||||
// Normalize symbol (BTCUSDT -> BTC)
|
||||
const baseAsset = symbol.replace('USDT', '').replace('USD', '').toUpperCase();
|
||||
|
||||
return this.fetchAllNews({
|
||||
symbols: [baseAsset],
|
||||
limit
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get aggregated sentiment for symbol
|
||||
*/
|
||||
async getSymbolSentiment(symbol: string): Promise<{
|
||||
overallSentiment: number;
|
||||
sentimentLabel: SentimentLabel;
|
||||
articleCount: number;
|
||||
bullishCount: number;
|
||||
bearishCount: number;
|
||||
neutralCount: number;
|
||||
topArticles: NewsArticle[];
|
||||
}> {
|
||||
const articles = await this.getNewsForSymbol(symbol);
|
||||
|
||||
let bullishCount = 0;
|
||||
let bearishCount = 0;
|
||||
let neutralCount = 0;
|
||||
let totalSentiment = 0;
|
||||
|
||||
articles.forEach(article => {
|
||||
const sentiment = article.sentiment || 0;
|
||||
totalSentiment += sentiment;
|
||||
|
||||
if (sentiment > 0.2) bullishCount++;
|
||||
else if (sentiment < -0.2) bearishCount++;
|
||||
else neutralCount++;
|
||||
});
|
||||
|
||||
const overallSentiment = articles.length > 0
|
||||
? totalSentiment / articles.length
|
||||
: 0;
|
||||
|
||||
return {
|
||||
overallSentiment,
|
||||
sentimentLabel: this.getSentimentLabel(overallSentiment),
|
||||
articleCount: articles.length,
|
||||
bullishCount,
|
||||
bearishCount,
|
||||
neutralCount,
|
||||
topArticles: articles.slice(0, 5)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const newsAggregator = new NewsAggregator();
|
||||
915
src/lib/trading/signals/signal-engine.ts
Normal file
915
src/lib/trading/signals/signal-engine.ts
Normal file
@@ -0,0 +1,915 @@
|
||||
/**
|
||||
* Signal Generation Engine for Mantle AI Trading Bot
|
||||
* AI-powered signal generation with comprehensive analysis and rating system
|
||||
*/
|
||||
|
||||
import ZAI from 'z-ai-web-dev-sdk';
|
||||
import {
|
||||
Signal,
|
||||
SignalGenerationInput,
|
||||
SignalGenerationOutput,
|
||||
SignalAnalysis,
|
||||
TechnicalAnalysis,
|
||||
FundamentalAnalysis,
|
||||
SentimentAnalysis,
|
||||
RiskAssessment,
|
||||
TradeAction,
|
||||
RiskLevel,
|
||||
SentimentLabel,
|
||||
TimeFrame,
|
||||
MarketDataPoint,
|
||||
NewsArticle
|
||||
} from '../core/types';
|
||||
import { vectorStore } from '../../vector/vector-store';
|
||||
import { newsAggregator } from '../news/news-aggregator';
|
||||
|
||||
// Technical analysis helpers
|
||||
function calculateSMA(data: number[], period: number): number[] {
|
||||
const result: number[] = [];
|
||||
for (let i = period - 1; i < data.length; i++) {
|
||||
const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
|
||||
result.push(sum / period);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function calculateEMA(data: number[], period: number): number[] {
|
||||
const result: number[] = [];
|
||||
const multiplier = 2 / (period + 1);
|
||||
result[0] = data[0];
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
result[i] = (data[i] - result[i - 1]) * multiplier + result[i - 1];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function calculateRSI(closes: number[], period: number = 14): number {
|
||||
if (closes.length < period + 1) return 50;
|
||||
|
||||
let gains = 0;
|
||||
let losses = 0;
|
||||
|
||||
for (let i = closes.length - period; i < closes.length; i++) {
|
||||
const diff = closes[i] - closes[i - 1];
|
||||
if (diff > 0) gains += diff;
|
||||
else losses += Math.abs(diff);
|
||||
}
|
||||
|
||||
const avgGain = gains / period;
|
||||
const avgLoss = losses / period;
|
||||
|
||||
if (avgLoss === 0) return 100;
|
||||
|
||||
const rs = avgGain / avgLoss;
|
||||
return 100 - (100 / (1 + rs));
|
||||
}
|
||||
|
||||
function calculateMACD(closes: number[]): { macd: number; signal: number; histogram: number } {
|
||||
const ema12 = calculateEMA(closes, 12);
|
||||
const ema26 = calculateEMA(closes, 26);
|
||||
const macd = ema12[ema12.length - 1] - ema26[ema26.length - 1];
|
||||
const signal = calculateEMA([...Array(8).fill(macd), macd], 9)[8];
|
||||
const histogram = macd - signal;
|
||||
|
||||
return { macd, signal, histogram };
|
||||
}
|
||||
|
||||
function findSupportResistance(
|
||||
highs: number[],
|
||||
lows: number[],
|
||||
closes: number[]
|
||||
): { support: number[]; resistance: number[] } {
|
||||
const support: number[] = [];
|
||||
const resistance: number[] = [];
|
||||
|
||||
for (let i = 2; i < highs.length - 2; i++) {
|
||||
// Support: local low
|
||||
if (lows[i] < lows[i - 1] && lows[i] < lows[i - 2] &&
|
||||
lows[i] < lows[i + 1] && lows[i] < lows[i + 2]) {
|
||||
support.push(lows[i]);
|
||||
}
|
||||
|
||||
// Resistance: local high
|
||||
if (highs[i] > highs[i - 1] && highs[i] > highs[i - 2] &&
|
||||
highs[i] > highs[i + 1] && highs[i] > highs[i + 2]) {
|
||||
resistance.push(highs[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort and deduplicate
|
||||
support.sort((a, b) => b - a);
|
||||
resistance.sort((a, b) => a - b);
|
||||
|
||||
return {
|
||||
support: [...new Set(support)].slice(0, 5),
|
||||
resistance: [...new Set(resistance)].slice(0, 5)
|
||||
};
|
||||
}
|
||||
|
||||
function detectPatterns(
|
||||
opens: number[],
|
||||
highs: number[],
|
||||
lows: number[],
|
||||
closes: number[]
|
||||
): string[] {
|
||||
const patterns: string[] = [];
|
||||
const len = closes.length;
|
||||
|
||||
if (len < 5) return patterns;
|
||||
|
||||
// Doji
|
||||
const lastOpen = opens[len - 1];
|
||||
const lastClose = closes[len - 1];
|
||||
const lastHigh = highs[len - 1];
|
||||
const lastLow = lows[len - 1];
|
||||
const bodySize = Math.abs(lastClose - lastOpen);
|
||||
const range = lastHigh - lastLow;
|
||||
|
||||
if (bodySize < range * 0.1) {
|
||||
patterns.push('DOJI');
|
||||
}
|
||||
|
||||
// Hammer
|
||||
if (bodySize < range * 0.3 &&
|
||||
lastLow < Math.min(lastOpen, lastClose) - range * 0.6) {
|
||||
patterns.push('HAMMER');
|
||||
}
|
||||
|
||||
// Bullish Engulfing
|
||||
if (len >= 2) {
|
||||
const prevClose = closes[len - 2];
|
||||
const prevOpen = opens[len - 2];
|
||||
|
||||
if (prevClose < prevOpen && // Previous bearish
|
||||
lastClose > lastOpen && // Current bullish
|
||||
lastOpen < prevClose && // Opens below prev close
|
||||
lastClose > prevOpen) { // Closes above prev open
|
||||
patterns.push('BULLISH_ENGULFING');
|
||||
}
|
||||
}
|
||||
|
||||
// Bearish Engulfing
|
||||
if (len >= 2) {
|
||||
const prevClose = closes[len - 2];
|
||||
const prevOpen = opens[len - 2];
|
||||
|
||||
if (prevClose > prevOpen && // Previous bullish
|
||||
lastClose < lastOpen && // Current bearish
|
||||
lastOpen > prevClose && // Opens above prev close
|
||||
lastClose < prevOpen) { // Closes below prev open
|
||||
patterns.push('BEARISH_ENGULFING');
|
||||
}
|
||||
}
|
||||
|
||||
// Morning Star / Evening Star
|
||||
if (len >= 3) {
|
||||
const firstClose = closes[len - 3];
|
||||
const firstOpen = opens[len - 3];
|
||||
const secondClose = closes[len - 2];
|
||||
const secondOpen = opens[len - 2];
|
||||
|
||||
if (firstClose < firstOpen && // First bearish
|
||||
Math.abs(secondClose - secondOpen) < (secondHigh(secondOpen, secondClose) - secondLow(secondOpen, secondClose)) * 0.3 && // Small body
|
||||
lastClose > lastOpen && lastClose > (firstOpen + firstClose) / 2) { // Bullish third
|
||||
patterns.push('MORNING_STAR');
|
||||
}
|
||||
}
|
||||
|
||||
return patterns;
|
||||
}
|
||||
|
||||
function secondHigh(open: number, close: number): number {
|
||||
return Math.max(open, close);
|
||||
}
|
||||
|
||||
function secondLow(open: number, close: number): number {
|
||||
return Math.min(open, close);
|
||||
}
|
||||
|
||||
export class SignalEngine {
|
||||
private zai: Awaited<ReturnType<typeof ZAI.create>> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.initAI();
|
||||
}
|
||||
|
||||
private async initAI(): Promise<void> {
|
||||
try {
|
||||
this.zai = await ZAI.create();
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate trading signal with comprehensive analysis
|
||||
*/
|
||||
async generateSignal(input: SignalGenerationInput): Promise<SignalGenerationOutput> {
|
||||
// Perform technical analysis
|
||||
const technicalAnalysis = this.performTechnicalAnalysis(input.marketData);
|
||||
|
||||
// Perform fundamental analysis
|
||||
const fundamentalAnalysis = await this.performFundamentalAnalysis(
|
||||
input.symbol,
|
||||
input.newsArticles
|
||||
);
|
||||
|
||||
// Perform sentiment analysis
|
||||
const sentimentAnalysis = await this.performSentimentAnalysis(
|
||||
input.symbol,
|
||||
input.newsArticles
|
||||
);
|
||||
|
||||
// Calculate overall score
|
||||
const overallScore = this.calculateOverallScore(
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis
|
||||
);
|
||||
|
||||
// Determine action
|
||||
const action = this.determineAction(
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis,
|
||||
overallScore
|
||||
);
|
||||
|
||||
// Generate reasoning using AI
|
||||
const reasoning = await this.generateReasoning(
|
||||
input.symbol,
|
||||
action,
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis
|
||||
);
|
||||
|
||||
// Calculate confidence
|
||||
const confidence = this.calculateConfidence(
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis,
|
||||
overallScore
|
||||
);
|
||||
|
||||
// Assess risk
|
||||
const riskAssessment = this.assessRisk(
|
||||
input.symbol,
|
||||
action,
|
||||
technicalAnalysis,
|
||||
input.marketData
|
||||
);
|
||||
|
||||
// Calculate targets
|
||||
const currentPrice = input.marketData[input.marketData.length - 1]?.close || 0;
|
||||
const { priceTarget, stopLoss, takeProfit } = this.calculateTargets(
|
||||
action,
|
||||
currentPrice,
|
||||
technicalAnalysis,
|
||||
riskAssessment
|
||||
);
|
||||
|
||||
// Build signal
|
||||
const signal: Omit<Signal, 'id' | 'createdAt' | 'updatedAt'> = {
|
||||
symbol: input.symbol,
|
||||
action,
|
||||
confidence,
|
||||
rating: 0,
|
||||
priceTarget,
|
||||
stopLoss,
|
||||
takeProfit,
|
||||
reasoning,
|
||||
newsSources: input.newsArticles.slice(0, 5).map(a => a.sourceUrl).filter(Boolean) as string[],
|
||||
sentimentScore: sentimentAnalysis.overallSentiment,
|
||||
technicalScore: technicalAnalysis.score,
|
||||
fundamentalScore: fundamentalAnalysis.score,
|
||||
status: 'PENDING' as Signal['status'],
|
||||
demo: false
|
||||
};
|
||||
|
||||
// Build analysis
|
||||
const analysis: SignalAnalysis = {
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis,
|
||||
overallScore,
|
||||
keyFactors: this.extractKeyFactors(
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis
|
||||
),
|
||||
warnings: this.generateWarnings(
|
||||
technicalAnalysis,
|
||||
fundamentalAnalysis,
|
||||
sentimentAnalysis,
|
||||
riskAssessment
|
||||
)
|
||||
};
|
||||
|
||||
return {
|
||||
signal,
|
||||
analysis,
|
||||
riskAssessment
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform technical analysis on market data
|
||||
*/
|
||||
private performTechnicalAnalysis(data: MarketDataPoint[]): TechnicalAnalysis {
|
||||
if (data.length < 50) {
|
||||
return {
|
||||
trend: 'SIDEWAYS',
|
||||
trendStrength: 0,
|
||||
supportLevels: [],
|
||||
resistanceLevels: [],
|
||||
indicators: {},
|
||||
patterns: [],
|
||||
score: 0.5
|
||||
};
|
||||
}
|
||||
|
||||
const closes = data.map(d => d.close);
|
||||
const highs = data.map(d => d.high);
|
||||
const lows = data.map(d => d.low);
|
||||
const opens = data.map(d => d.open);
|
||||
const volumes = data.map(d => d.volume);
|
||||
|
||||
// Calculate indicators
|
||||
const sma20 = calculateSMA(closes, 20);
|
||||
const sma50 = calculateSMA(closes, 50);
|
||||
const ema12 = calculateEMA(closes, 12);
|
||||
const ema26 = calculateEMA(closes, 26);
|
||||
const rsi = calculateRSI(closes);
|
||||
const macd = calculateMACD(closes);
|
||||
|
||||
// Determine trend
|
||||
const lastClose = closes[closes.length - 1];
|
||||
const lastSma20 = sma20[sma20.length - 1];
|
||||
const lastSma50 = sma50[sma50.length - 1];
|
||||
|
||||
let trend: 'BULLISH' | 'BEARISH' | 'SIDEWAYS' = 'SIDEWAYS';
|
||||
let trendStrength = 0;
|
||||
|
||||
if (lastClose > lastSma20 && lastSma20 > lastSma50) {
|
||||
trend = 'BULLISH';
|
||||
trendStrength = Math.min((lastClose - lastSma50) / lastSma50, 1);
|
||||
} else if (lastClose < lastSma20 && lastSma20 < lastSma50) {
|
||||
trend = 'BEARISH';
|
||||
trendStrength = Math.min((lastSma50 - lastClose) / lastSma50, 1);
|
||||
}
|
||||
|
||||
// Find support and resistance
|
||||
const { support, resistance } = findSupportResistance(highs, lows, closes);
|
||||
|
||||
// Detect patterns
|
||||
const patterns = detectPatterns(opens, highs, lows, closes);
|
||||
|
||||
// Calculate score
|
||||
let score = 0.5;
|
||||
|
||||
// RSI contribution
|
||||
if (rsi > 70) score -= 0.15; // Overbought
|
||||
else if (rsi < 30) score += 0.15; // Oversold
|
||||
else if (rsi > 50) score += 0.1;
|
||||
|
||||
// MACD contribution
|
||||
if (macd.histogram > 0) score += 0.1;
|
||||
else score -= 0.1;
|
||||
|
||||
// Trend contribution
|
||||
if (trend === 'BULLISH') score += 0.15 * trendStrength;
|
||||
else if (trend === 'BEARISH') score -= 0.15 * trendStrength;
|
||||
|
||||
// Pattern contribution
|
||||
if (patterns.includes('HAMMER') || patterns.includes('MORNING_STAR') || patterns.includes('BULLISH_ENGULFING')) {
|
||||
score += 0.1;
|
||||
}
|
||||
if (patterns.includes('BEARISH_ENGULFING')) {
|
||||
score -= 0.1;
|
||||
}
|
||||
|
||||
// Volume analysis
|
||||
const avgVolume = volumes.slice(-20).reduce((a, b) => a + b, 0) / 20;
|
||||
const lastVolume = volumes[volumes.length - 1];
|
||||
if (lastVolume > avgVolume * 1.5) {
|
||||
// High volume confirms trend
|
||||
if (trend === 'BULLISH') score += 0.05;
|
||||
else if (trend === 'BEARISH') score -= 0.05;
|
||||
}
|
||||
|
||||
return {
|
||||
trend,
|
||||
trendStrength,
|
||||
supportLevels: support,
|
||||
resistanceLevels: resistance,
|
||||
indicators: {
|
||||
rsi,
|
||||
macd: macd.macd,
|
||||
macdSignal: macd.signal,
|
||||
macdHistogram: macd.histogram,
|
||||
sma20: lastSma20,
|
||||
sma50: lastSma50,
|
||||
ema12: ema12[ema12.length - 1],
|
||||
ema26: ema26[ema26.length - 1]
|
||||
},
|
||||
patterns,
|
||||
score: Math.max(0, Math.min(1, score))
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform fundamental analysis
|
||||
*/
|
||||
private async performFundamentalAnalysis(
|
||||
symbol: string,
|
||||
newsArticles: NewsArticle[]
|
||||
): Promise<FundamentalAnalysis> {
|
||||
// Get news sentiment
|
||||
const newsImpact = this.calculateNewsImpact(newsArticles);
|
||||
|
||||
// Extract market events
|
||||
const marketEvents = this.extractMarketEvents(newsArticles);
|
||||
|
||||
// Economic factors
|
||||
const economicFactors = this.identifyEconomicFactors(newsArticles);
|
||||
|
||||
// Calculate score based on news
|
||||
let score = 0.5;
|
||||
|
||||
// Positive events boost score
|
||||
marketEvents.forEach(event => {
|
||||
if (event.toLowerCase().includes('partnership') ||
|
||||
event.toLowerCase().includes('adoption') ||
|
||||
event.toLowerCase().includes('launch')) {
|
||||
score += 0.05;
|
||||
}
|
||||
if (event.toLowerCase().includes('hack') ||
|
||||
event.toLowerCase().includes('regulation') ||
|
||||
event.toLowerCase().includes('ban')) {
|
||||
score -= 0.05;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
newsImpact,
|
||||
marketEvents,
|
||||
economicFactors,
|
||||
score: Math.max(0, Math.min(1, score))
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform sentiment analysis
|
||||
*/
|
||||
private async performSentimentAnalysis(
|
||||
symbol: string,
|
||||
newsArticles: NewsArticle[]
|
||||
): Promise<SentimentAnalysis> {
|
||||
// Get sentiment from news aggregator
|
||||
const symbolSentiment = await newsAggregator.getSymbolSentiment(symbol);
|
||||
|
||||
// Get contextual sentiment from vector store
|
||||
const contextSentiment = await vectorStore.analyzeSentimentWithContext(
|
||||
`${symbol} trading analysis`
|
||||
);
|
||||
|
||||
// Combine sentiments
|
||||
const overallSentiment = (
|
||||
symbolSentiment.overallSentiment +
|
||||
contextSentiment.sentiment
|
||||
) / 2;
|
||||
|
||||
// Determine label
|
||||
let sentimentLabel = SentimentLabel.NEUTRAL;
|
||||
if (overallSentiment >= 0.3) sentimentLabel = SentimentLabel.BULLISH;
|
||||
else if (overallSentiment >= 0.6) sentimentLabel = SentimentLabel.VERY_BULLISH;
|
||||
else if (overallSentiment <= -0.3) sentimentLabel = SentimentLabel.BEARISH;
|
||||
else if (overallSentiment <= -0.6) sentimentLabel = SentimentLabel.VERY_BEARISH;
|
||||
|
||||
// Extract key topics
|
||||
const keyTopics = this.extractKeyTopics(newsArticles);
|
||||
|
||||
return {
|
||||
overallSentiment,
|
||||
sentimentLabel,
|
||||
newsSentiment: symbolSentiment.overallSentiment,
|
||||
socialSentiment: contextSentiment.sentiment,
|
||||
keyTopics,
|
||||
trendingKeywords: keyTopics
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate overall score
|
||||
*/
|
||||
private calculateOverallScore(
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis
|
||||
): number {
|
||||
const weights = {
|
||||
technical: 0.4,
|
||||
fundamental: 0.3,
|
||||
sentiment: 0.3
|
||||
};
|
||||
|
||||
return (
|
||||
technical.score * weights.technical +
|
||||
fundamental.score * weights.fundamental +
|
||||
((sentiment.overallSentiment + 1) / 2) * weights.sentiment
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine trading action
|
||||
*/
|
||||
private determineAction(
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis,
|
||||
overallScore: number
|
||||
): TradeAction {
|
||||
// Strong buy conditions
|
||||
if (overallScore >= 0.7 &&
|
||||
technical.trend === 'BULLISH' &&
|
||||
sentiment.sentimentLabel === SentimentLabel.BULLISH) {
|
||||
return TradeAction.BUY;
|
||||
}
|
||||
|
||||
// Strong sell conditions
|
||||
if (overallScore <= 0.3 &&
|
||||
technical.trend === 'BEARISH' &&
|
||||
sentiment.sentimentLabel === SentimentLabel.BEARISH) {
|
||||
return TradeAction.SELL;
|
||||
}
|
||||
|
||||
// Moderate buy
|
||||
if (overallScore >= 0.6 &&
|
||||
technical.indicators.rsi < 70 &&
|
||||
sentiment.overallSentiment > 0) {
|
||||
return TradeAction.BUY;
|
||||
}
|
||||
|
||||
// Moderate sell
|
||||
if (overallScore <= 0.4 &&
|
||||
technical.indicators.rsi > 30 &&
|
||||
sentiment.overallSentiment < 0) {
|
||||
return TradeAction.SELL;
|
||||
}
|
||||
|
||||
return TradeAction.HOLD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate AI reasoning
|
||||
*/
|
||||
private async generateReasoning(
|
||||
symbol: string,
|
||||
action: TradeAction,
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis
|
||||
): Promise<string> {
|
||||
if (!this.zai) {
|
||||
return this.generateBasicReasoning(
|
||||
symbol, action, technical, fundamental, sentiment
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const prompt = `Analyze the following trading signal for ${symbol} and provide a brief, professional reasoning (2-3 sentences):
|
||||
|
||||
Action: ${action}
|
||||
Technical Analysis: Trend is ${technical.trend} with ${Math.round(technical.trendStrength * 100)}% strength. RSI: ${technical.indicators.rsi?.toFixed(1) || 'N/A'}. Patterns detected: ${technical.patterns.join(', ') || 'None'}.
|
||||
Fundamental Analysis: News impact score: ${(fundamental.newsImpact * 100).toFixed(0)}%. Key events: ${fundamental.marketEvents.slice(0, 3).join(', ') || 'None significant'}.
|
||||
Sentiment: ${sentiment.sentimentLabel} (${(sentiment.overallSentiment * 100).toFixed(0)}%)
|
||||
|
||||
Provide a concise trading rationale:`;
|
||||
|
||||
const completion = await this.zai.chat.completions.create({
|
||||
messages: [
|
||||
{ role: 'system', content: 'You are a professional trading analyst. Provide concise, actionable insights.' },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
max_tokens: 200,
|
||||
temperature: 0.3
|
||||
});
|
||||
|
||||
return completion.choices[0]?.message?.content ||
|
||||
this.generateBasicReasoning(symbol, action, technical, fundamental, sentiment);
|
||||
} catch (error) {
|
||||
return this.generateBasicReasoning(symbol, action, technical, fundamental, sentiment);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate basic reasoning without AI
|
||||
*/
|
||||
private generateBasicReasoning(
|
||||
symbol: string,
|
||||
action: TradeAction,
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis
|
||||
): string {
|
||||
const reasons: string[] = [];
|
||||
|
||||
if (technical.trend === 'BULLISH' && action === TradeAction.BUY) {
|
||||
reasons.push(`Bullish trend detected with ${Math.round(technical.trendStrength * 100)}% strength`);
|
||||
}
|
||||
if (technical.trend === 'BEARISH' && action === TradeAction.SELL) {
|
||||
reasons.push(`Bearish trend detected with ${Math.round(technical.trendStrength * 100)}% strength`);
|
||||
}
|
||||
if (technical.indicators.rsi && technical.indicators.rsi < 30) {
|
||||
reasons.push('RSI indicates oversold conditions');
|
||||
}
|
||||
if (technical.indicators.rsi && technical.indicators.rsi > 70) {
|
||||
reasons.push('RSI indicates overbought conditions');
|
||||
}
|
||||
if (sentiment.sentimentLabel === SentimentLabel.BULLISH) {
|
||||
reasons.push('Market sentiment is bullish');
|
||||
}
|
||||
if (sentiment.sentimentLabel === SentimentLabel.BEARISH) {
|
||||
reasons.push('Market sentiment is bearish');
|
||||
}
|
||||
|
||||
return reasons.length > 0
|
||||
? `${symbol}: ${action} signal. ${reasons.join('. ')}.`
|
||||
: `${symbol}: ${action} signal based on mixed indicators.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate confidence
|
||||
*/
|
||||
private calculateConfidence(
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis,
|
||||
overallScore: number
|
||||
): number {
|
||||
// Base confidence from overall score
|
||||
let confidence = Math.abs(overallScore - 0.5) * 2;
|
||||
|
||||
// Boost confidence when all indicators align
|
||||
const technicalDirection = technical.score > 0.5 ? 1 : -1;
|
||||
const sentimentDirection = sentiment.overallSentiment > 0 ? 1 : -1;
|
||||
|
||||
if (technicalDirection === sentimentDirection) {
|
||||
confidence *= 1.2;
|
||||
}
|
||||
|
||||
// Reduce confidence during high volatility (wide support/resistance range)
|
||||
if (technical.supportLevels.length > 0 && technical.resistanceLevels.length > 0) {
|
||||
const range = technical.resistanceLevels[0] - technical.supportLevels[0];
|
||||
const midPrice = (technical.resistanceLevels[0] + technical.supportLevels[0]) / 2;
|
||||
const rangePercent = range / midPrice;
|
||||
|
||||
if (rangePercent > 0.1) {
|
||||
confidence *= 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.min(1, confidence);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assess risk
|
||||
*/
|
||||
private assessRisk(
|
||||
symbol: string,
|
||||
action: TradeAction,
|
||||
technical: TechnicalAnalysis,
|
||||
marketData: MarketDataPoint[]
|
||||
): RiskAssessment {
|
||||
const lastPrice = marketData[marketData.length - 1]?.close || 0;
|
||||
|
||||
// Calculate volatility
|
||||
const returns = marketData.slice(-20).map((d, i, arr) => {
|
||||
if (i === 0) return 0;
|
||||
return (d.close - arr[i - 1].close) / arr[i - 1].close;
|
||||
});
|
||||
const volatility = Math.sqrt(
|
||||
returns.reduce((sum, r) => sum + r * r, 0) / returns.length
|
||||
);
|
||||
|
||||
// Determine risk level
|
||||
let riskLevel = RiskLevel.MODERATE;
|
||||
let riskScore = 0.5;
|
||||
|
||||
if (volatility > 0.05) {
|
||||
riskLevel = RiskLevel.AGGRESSIVE;
|
||||
riskScore = 0.7;
|
||||
} else if (volatility < 0.02) {
|
||||
riskLevel = RiskLevel.CONSERVATIVE;
|
||||
riskScore = 0.3;
|
||||
}
|
||||
|
||||
// Calculate suggested levels
|
||||
const suggestedStopLoss = action === TradeAction.BUY
|
||||
? lastPrice * (1 - volatility * 2)
|
||||
: lastPrice * (1 + volatility * 2);
|
||||
|
||||
const suggestedTakeProfit = action === TradeAction.BUY
|
||||
? lastPrice * (1 + volatility * 3)
|
||||
: lastPrice * (1 - volatility * 3);
|
||||
|
||||
// Risk factors
|
||||
const riskFactors: string[] = [];
|
||||
if (technical.indicators.rsi && technical.indicators.rsi > 70) {
|
||||
riskFactors.push('Overbought conditions');
|
||||
}
|
||||
if (technical.indicators.rsi && technical.indicators.rsi < 30) {
|
||||
riskFactors.push('Oversold conditions');
|
||||
}
|
||||
if (volatility > 0.04) {
|
||||
riskFactors.push('High market volatility');
|
||||
}
|
||||
if (technical.patterns.includes('DOJI')) {
|
||||
riskFactors.push('Indecision pattern detected');
|
||||
}
|
||||
|
||||
return {
|
||||
riskScore,
|
||||
riskLevel,
|
||||
maxRecommendedPosition: lastPrice * 10, // $10 worth at current price
|
||||
suggestedStopLoss,
|
||||
suggestedTakeProfit,
|
||||
riskFactors,
|
||||
marketVolatility: volatility,
|
||||
liquidityRisk: 0.2 // Assume good liquidity for major pairs
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate price targets
|
||||
*/
|
||||
private calculateTargets(
|
||||
action: TradeAction,
|
||||
currentPrice: number,
|
||||
technical: TechnicalAnalysis,
|
||||
risk: RiskAssessment
|
||||
): { priceTarget: number; stopLoss: number; takeProfit: number } {
|
||||
if (action === TradeAction.HOLD) {
|
||||
return {
|
||||
priceTarget: currentPrice,
|
||||
stopLoss: currentPrice,
|
||||
takeProfit: currentPrice
|
||||
};
|
||||
}
|
||||
|
||||
// Use support/resistance if available
|
||||
let priceTarget = risk.suggestedTakeProfit;
|
||||
let stopLoss = risk.suggestedStopLoss;
|
||||
|
||||
if (action === TradeAction.BUY) {
|
||||
// Target nearest resistance
|
||||
if (technical.resistanceLevels.length > 0) {
|
||||
priceTarget = Math.min(
|
||||
technical.resistanceLevels[0],
|
||||
risk.suggestedTakeProfit
|
||||
);
|
||||
}
|
||||
// Stop at nearest support
|
||||
if (technical.supportLevels.length > 0) {
|
||||
stopLoss = Math.max(
|
||||
technical.supportLevels[0],
|
||||
risk.suggestedStopLoss
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Target nearest support
|
||||
if (technical.supportLevels.length > 0) {
|
||||
priceTarget = Math.max(
|
||||
technical.supportLevels[0],
|
||||
risk.suggestedTakeProfit
|
||||
);
|
||||
}
|
||||
// Stop at nearest resistance
|
||||
if (technical.resistanceLevels.length > 0) {
|
||||
stopLoss = Math.min(
|
||||
technical.resistanceLevels[0],
|
||||
risk.suggestedStopLoss
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const takeProfit = priceTarget;
|
||||
|
||||
return { priceTarget, stopLoss, takeProfit };
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private calculateNewsImpact(articles: NewsArticle[]): number {
|
||||
if (articles.length === 0) return 0;
|
||||
|
||||
const totalImportance = articles.reduce(
|
||||
(sum, a) => sum + (a.importance || 0.5),
|
||||
0
|
||||
);
|
||||
|
||||
return Math.min(totalImportance / articles.length, 1);
|
||||
}
|
||||
|
||||
private extractMarketEvents(articles: NewsArticle[]): string[] {
|
||||
return articles
|
||||
.filter(a => a.importance && a.importance > 0.6)
|
||||
.slice(0, 10)
|
||||
.map(a => a.title);
|
||||
}
|
||||
|
||||
private identifyEconomicFactors(articles: NewsArticle[]): string[] {
|
||||
const factors: string[] = [];
|
||||
const keywords = ['inflation', 'interest rate', 'fed', 'regulation', 'adoption', 'institutional'];
|
||||
|
||||
articles.forEach(article => {
|
||||
const text = article.title.toLowerCase();
|
||||
keywords.forEach(kw => {
|
||||
if (text.includes(kw)) {
|
||||
factors.push(kw);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return [...new Set(factors)];
|
||||
}
|
||||
|
||||
private extractKeyTopics(articles: NewsArticle[]): string[] {
|
||||
const topics: string[] = [];
|
||||
|
||||
articles.forEach(article => {
|
||||
if (article.tags) {
|
||||
topics.push(...article.tags);
|
||||
}
|
||||
});
|
||||
|
||||
// Return most frequent topics
|
||||
const frequency: Record<string, number> = {};
|
||||
topics.forEach(t => {
|
||||
frequency[t] = (frequency[t] || 0) + 1;
|
||||
});
|
||||
|
||||
return Object.entries(frequency)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([topic]) => topic);
|
||||
}
|
||||
|
||||
private extractKeyFactors(
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis
|
||||
): string[] {
|
||||
const factors: string[] = [];
|
||||
|
||||
if (technical.trend !== 'SIDEWAYS') {
|
||||
factors.push(`${technical.trend} trend (${Math.round(technical.trendStrength * 100)}% strength)`);
|
||||
}
|
||||
if (technical.patterns.length > 0) {
|
||||
factors.push(`Patterns: ${technical.patterns.join(', ')}`);
|
||||
}
|
||||
if (fundamental.marketEvents.length > 0) {
|
||||
factors.push(`Key events: ${fundamental.marketEvents.slice(0, 2).join(', ')}`);
|
||||
}
|
||||
if (sentiment.sentimentLabel !== SentimentLabel.NEUTRAL) {
|
||||
factors.push(`Sentiment: ${sentiment.sentimentLabel}`);
|
||||
}
|
||||
|
||||
return factors;
|
||||
}
|
||||
|
||||
private generateWarnings(
|
||||
technical: TechnicalAnalysis,
|
||||
fundamental: FundamentalAnalysis,
|
||||
sentiment: SentimentAnalysis,
|
||||
risk: RiskAssessment
|
||||
): string[] {
|
||||
const warnings: string[] = [];
|
||||
|
||||
if (technical.indicators.rsi && technical.indicators.rsi > 70) {
|
||||
warnings.push('RSI indicates overbought conditions - potential reversal risk');
|
||||
}
|
||||
if (technical.indicators.rsi && technical.indicators.rsi < 30) {
|
||||
warnings.push('RSI indicates oversold conditions - may continue falling');
|
||||
}
|
||||
if (risk.marketVolatility > 0.05) {
|
||||
warnings.push('High market volatility - use smaller position sizes');
|
||||
}
|
||||
if (risk.riskFactors.includes('Indecision pattern detected')) {
|
||||
warnings.push('Market showing indecision - wait for clearer signals');
|
||||
}
|
||||
if (fundamental.marketEvents.some(e =>
|
||||
e.toLowerCase().includes('regulation') ||
|
||||
e.toLowerCase().includes('ban')
|
||||
)) {
|
||||
warnings.push('Regulatory news may cause volatility');
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const signalEngine = new SignalEngine();
|
||||
6
src/lib/utils.ts
Normal file
6
src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
443
src/lib/vector/vector-store.ts
Normal file
443
src/lib/vector/vector-store.ts
Normal file
@@ -0,0 +1,443 @@
|
||||
/**
|
||||
* Vector Database Service for Mantle AI Trading Bot
|
||||
* ChromaDB integration for semantic search of news and analysis
|
||||
*/
|
||||
|
||||
import { ChromaClient, Collection, IncludeEnum } from 'chromadb-client';
|
||||
import { NewsArticle, Signal, SignalAnalysis, SentimentLabel } from '../trading/core/types';
|
||||
|
||||
// Collection names
|
||||
const COLLECTIONS = {
|
||||
NEWS: 'trading_news',
|
||||
SIGNALS: 'trading_signals',
|
||||
ANALYSIS: 'signal_analysis'
|
||||
};
|
||||
|
||||
// Embedding dimension (for typical embedding models)
|
||||
const EMBEDDING_DIMENSION = 384;
|
||||
|
||||
export class VectorStore {
|
||||
private client: ChromaClient | null = null;
|
||||
private newsCollection: Collection | null = null;
|
||||
private signalsCollection: Collection | null = null;
|
||||
private analysisCollection: Collection | null = null;
|
||||
private connected = false;
|
||||
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize ChromaDB connection
|
||||
*/
|
||||
private async init(): Promise<void> {
|
||||
try {
|
||||
// Try to connect to ChromaDB server
|
||||
this.client = new ChromaClient({
|
||||
path: process.env.CHROMADB_URL || 'http://localhost:8000'
|
||||
});
|
||||
|
||||
// Create or get collections
|
||||
await this.createCollections();
|
||||
this.connected = true;
|
||||
console.log('VectorStore: Connected to ChromaDB');
|
||||
} catch (error) {
|
||||
console.warn('VectorStore: ChromaDB not available, using fallback mode');
|
||||
this.connected = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or get collections
|
||||
*/
|
||||
private async createCollections(): Promise<void> {
|
||||
if (!this.client) return;
|
||||
|
||||
// News collection
|
||||
this.newsCollection = await this.client.getOrCreateCollection({
|
||||
name: COLLECTIONS.NEWS,
|
||||
metadata: { description: 'Trading news articles for semantic search' }
|
||||
});
|
||||
|
||||
// Signals collection
|
||||
this.signalsCollection = await this.client.getOrCreateCollection({
|
||||
name: COLLECTIONS.SIGNALS,
|
||||
metadata: { description: 'Historical trading signals' }
|
||||
});
|
||||
|
||||
// Analysis collection
|
||||
this.analysisCollection = await this.client.getOrCreateCollection({
|
||||
name: COLLECTIONS.ANALYSIS,
|
||||
metadata: { description: 'Signal analysis and reasoning' }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if connected
|
||||
*/
|
||||
isConnected(): boolean {
|
||||
return this.connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate simple embedding (fallback when no embedding model)
|
||||
* This creates a deterministic embedding based on text content
|
||||
*/
|
||||
private generateSimpleEmbedding(text: string): number[] {
|
||||
const embedding = new Array(EMBEDDING_DIMENSION).fill(0);
|
||||
const words = text.toLowerCase().split(/\s+/);
|
||||
|
||||
words.forEach((word, index) => {
|
||||
// Simple hash-based embedding
|
||||
const hash = this.simpleHash(word);
|
||||
const pos = Math.abs(hash) % EMBEDDING_DIMENSION;
|
||||
embedding[pos] += 1;
|
||||
|
||||
// Add positional encoding
|
||||
const pos2 = (pos + index) % EMBEDDING_DIMENSION;
|
||||
embedding[pos2] += 0.5;
|
||||
});
|
||||
|
||||
// Normalize
|
||||
const norm = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0)) || 1;
|
||||
return embedding.map(val => val / norm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple string hash
|
||||
*/
|
||||
private simpleHash(str: string): number {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store news article in vector database
|
||||
*/
|
||||
async storeNewsArticle(article: NewsArticle): Promise<string | null> {
|
||||
if (!this.newsCollection || !this.connected) {
|
||||
// Store article ID as vector reference
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const id = article.id || `news-${Date.now()}`;
|
||||
const text = `${article.title} ${article.content || ''}`;
|
||||
const embedding = this.generateSimpleEmbedding(text);
|
||||
|
||||
await this.newsCollection.add({
|
||||
ids: [id],
|
||||
embeddings: [embedding],
|
||||
metadatas: [{
|
||||
title: article.title,
|
||||
source: article.source,
|
||||
category: article.category || 'General',
|
||||
sentiment: article.sentiment || 0,
|
||||
importance: article.importance || 0.5,
|
||||
publishedAt: article.publishedAt?.toISOString() || new Date().toISOString(),
|
||||
url: article.sourceUrl || ''
|
||||
}],
|
||||
documents: [text]
|
||||
});
|
||||
|
||||
return id;
|
||||
} catch (error) {
|
||||
console.error('Error storing news article:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store multiple news articles
|
||||
*/
|
||||
async storeNewsArticles(articles: NewsArticle[]): Promise<string[]> {
|
||||
if (!this.newsCollection || !this.connected) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const ids: string[] = [];
|
||||
const embeddings: number[][] = [];
|
||||
const metadatas: Record<string, unknown>[] = [];
|
||||
const documents: string[] = [];
|
||||
|
||||
articles.forEach(article => {
|
||||
const id = article.id || `news-${Date.now()}-${Math.random()}`;
|
||||
const text = `${article.title} ${article.content || ''}`;
|
||||
|
||||
ids.push(id);
|
||||
embeddings.push(this.generateSimpleEmbedding(text));
|
||||
metadatas.push({
|
||||
title: article.title,
|
||||
source: article.source,
|
||||
category: article.category || 'General',
|
||||
sentiment: article.sentiment || 0,
|
||||
importance: article.importance || 0.5,
|
||||
publishedAt: article.publishedAt?.toISOString() || new Date().toISOString(),
|
||||
url: article.sourceUrl || ''
|
||||
});
|
||||
documents.push(text);
|
||||
});
|
||||
|
||||
try {
|
||||
await this.newsCollection.add({
|
||||
ids,
|
||||
embeddings,
|
||||
metadatas,
|
||||
documents
|
||||
});
|
||||
|
||||
return ids;
|
||||
} catch (error) {
|
||||
console.error('Error storing news articles:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search similar news articles
|
||||
*/
|
||||
async searchSimilarNews(
|
||||
query: string,
|
||||
nResults: number = 10,
|
||||
filters?: Record<string, unknown>
|
||||
): Promise<Array<{
|
||||
id: string;
|
||||
text: string;
|
||||
metadata: Record<string, unknown>;
|
||||
distance: number;
|
||||
}>> {
|
||||
if (!this.newsCollection || !this.connected) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const queryEmbedding = this.generateSimpleEmbedding(query);
|
||||
|
||||
const results = await this.newsCollection.query({
|
||||
queryEmbeddings: [queryEmbedding],
|
||||
nResults,
|
||||
where: filters,
|
||||
include: [IncludeEnum.Documents, IncludeEnum.Metadatas, IncludeEnum.Distances]
|
||||
});
|
||||
|
||||
if (!results.ids[0]) return [];
|
||||
|
||||
return results.ids[0].map((id, index) => ({
|
||||
id,
|
||||
text: results.documents?.[0]?.[index] || '',
|
||||
metadata: results.metadatas?.[0]?.[index] || {},
|
||||
distance: results.distances?.[0]?.[index] || 0
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Error searching news:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store signal with analysis
|
||||
*/
|
||||
async storeSignalAnalysis(
|
||||
signal: Signal,
|
||||
analysis: SignalAnalysis
|
||||
): Promise<void> {
|
||||
if (!this.signalsCollection || !this.analysisCollection || !this.connected) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Store signal
|
||||
const signalText = `${signal.symbol} ${signal.action} ${signal.reasoning}`;
|
||||
await this.signalsCollection.add({
|
||||
ids: [signal.id],
|
||||
embeddings: [this.generateSimpleEmbedding(signalText)],
|
||||
metadatas: [{
|
||||
symbol: signal.symbol,
|
||||
action: signal.action,
|
||||
confidence: signal.confidence,
|
||||
status: signal.status,
|
||||
result: signal.result || 'PENDING',
|
||||
pnl: signal.resultPnL || 0,
|
||||
createdAt: signal.createdAt.toISOString()
|
||||
}],
|
||||
documents: [signalText]
|
||||
});
|
||||
|
||||
// Store analysis
|
||||
const analysisText = analysis.keyFactors.join(' ') + ' ' +
|
||||
analysis.technicalAnalysis.patterns.join(' ') + ' ' +
|
||||
analysis.fundamentalAnalysis.marketEvents.join(' ');
|
||||
|
||||
await this.analysisCollection.add({
|
||||
ids: [`analysis-${signal.id}`],
|
||||
embeddings: [this.generateSimpleEmbedding(analysisText)],
|
||||
metadatas: [{
|
||||
signalId: signal.id,
|
||||
overallScore: analysis.overallScore,
|
||||
technicalScore: analysis.technicalAnalysis.score,
|
||||
fundamentalScore: analysis.fundamentalAnalysis.score,
|
||||
sentimentScore: analysis.sentimentAnalysis.overallSentiment
|
||||
}],
|
||||
documents: [analysisText]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error storing signal analysis:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find similar historical signals
|
||||
*/
|
||||
async findSimilarSignals(
|
||||
symbol: string,
|
||||
action: string,
|
||||
reasoning: string,
|
||||
nResults: number = 5
|
||||
): Promise<Array<{
|
||||
signalId: string;
|
||||
metadata: Record<string, unknown>;
|
||||
distance: number;
|
||||
}>> {
|
||||
if (!this.signalsCollection || !this.connected) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const queryText = `${symbol} ${action} ${reasoning}`;
|
||||
const queryEmbedding = this.generateSimpleEmbedding(queryText);
|
||||
|
||||
const results = await this.signalsCollection.query({
|
||||
queryEmbeddings: [queryEmbedding],
|
||||
nResults,
|
||||
where: { symbol },
|
||||
include: [IncludeEnum.Metadatas, IncludeEnum.Distances]
|
||||
});
|
||||
|
||||
if (!results.ids[0]) return [];
|
||||
|
||||
return results.ids[0].map((id, index) => ({
|
||||
signalId: id,
|
||||
metadata: results.metadatas?.[0]?.[index] || {},
|
||||
distance: results.distances?.[0]?.[index] || 0
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Error finding similar signals:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signal statistics from vector store
|
||||
*/
|
||||
async getSignalStatistics(symbol?: string): Promise<{
|
||||
totalSignals: number;
|
||||
winRate: number;
|
||||
avgConfidence: number;
|
||||
avgPnL: number;
|
||||
}> {
|
||||
// This would require aggregation queries in ChromaDB
|
||||
// For now, return placeholder values
|
||||
return {
|
||||
totalSignals: 0,
|
||||
winRate: 0,
|
||||
avgConfidence: 0,
|
||||
avgPnL: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete old entries (cleanup)
|
||||
*/
|
||||
async cleanupOldEntries(beforeDate: Date): Promise<void> {
|
||||
if (!this.connected) return;
|
||||
|
||||
try {
|
||||
// ChromaDB doesn't have a direct delete by date,
|
||||
// would need to query and delete by IDs
|
||||
// This is a placeholder for cleanup logic
|
||||
} catch (error) {
|
||||
console.error('Error during cleanup:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get contextual news for signal generation
|
||||
*/
|
||||
async getContextualNews(
|
||||
symbol: string,
|
||||
timeframe: string,
|
||||
maxArticles: number = 10
|
||||
): Promise<NewsArticle[]> {
|
||||
// Search for relevant news
|
||||
const results = await this.searchSimilarNews(
|
||||
`${symbol} cryptocurrency trading`,
|
||||
maxArticles,
|
||||
{ symbol: { $contains: symbol } }
|
||||
);
|
||||
|
||||
return results.map(result => ({
|
||||
id: result.id,
|
||||
title: result.metadata.title as string || '',
|
||||
source: result.metadata.source as string || 'Unknown',
|
||||
sentiment: result.metadata.sentiment as number,
|
||||
importance: result.metadata.importance as number,
|
||||
category: result.metadata.category as string,
|
||||
publishedAt: new Date(result.metadata.publishedAt as string),
|
||||
fetchedAt: new Date(),
|
||||
processed: true,
|
||||
vectorId: result.id
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze text sentiment using stored knowledge
|
||||
*/
|
||||
async analyzeSentimentWithContext(text: string): Promise<{
|
||||
sentiment: number;
|
||||
label: SentimentLabel;
|
||||
relevantArticles: NewsArticle[];
|
||||
}> {
|
||||
// Search for similar articles
|
||||
const similar = await this.searchSimilarNews(text, 5);
|
||||
|
||||
// Calculate aggregate sentiment from similar articles
|
||||
let totalSentiment = 0;
|
||||
const relevantArticles: NewsArticle[] = [];
|
||||
|
||||
similar.forEach(result => {
|
||||
const sentiment = result.metadata.sentiment as number || 0;
|
||||
totalSentiment += sentiment;
|
||||
relevantArticles.push({
|
||||
id: result.id,
|
||||
title: result.metadata.title as string || '',
|
||||
source: result.metadata.source as string || 'Unknown',
|
||||
sentiment,
|
||||
publishedAt: new Date(result.metadata.publishedAt as string),
|
||||
fetchedAt: new Date(),
|
||||
processed: true
|
||||
});
|
||||
});
|
||||
|
||||
const avgSentiment = similar.length > 0 ? totalSentiment / similar.length : 0;
|
||||
|
||||
let label = SentimentLabel.NEUTRAL;
|
||||
if (avgSentiment >= 0.3) label = SentimentLabel.BULLISH;
|
||||
else if (avgSentiment >= 0.6) label = SentimentLabel.VERY_BULLISH;
|
||||
else if (avgSentiment <= -0.3) label = SentimentLabel.BEARISH;
|
||||
else if (avgSentiment <= -0.6) label = SentimentLabel.VERY_BEARISH;
|
||||
|
||||
return {
|
||||
sentiment: avgSentiment,
|
||||
label,
|
||||
relevantArticles
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const vectorStore = new VectorStore();
|
||||
64
tailwind.config.ts
Normal file
64
tailwind.config.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
import tailwindcssAnimate from "tailwindcss-animate";
|
||||
|
||||
const config: Config = {
|
||||
darkMode: "class",
|
||||
content: [
|
||||
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
background: 'hsl(var(--background))',
|
||||
foreground: 'hsl(var(--foreground))',
|
||||
card: {
|
||||
DEFAULT: 'hsl(var(--card))',
|
||||
foreground: 'hsl(var(--card-foreground))'
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: 'hsl(var(--popover))',
|
||||
foreground: 'hsl(var(--popover-foreground))'
|
||||
},
|
||||
primary: {
|
||||
DEFAULT: 'hsl(var(--primary))',
|
||||
foreground: 'hsl(var(--primary-foreground))'
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: 'hsl(var(--secondary))',
|
||||
foreground: 'hsl(var(--secondary-foreground))'
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: 'hsl(var(--muted))',
|
||||
foreground: 'hsl(var(--muted-foreground))'
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: 'hsl(var(--accent))',
|
||||
foreground: 'hsl(var(--accent-foreground))'
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: 'hsl(var(--destructive))',
|
||||
foreground: 'hsl(var(--destructive-foreground))'
|
||||
},
|
||||
border: 'hsl(var(--border))',
|
||||
input: 'hsl(var(--input))',
|
||||
ring: 'hsl(var(--ring))',
|
||||
chart: {
|
||||
'1': 'hsl(var(--chart-1))',
|
||||
'2': 'hsl(var(--chart-2))',
|
||||
'3': 'hsl(var(--chart-3))',
|
||||
'4': 'hsl(var(--chart-4))',
|
||||
'5': 'hsl(var(--chart-5))'
|
||||
}
|
||||
},
|
||||
borderRadius: {
|
||||
lg: 'var(--radius)',
|
||||
md: 'calc(var(--radius) - 2px)',
|
||||
sm: 'calc(var(--radius) - 4px)'
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: [tailwindcssAnimate],
|
||||
};
|
||||
export default config;
|
||||
184
tests/unit/demo-trader.test.ts
Normal file
184
tests/unit/demo-trader.test.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Unit Tests for Demo Trader
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||
import { DemoTrader } from '../../src/lib/trading/demo/demo-trader';
|
||||
import { TradeAction, OrderType } from '../../src/lib/trading/core/types';
|
||||
|
||||
describe('DemoTrader', () => {
|
||||
let demoTrader: DemoTrader;
|
||||
|
||||
beforeEach(() => {
|
||||
demoTrader = new DemoTrader(10000);
|
||||
});
|
||||
|
||||
describe('initialization', () => {
|
||||
test('should initialize with correct portfolio', () => {
|
||||
const portfolio = demoTrader.getPortfolio();
|
||||
|
||||
expect(portfolio.totalValue).toBe(10000);
|
||||
expect(portfolio.cashBalance).toBe(10000);
|
||||
expect(portfolio.realizedPnL).toBe(0);
|
||||
expect(portfolio.unrealizedPnL).toBe(0);
|
||||
});
|
||||
|
||||
test('should have no positions initially', () => {
|
||||
const positions = demoTrader.getPositions();
|
||||
expect(positions.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeOrder', () => {
|
||||
test('should place a market buy order', () => {
|
||||
// Set price first
|
||||
demoTrader.updatePrice('BTCUSDT', 45000);
|
||||
|
||||
const order = demoTrader.placeOrder({
|
||||
symbol: 'BTCUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 0.1
|
||||
});
|
||||
|
||||
expect(order).toBeDefined();
|
||||
expect(order.status).toBe('FILLED');
|
||||
expect(order.symbol).toBe('BTCUSDT');
|
||||
expect(order.side).toBe(TradeAction.BUY);
|
||||
});
|
||||
|
||||
test('should update cash balance after buy order', () => {
|
||||
demoTrader.updatePrice('ETHUSDT', 2500);
|
||||
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'ETHUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 2
|
||||
});
|
||||
|
||||
const portfolio = demoTrader.getPortfolio();
|
||||
expect(portfolio.cashBalance).toBe(10000 - (2500 * 2));
|
||||
});
|
||||
|
||||
test('should create a position after buy order', () => {
|
||||
demoTrader.updatePrice('SOLUSDT', 100);
|
||||
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'SOLUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 10
|
||||
});
|
||||
|
||||
const positions = demoTrader.getPositions();
|
||||
expect(positions.length).toBe(1);
|
||||
expect(positions[0].symbol).toBe('SOLUSDT');
|
||||
expect(positions[0].side).toBe('LONG');
|
||||
expect(positions[0].quantity).toBe(10);
|
||||
});
|
||||
|
||||
test('should throw error for insufficient capital', () => {
|
||||
demoTrader.updatePrice('BTCUSDT', 45000);
|
||||
|
||||
expect(() => {
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'BTCUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 1 // Would cost 45000, but we only have 10000
|
||||
});
|
||||
}).toThrow('Insufficient capital');
|
||||
});
|
||||
});
|
||||
|
||||
describe('closePosition', () => {
|
||||
test('should close an existing position', () => {
|
||||
demoTrader.updatePrice('BTCUSDT', 45000);
|
||||
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'BTCUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 0.1
|
||||
});
|
||||
|
||||
const closeOrder = demoTrader.closePosition('BTCUSDT');
|
||||
|
||||
expect(closeOrder).toBeDefined();
|
||||
expect(closeOrder?.side).toBe(TradeAction.SELL);
|
||||
|
||||
const positions = demoTrader.getPositions();
|
||||
expect(positions.length).toBe(0);
|
||||
});
|
||||
|
||||
test('should return null when closing non-existent position', () => {
|
||||
const result = demoTrader.closePosition('NONEXISTENT');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePrice', () => {
|
||||
test('should update position PnL when price changes', () => {
|
||||
demoTrader.updatePrice('ETHUSDT', 2500);
|
||||
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'ETHUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 2
|
||||
});
|
||||
|
||||
// Price goes up
|
||||
demoTrader.updatePrice('ETHUSDT', 2600);
|
||||
|
||||
const positions = demoTrader.getPositions();
|
||||
expect(positions[0].unrealizedPnL).toBeGreaterThan(0);
|
||||
expect(positions[0].currentPrice).toBe(2600);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset', () => {
|
||||
test('should reset portfolio to initial state', () => {
|
||||
demoTrader.updatePrice('BTCUSDT', 45000);
|
||||
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'BTCUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 0.1
|
||||
});
|
||||
|
||||
demoTrader.reset(15000);
|
||||
|
||||
const portfolio = demoTrader.getPortfolio();
|
||||
expect(portfolio.totalValue).toBe(15000);
|
||||
expect(portfolio.cashBalance).toBe(15000);
|
||||
|
||||
const positions = demoTrader.getPositions();
|
||||
expect(positions.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStatistics', () => {
|
||||
test('should return correct trade statistics', () => {
|
||||
demoTrader.updatePrice('BTCUSDT', 45000);
|
||||
|
||||
// Open and close a position
|
||||
demoTrader.placeOrder({
|
||||
symbol: 'BTCUSDT',
|
||||
side: TradeAction.BUY,
|
||||
type: OrderType.MARKET,
|
||||
quantity: 0.1
|
||||
});
|
||||
|
||||
demoTrader.updatePrice('BTCUSDT', 46000); // Price up
|
||||
demoTrader.closePosition('BTCUSDT');
|
||||
|
||||
const stats = demoTrader.getStatistics();
|
||||
|
||||
expect(stats.totalTrades).toBe(2); // Open and close
|
||||
expect(stats.winningTrades + stats.losingTrades).toBe(stats.totalTrades);
|
||||
});
|
||||
});
|
||||
});
|
||||
114
tests/unit/signal-engine.test.ts
Normal file
114
tests/unit/signal-engine.test.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Unit Tests for Signal Engine
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||
import { SignalEngine } from '../../src/lib/trading/signals/signal-engine';
|
||||
import { TimeFrame, TradeAction, MarketDataPoint } from '../../src/lib/trading/core/types';
|
||||
|
||||
describe('SignalEngine', () => {
|
||||
let signalEngine: SignalEngine;
|
||||
|
||||
beforeEach(() => {
|
||||
signalEngine = new SignalEngine();
|
||||
});
|
||||
|
||||
describe('generateSignal', () => {
|
||||
test('should generate a signal with required fields', async () => {
|
||||
const marketData = generateTestMarketData('BTCUSDT', 100);
|
||||
|
||||
const result = await signalEngine.generateSignal({
|
||||
symbol: 'BTCUSDT',
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
marketData,
|
||||
newsArticles: []
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.signal).toBeDefined();
|
||||
expect(result.signal.symbol).toBe('BTCUSDT');
|
||||
expect(result.signal.action).toBeDefined();
|
||||
expect([TradeAction.BUY, TradeAction.SELL, TradeAction.HOLD]).toContain(result.signal.action);
|
||||
expect(result.signal.confidence).toBeGreaterThanOrEqual(0);
|
||||
expect(result.signal.confidence).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test('should include technical analysis', async () => {
|
||||
const marketData = generateTestMarketData('ETHUSDT', 200);
|
||||
|
||||
const result = await signalEngine.generateSignal({
|
||||
symbol: 'ETHUSDT',
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
marketData,
|
||||
newsArticles: []
|
||||
});
|
||||
|
||||
expect(result.analysis.technicalAnalysis).toBeDefined();
|
||||
expect(result.analysis.technicalAnalysis.trend).toBeDefined();
|
||||
expect(['BULLISH', 'BEARISH', 'SIDEWAYS']).toContain(result.analysis.technicalAnalysis.trend);
|
||||
expect(result.analysis.technicalAnalysis.indicators).toBeDefined();
|
||||
});
|
||||
|
||||
test('should include risk assessment', async () => {
|
||||
const marketData = generateTestMarketData('SOLUSDT', 150);
|
||||
|
||||
const result = await signalEngine.generateSignal({
|
||||
symbol: 'SOLUSDT',
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
marketData,
|
||||
newsArticles: []
|
||||
});
|
||||
|
||||
expect(result.riskAssessment).toBeDefined();
|
||||
expect(result.riskAssessment.riskScore).toBeGreaterThanOrEqual(0);
|
||||
expect(result.riskAssessment.riskScore).toBeLessThanOrEqual(1);
|
||||
expect(result.riskAssessment.riskLevel).toBeDefined();
|
||||
});
|
||||
|
||||
test('should handle insufficient data gracefully', async () => {
|
||||
const marketData = generateTestMarketData('BTCUSDT', 10);
|
||||
|
||||
const result = await signalEngine.generateSignal({
|
||||
symbol: 'BTCUSDT',
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
marketData,
|
||||
newsArticles: []
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.analysis.technicalAnalysis.score).toBe(0.5); // Default for insufficient data
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Helper function to generate test market data
|
||||
function generateTestMarketData(symbol: string, count: number): MarketDataPoint[] {
|
||||
const data: MarketDataPoint[] = [];
|
||||
let price = 40000 + Math.random() * 5000;
|
||||
const now = Date.now();
|
||||
const hourMs = 60 * 60 * 1000;
|
||||
|
||||
for (let i = count; i >= 0; i--) {
|
||||
const change = (Math.random() - 0.5) * price * 0.02;
|
||||
const open = price;
|
||||
const close = price + change;
|
||||
const high = Math.max(open, close) + Math.random() * Math.abs(change) * 0.5;
|
||||
const low = Math.min(open, close) - Math.random() * Math.abs(change) * 0.5;
|
||||
const volume = 1000 + Math.random() * 5000;
|
||||
|
||||
data.push({
|
||||
symbol,
|
||||
timeframe: TimeFrame.ONE_HOUR,
|
||||
timestamp: new Date(now - i * hourMs),
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume
|
||||
});
|
||||
|
||||
price = close;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
42
tsconfig.json
Normal file
42
tsconfig.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"noImplicitAny": false,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
168
worklog.md
Normal file
168
worklog.md
Normal file
@@ -0,0 +1,168 @@
|
||||
# Mantle AI Trading Bot - Worklog
|
||||
|
||||
---
|
||||
Task ID: 1
|
||||
Agent: Main Agent
|
||||
Task: Initialize project structure and architecture
|
||||
|
||||
Work Log:
|
||||
- Created comprehensive project structure with all required directories
|
||||
- Designed system architecture with multiple components
|
||||
- Created Prisma database schema with all models (Signal, Trade, NewsArticle, etc.)
|
||||
- Initialized Next.js 16 project with TypeScript, Tailwind CSS, shadcn/ui
|
||||
|
||||
Stage Summary:
|
||||
- Project structure created at /home/z/my-project
|
||||
- Database schema designed with 12 models for signals, trades, news, backtesting
|
||||
- Core types and interfaces defined in src/lib/trading/core/types.ts
|
||||
|
||||
---
|
||||
Task ID: 2
|
||||
Agent: Main Agent
|
||||
Task: Build core trading engine with Bybit API integration
|
||||
|
||||
Work Log:
|
||||
- Created BybitClient class for exchange interactions
|
||||
- Implemented authentication with signature generation
|
||||
- Added methods for ticker, klines, order book data
|
||||
- Implemented order placement, cancellation, and position management
|
||||
- Added wallet balance and leverage management
|
||||
|
||||
Stage Summary:
|
||||
- Core trading engine at src/lib/trading/core/trading-engine.ts
|
||||
- Full Bybit API integration with testnet support
|
||||
- Order management with market and limit orders
|
||||
- Position tracking and portfolio management
|
||||
|
||||
---
|
||||
Task ID: 3
|
||||
Agent: Main Agent
|
||||
Task: Implement news aggregation system
|
||||
|
||||
Work Log:
|
||||
- Created NewsAggregator class with multiple source support
|
||||
- Implemented CryptoPanic, CoinGecko, CryptoCompare integrations
|
||||
- Added RSS feed support for custom sources
|
||||
- Built sentiment analysis with keyword-based scoring
|
||||
- Created category detection and tag extraction
|
||||
|
||||
Stage Summary:
|
||||
- News aggregator at src/lib/trading/news/news-aggregator.ts
|
||||
- Support for 4+ news sources
|
||||
- Sentiment analysis with bullish/bearish detection
|
||||
- Market-moving news detection
|
||||
|
||||
---
|
||||
Task ID: 4
|
||||
Agent: Main Agent
|
||||
Task: Build VectorDB integration for semantic analysis
|
||||
|
||||
Work Log:
|
||||
- Created VectorStore class with ChromaDB client
|
||||
- Implemented simple embedding generation for fallback
|
||||
- Added methods for storing and searching news articles
|
||||
- Created signal analysis storage and retrieval
|
||||
- Built contextual sentiment analysis
|
||||
|
||||
Stage Summary:
|
||||
- Vector store at src/lib/vector/vector-store.ts
|
||||
- ChromaDB integration with fallback mode
|
||||
- Semantic search for similar articles
|
||||
- Signal analysis persistence
|
||||
|
||||
---
|
||||
Task ID: 5
|
||||
Agent: Main Agent
|
||||
Task: Create signal generation and rating system
|
||||
|
||||
Work Log:
|
||||
- Created SignalEngine class for AI-powered signals
|
||||
- Implemented technical analysis (SMA, EMA, RSI, MACD)
|
||||
- Added support/resistance detection and pattern recognition
|
||||
- Built fundamental analysis from news data
|
||||
- Created comprehensive risk assessment
|
||||
- Added AI reasoning generation with z-ai-web-dev-sdk
|
||||
- Implemented confidence scoring and target calculation
|
||||
|
||||
Stage Summary:
|
||||
- Signal engine at src/lib/trading/signals/signal-engine.ts
|
||||
- Complete technical analysis with 6+ indicators
|
||||
- Pattern detection (Doji, Hammer, Engulfing, Morning Star)
|
||||
- Multi-factor scoring system (technical, fundamental, sentiment)
|
||||
- Risk assessment with position sizing
|
||||
|
||||
---
|
||||
Task ID: 6
|
||||
Agent: Main Agent
|
||||
Task: Implement backtesting engine
|
||||
|
||||
Work Log:
|
||||
- Created BacktestEngine class for strategy simulation
|
||||
- Implemented historical data simulation
|
||||
- Built trade execution with slippage and fees
|
||||
- Created performance metrics calculation (Sharpe, Sortino, etc.)
|
||||
- Added strategy optimization with parameter grid search
|
||||
- Built backtest report generation
|
||||
|
||||
Stage Summary:
|
||||
- Backtest engine at src/lib/trading/backtest/backtest-engine.ts
|
||||
- Full trade simulation with stop-loss/take-profit
|
||||
- Comprehensive performance metrics
|
||||
- Strategy optimization support
|
||||
|
||||
---
|
||||
Task ID: 7
|
||||
Agent: Main Agent
|
||||
Task: Build demo mode for paper trading
|
||||
|
||||
Work Log:
|
||||
- Created DemoTrader class for paper trading
|
||||
- Implemented order placement and execution
|
||||
- Added position tracking and P&L calculation
|
||||
- Built stop-loss and take-profit monitoring
|
||||
- Created trade statistics and history
|
||||
- Added real-time price updates and portfolio sync
|
||||
|
||||
Stage Summary:
|
||||
- Demo trader at src/lib/trading/demo/demo-trader.ts
|
||||
- Complete paper trading system
|
||||
- Real-time position tracking
|
||||
- Event-based architecture for UI updates
|
||||
|
||||
---
|
||||
Task ID: 8
|
||||
Agent: Main Agent
|
||||
Task: Create WebSocket service and API routes
|
||||
|
||||
Work Log:
|
||||
- Created TradingWebSocketService for real-time updates
|
||||
- Implemented socket.io server with event handlers
|
||||
- Created API routes for signals, news, backtest, demo trading
|
||||
- Added RESTful endpoints for all trading operations
|
||||
|
||||
Stage Summary:
|
||||
- WebSocket service at mini-services/trading-service/index.ts
|
||||
- API routes in src/app/api/trading/
|
||||
- Real-time price updates and portfolio sync
|
||||
- Full CRUD operations for signals and trades
|
||||
|
||||
---
|
||||
Task ID: 9
|
||||
Agent: Main Agent
|
||||
Task: Build UI/Dashboard with real-time updates
|
||||
|
||||
Work Log:
|
||||
- Created comprehensive dashboard with React components
|
||||
- Implemented real-time data display with socket.io
|
||||
- Built signal generation interface with analysis display
|
||||
- Created positions and portfolio visualization
|
||||
- Added charts with recharts (Line, Area, Pie)
|
||||
- Built news feed with sentiment indicators
|
||||
- Created backtesting interface
|
||||
|
||||
Stage Summary:
|
||||
- Dashboard at src/app/page.tsx
|
||||
- Real-time updates via WebSocket
|
||||
- 4 main tabs: Signals, Positions, Backtest, News
|
||||
- Live price ticker for major pairs
|
||||
- Signal execution and position management
|
||||
Reference in New Issue
Block a user