chore: move shell scripts under scripts/ and update docs

This commit is contained in:
icy
2025-11-06 17:53:27 +08:00
parent b15b0fb01a
commit 6ca197437d
9 changed files with 68 additions and 62 deletions

228
scripts/generate_beta_code.sh Executable file
View File

@@ -0,0 +1,228 @@
#!/bin/bash
# Fail fast and normalize working directory
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"
# 内测码生成脚本
# 生成6位不重复的内测码并写入 beta_codes.txt
BETA_CODES_FILE="beta_codes.txt"
COUNT=1
LIST_ONLY=false
CODE_LENGTH=6
# 字符集避免易混淆字符0/O, 1/I/l
CHARSET="23456789abcdefghjkmnpqrstuvwxyz"
# 显示帮助信息
show_help() {
cat << EOF
用法: $0 [选项]
选项:
-c COUNT 生成内测码数量 (默认: 1)
-l 列出现有内测码
-f FILE 内测码文件路径 (默认: beta_codes.txt)
-h 显示此帮助信息
示例:
$0 -c 10 # 生成10个内测码
$0 -l # 列出现有内测码
$0 -f custom.txt -c 5 # 在自定义文件中生成5个内测码
EOF
}
# 生成随机内测码
generate_beta_code() {
local length="$1"
local charset="$2"
local code=""
for ((i=0; i<length; i++)); do
local random_index=$((RANDOM % ${#charset}))
code+="${charset:$random_index:1}"
done
echo "$code"
}
# 读取现有内测码
read_existing_codes() {
local file="$1"
if [ -f "$file" ]; then
grep -v '^$' "$file" 2>/dev/null | tr -d ' \t' | grep -v '^#' || true
fi
}
# 检查内测码是否已存在
code_exists() {
local code="$1"
local file="$2"
if [ -f "$file" ]; then
grep -Fxq "$code" "$file" 2>/dev/null
else
return 1
fi
}
# 添加内测码到文件
add_code_to_file() {
local code="$1"
local file="$2"
echo "$code" >> "$file"
}
# 验证内测码格式
validate_code() {
local code="$1"
# 检查长度
if [ ${#code} -ne $CODE_LENGTH ]; then
return 1
fi
# 检查字符是否都在允许的字符集中
if [[ ! "$code" =~ ^[$CHARSET]+$ ]]; then
return 1
fi
return 0
}
# 去重并排序内测码
dedupe_and_sort_codes() {
local file="$1"
if [ -f "$file" ]; then
# 过滤空行和注释,去重并排序
grep -v '^$' "$file" | grep -v '^#' | sort -u > "${file}.tmp" && mv "${file}.tmp" "$file"
fi
}
# 解析命令行参数
while getopts "c:lf:h" opt; do
case $opt in
c)
COUNT="$OPTARG"
if ! [[ "$COUNT" =~ ^[0-9]+$ ]] || [ "$COUNT" -lt 1 ]; then
echo "错误: count 必须是正整数" >&2
exit 1
fi
;;
l)
LIST_ONLY=true
;;
f)
BETA_CODES_FILE="$OPTARG"
;;
h)
show_help
exit 0
;;
\?)
echo "无效选项: -$OPTARG" >&2
echo "使用 -h 查看帮助信息" >&2
exit 1
;;
esac
done
# 如果是列出现有内测码
if [ "$LIST_ONLY" = true ]; then
if [ -f "$BETA_CODES_FILE" ]; then
existing_codes=$(read_existing_codes "$BETA_CODES_FILE")
if [ -z "$existing_codes" ]; then
echo "内测码列表为空"
else
count=$(echo "$existing_codes" | wc -l | tr -d ' ')
echo "当前内测码 ($count 个):"
echo "$existing_codes" | nl -w3 -s'. '
fi
else
echo "内测码文件不存在: $BETA_CODES_FILE"
fi
exit 0
fi
# 读取现有内测码
existing_codes=$(read_existing_codes "$BETA_CODES_FILE")
# 生成新内测码
new_codes=()
max_attempts=1000 # 防止无限循环
echo "正在生成 $COUNT 个内测码..."
for ((i=1; i<=COUNT; i++)); do
attempts=0
while [ $attempts -lt $max_attempts ]; do
code=$(generate_beta_code $CODE_LENGTH "$CHARSET")
# 验证格式
if ! validate_code "$code"; then
((attempts++))
continue
fi
# 检查是否已存在
if code_exists "$code" "$BETA_CODES_FILE"; then
((attempts++))
continue
fi
# 检查是否与本次生成的重复
duplicate=false
for existing_code in "${new_codes[@]}"; do
if [ "$code" = "$existing_code" ]; then
duplicate=true
break
fi
done
if [ "$duplicate" = false ]; then
new_codes+=("$code")
break
fi
((attempts++))
done
if [ $attempts -eq $max_attempts ]; then
echo "警告: 生成第 $i 个内测码时达到最大尝试次数,可能字符空间不足" >&2
break
fi
done
# 检查是否成功生成了内测码
if [ ${#new_codes[@]} -eq 0 ]; then
echo "未能生成任何新的内测码"
exit 1
fi
# 添加到文件
for code in "${new_codes[@]}"; do
add_code_to_file "$code" "$BETA_CODES_FILE"
done
# 去重并排序
dedupe_and_sort_codes "$BETA_CODES_FILE"
echo "成功生成 ${#new_codes[@]} 个内测码:"
printf ' %s\n' "${new_codes[@]}"
echo
echo "内测码文件: $BETA_CODES_FILE"
# 显示当前总数
if [ -f "$BETA_CODES_FILE" ]; then
total_count=$(read_existing_codes "$BETA_CODES_FILE" | wc -l | tr -d ' ')
echo "当前内测码总计: $total_count"
fi
# 显示文件头部信息(如果是新文件)
if [ ! -s "$BETA_CODES_FILE" ] || [ $(wc -l < "$BETA_CODES_FILE") -eq ${#new_codes[@]} ]; then
echo
echo "内测码规则:"
echo "- 长度: $CODE_LENGTH"
echo "- 字符集: 数字 2-9, 小写字母 a-z (排除 0,1,i,l,o 避免混淆)"
echo "- 每个内测码唯一且不重复"
fi

52
scripts/import_beta_codes.sh Executable file
View File

@@ -0,0 +1,52 @@
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"
# 将beta_codes.txt刷到PostgreSQL数据库
echo "🎟️ 导入beta_codes.txt到数据库"
# 检查文件
if [ ! -f "beta_codes.txt" ]; then
echo "❌ 找不到beta_codes.txt文件"
exit 1
fi
# 检测docker命令
if command -v "docker-compose" &> /dev/null; then
DOCKER_CMD="docker-compose"
else
DOCKER_CMD="docker compose"
fi
# 统计数量
TOTAL=$(cat beta_codes.txt | wc -l)
echo "📊 文件中共有 $TOTAL 个内测码"
# 生成SQL
cat > import.sql << EOF
INSERT INTO beta_codes (code) VALUES
EOF
# 读取每行并生成INSERT语句
cat beta_codes.txt | while read line; do
if [ -n "$line" ]; then
echo "('$line')," >> import.sql
fi
done
# 移除最后的逗号并添加冲突处理
sed -i '$ s/,$//' import.sql
echo "ON CONFLICT (code) DO NOTHING;" >> import.sql
# 执行导入
echo "🔄 导入到数据库..."
$DOCKER_CMD exec -T postgres psql -U nofx -d nofx < import.sql
echo "✅ 导入完成(重复的已跳过)"
# 清理
rm import.sql

321
scripts/start.sh Executable file
View File

@@ -0,0 +1,321 @@
#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# NOFX AI Trading System - Docker Quick Start Script
# Usage: ./scripts/start.sh [command]
# ═══════════════════════════════════════════════════════════════
set -e
# Ensure we operate from repo root regardless of invocation location
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"
# ------------------------------------------------------------------------
# Color Definitions
# ------------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ------------------------------------------------------------------------
# Utility Functions: Colored Output
# ------------------------------------------------------------------------
print_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# ------------------------------------------------------------------------
# Detection: Docker Compose Command (Backward Compatible)
# ------------------------------------------------------------------------
detect_compose_cmd() {
if command -v docker compose &> /dev/null; then
COMPOSE_CMD="docker compose"
elif command -v docker-compose &> /dev/null; then
COMPOSE_CMD="docker-compose"
else
print_error "Docker Compose 未安装!请先安装 Docker Compose"
exit 1
fi
print_info "使用 Docker Compose 命令: $COMPOSE_CMD"
}
# ------------------------------------------------------------------------
# Validation: Docker Installation
# ------------------------------------------------------------------------
check_docker() {
if ! command -v docker &> /dev/null; then
print_error "Docker 未安装!请先安装 Docker: https://docs.docker.com/get-docker/"
exit 1
fi
detect_compose_cmd
print_success "Docker 和 Docker Compose 已安装"
}
# ------------------------------------------------------------------------
# Validation: Environment File (.env)
# ------------------------------------------------------------------------
check_env() {
if [ ! -f ".env" ]; then
print_warning ".env 不存在,从模板复制..."
cp .env.example .env
print_info "✓ 已使用默认环境变量创建 .env"
print_info "💡 如需修改端口等设置,可编辑 .env 文件"
fi
print_success "环境变量文件存在"
}
# ------------------------------------------------------------------------
# Validation: Configuration File (config.json) - BASIC SETTINGS ONLY
# ------------------------------------------------------------------------
check_config() {
if [ ! -f "config.json" ]; then
print_warning "config.json 不存在,从模板复制..."
cp config.json.example config.json
print_info "✓ 已使用默认配置创建 config.json"
print_info "💡 如需修改基础设置杠杆大小、开仓币种、JWT密钥等可编辑 config.json"
print_info "💡 模型/交易所/交易员配置请使用Web界面"
fi
print_success "配置文件存在"
}
# ------------------------------------------------------------------------
# Utility: Read Environment Variables
# ------------------------------------------------------------------------
read_env_vars() {
if [ -f ".env" ]; then
# 读取端口配置,设置默认值
NOFX_FRONTEND_PORT=$(grep "^NOFX_FRONTEND_PORT=" .env 2>/dev/null | cut -d'=' -f2 || echo "3000")
NOFX_BACKEND_PORT=$(grep "^NOFX_BACKEND_PORT=" .env 2>/dev/null | cut -d'=' -f2 || echo "8080")
# 去除可能的引号和空格
NOFX_FRONTEND_PORT=$(echo "$NOFX_FRONTEND_PORT" | tr -d '"'"'" | tr -d ' ')
NOFX_BACKEND_PORT=$(echo "$NOFX_BACKEND_PORT" | tr -d '"'"'" | tr -d ' ')
# 如果为空则使用默认值
NOFX_FRONTEND_PORT=${NOFX_FRONTEND_PORT:-3000}
NOFX_BACKEND_PORT=${NOFX_BACKEND_PORT:-8080}
else
# 如果.env不存在使用默认端口
NOFX_FRONTEND_PORT=3000
NOFX_BACKEND_PORT=8080
fi
}
# ------------------------------------------------------------------------
# Build: Frontend (Node.js Based)
# ------------------------------------------------------------------------
# build_frontend() {
# print_info "检查前端构建环境..."
# if ! command -v node &> /dev/null; then
# print_error "Node.js 未安装!请先安装 Node.js"
# exit 1
# fi
# if ! command -v npm &> /dev/null; then
# print_error "npm 未安装!请先安装 npm"
# exit 1
# fi
# print_info "正在构建前端..."
# cd web
# print_info "安装 Node.js 依赖..."
# npm install
# print_info "构建前端应用..."
# npm run build
# cd ..
# print_success "前端构建完成"
# }
# ------------------------------------------------------------------------
# Service Management: Start
# ------------------------------------------------------------------------
start() {
print_info "正在启动 NOFX AI Trading System..."
# 读取环境变量
read_env_vars
# 确保必要的目录存在
if [ ! -d "decision_logs" ]; then
print_info "创建日志目录..."
mkdir -p decision_logs
fi
# Auto-build frontend if missing or forced
# if [ ! -d "web/dist" ] || [ "$1" == "--build" ]; then
# build_frontend
# fi
# Rebuild images if flag set
if [ "$1" == "--build" ]; then
print_info "重新构建镜像..."
$COMPOSE_CMD up -d --build
else
print_info "启动容器..."
$COMPOSE_CMD up -d
fi
print_success "服务已启动!"
print_info "Web 界面: http://localhost:${NOFX_FRONTEND_PORT}"
print_info "API 端点: http://localhost:${NOFX_BACKEND_PORT}"
print_info ""
print_info "查看日志: ./scripts/start.sh logs"
print_info "停止服务: ./scripts/start.sh stop"
}
# ------------------------------------------------------------------------
# Service Management: Stop
# ------------------------------------------------------------------------
stop() {
print_info "正在停止服务..."
$COMPOSE_CMD stop
print_success "服务已停止"
}
# ------------------------------------------------------------------------
# Service Management: Restart
# ------------------------------------------------------------------------
restart() {
print_info "正在重启服务..."
$COMPOSE_CMD restart
print_success "服务已重启"
}
# ------------------------------------------------------------------------
# Monitoring: Logs
# ------------------------------------------------------------------------
logs() {
if [ -z "$2" ]; then
$COMPOSE_CMD logs -f
else
$COMPOSE_CMD logs -f "$2"
fi
}
# ------------------------------------------------------------------------
# Monitoring: Status
# ------------------------------------------------------------------------
status() {
# 读取环境变量
read_env_vars
print_info "服务状态:"
$COMPOSE_CMD ps
echo ""
print_info "健康检查:"
curl -s "http://localhost:${NOFX_BACKEND_PORT}/api/health" | jq '.' || echo "后端未响应"
}
# ------------------------------------------------------------------------
# Maintenance: Clean (Destructive)
# ------------------------------------------------------------------------
clean() {
print_warning "这将删除所有容器和数据!"
read -p "确认删除?(yes/no): " confirm
if [ "$confirm" == "yes" ]; then
print_info "正在清理..."
$COMPOSE_CMD down -v
print_success "清理完成"
else
print_info "已取消"
fi
}
# ------------------------------------------------------------------------
# Maintenance: Update
# ------------------------------------------------------------------------
update() {
print_info "正在更新..."
git pull
$COMPOSE_CMD up -d --build
print_success "更新完成"
}
# ------------------------------------------------------------------------
# Help: Usage Information
# ------------------------------------------------------------------------
show_help() {
echo "NOFX AI Trading System - Docker 管理脚本"
echo ""
echo "用法: ./scripts/start.sh [command] [options]"
echo ""
echo "命令:"
echo " start [--build] 启动服务(可选:重新构建)"
echo " stop 停止服务"
echo " restart 重启服务"
echo " logs [service] 查看日志(可选:指定服务名 backend/frontend"
echo " status 查看服务状态"
echo " clean 清理所有容器和数据"
echo " update 更新代码并重启"
echo " help 显示此帮助信息"
echo ""
echo "示例:"
echo " ./scripts/start.sh start --build # 构建并启动"
echo " ./scripts/start.sh logs backend # 查看后端日志"
echo " ./scripts/start.sh status # 查看状态"
}
# ------------------------------------------------------------------------
# Main: Command Dispatcher
# ------------------------------------------------------------------------
main() {
check_docker
case "${1:-start}" in
start)
check_env
check_config
start "$2"
;;
stop)
stop
;;
restart)
restart
;;
logs)
logs "$@"
;;
status)
status
;;
clean)
clean
;;
update)
update
;;
help|--help|-h)
show_help
;;
*)
print_error "未知命令: $1"
show_help
exit 1
;;
esac
}
# Execute Main
main "$@"

72
scripts/view_pg_data.sh Executable file
View File

@@ -0,0 +1,72 @@
#!/bin/bash
set -e
# 保证从仓库根目录运行
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"
# PostgreSQL数据查看工具
echo "🔍 PostgreSQL 数据查看工具"
echo "=========================="
# 检测Docker Compose命令
DOCKER_COMPOSE_CMD=""
if command -v "docker-compose" &> /dev/null; then
DOCKER_COMPOSE_CMD="docker-compose"
elif command -v "docker" &> /dev/null && docker compose version &> /dev/null; then
DOCKER_COMPOSE_CMD="docker compose"
else
echo "❌ 错误:找不到 docker-compose 或 docker compose 命令"
exit 1
fi
echo "📊 数据库概览:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT relname as \"表名\", n_live_tup as \"记录数\"
FROM pg_stat_user_tables
WHERE n_live_tup > 0
ORDER BY relname;
"
echo -e "\n🤖 AI模型配置:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT id, name, provider, enabled,
CASE WHEN api_key != '' THEN '已配置' ELSE '未配置' END as api_key_status
FROM ai_models ORDER BY id;
"
echo -e "\n🏢 交易所配置:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT id, name, type, enabled,
CASE WHEN api_key != '' THEN '已配置' ELSE '未配置' END as api_key_status
FROM exchanges ORDER BY id;
"
echo -e "\n⚙ 关键系统配置:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT key,
CASE
WHEN LENGTH(value) > 50 THEN LEFT(value, 50) || '...'
ELSE value
END as value
FROM system_config
WHERE key IN ('beta_mode', 'api_server_port', 'default_coins', 'jwt_secret')
ORDER BY key;
"
echo -e "\n🎟 内测码统计:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT
CASE WHEN used THEN '已使用' ELSE '未使用' END as status,
COUNT(*) as count
FROM beta_codes
GROUP BY used
ORDER BY used;
"
echo -e "\n👥 用户信息:"
$DOCKER_COMPOSE_CMD exec postgres psql -U nofx -d nofx --pset pager=off -c "
SELECT id, email, otp_verified, created_at FROM users ORDER BY created_at;
"