diff --git a/.github/BRANCH_PROTECTION.md b/.github/BRANCH_PROTECTION.md deleted file mode 100644 index fb8089e..0000000 --- a/.github/BRANCH_PROTECTION.md +++ /dev/null @@ -1,315 +0,0 @@ -# 分支保护配置指南 - -## 为什么需要分支保护? - -分支保护可以: - -- ✅ 防止直接推送到主分支 -- ✅ 确保所有更改都经过 PR 审查 -- ✅ 强制 CI 测试必须通过 -- ✅ 要求代码审查 -- ✅ 保持代码质量和稳定性 - -## 推荐的分支保护规则 - -### 🔒 Main 分支保护 (强烈推荐) - -#### 基础保护 - -1. **Require a pull request before merging** (合并前需要 PR) - - - ✅ 启用此选项 - - Require approvals: 1 (至少 1 人审查) - - ✅ Dismiss stale pull request approvals when new commits are pushed (新提交时清除旧审查) - - ✅ Require review from Code Owners (如果有 CODEOWNERS 文件) - -2. **Require status checks to pass before merging** (合并前需要状态检查通过) - - - ✅ 启用此选项 - - ✅ Require branches to be up to date before merging (合并前需要更新分支) - - 必需的状态检查: - - `test (3.10)` - Python 3.10 测试 - - `test (3.11)` - Python 3.11 测试 - - `test (3.12)` - Python 3.12 测试 - - `test (3.13)` - Python 3.13 测试 - - `lint` - 代码质量检查 - - `build` - 包构建 - -3. **Require conversation resolution before merging** (合并前需要解决所有对话) - - - ✅ 启用此选项 - -4. **Require signed commits** (需要签名提交) - - - ⚠️ 可选 - 如果团队使用 GPG 签名 - -5. **Require linear history** (需要线性历史) - - - ⚠️ 可选 - 防止合并提交,保持历史清晰 - -6. **Do not allow bypassing the above settings** (不允许绕过以上设置) - - ✅ 启用此选项 (管理员也需遵守规则) - -#### 其他规则 - -- ✅ **Restrict who can push to matching branches** - 限制谁可以推送 - - 只允许维护者推送 -- ✅ **Allow force pushes** - 关闭 (防止强制推送) -- ✅ **Allow deletions** - 关闭 (防止删除主分支) - -## 📋 配置步骤 - -### 方式 1: 通过 GitHub 网页配置 (推荐) - -1. 访问仓库设置 - - ``` - https://github.com/talkincode/hyperliquid-mcp-python/settings/branches - ``` - -2. 点击 "Add branch protection rule" - -3. 在 "Branch name pattern" 中输入: `main` - -4. 启用以下选项: - - - ✅ Require a pull request before merging - - - Required number of approvals: 1 - - ✅ Dismiss stale pull request approvals when new commits are pushed - - - ✅ Require status checks to pass before merging - - - ✅ Require branches to be up to date before merging - - 添加必需的检查: - - `test (3.10)` - - `test (3.11)` - - `test (3.12)` - - `test (3.13)` - - `lint` - - `build` - - - ✅ Require conversation resolution before merging - - - ✅ Do not allow bypassing the above settings - -5. 点击 "Create" 保存 - -### 方式 2: 通过 GitHub CLI 配置 - -```bash -# 安装 GitHub CLI (如果未安装) -brew install gh - -# 登录 -gh auth login - -# 创建分支保护规则 -gh api repos/talkincode/hyperliquid-mcp-python/branches/main/protection \ - --method PUT \ - --field required_status_checks='{"strict":true,"contexts":["test (3.10)","test (3.11)","test (3.12)","test (3.13)","lint","build"]}' \ - --field enforce_admins=true \ - --field required_pull_request_reviews='{"dismiss_stale_reviews":true,"require_code_owner_reviews":false,"required_approving_review_count":1}' \ - --field restrictions=null -``` - -### 方式 3: 使用 Terraform (Infrastructure as Code) - -创建 `terraform/github.tf`: - -```hcl -resource "github_branch_protection" "main" { - repository_id = "hyperliquid-mcp-python" - pattern = "main" - - required_status_checks { - strict = true - contexts = [ - "test (3.10)", - "test (3.11)", - "test (3.12)", - "test (3.13)", - "lint", - "build" - ] - } - - required_pull_request_reviews { - dismiss_stale_reviews = true - require_code_owner_reviews = false - required_approving_review_count = 1 - } - - enforce_admins = true - require_conversation_resolution = true - require_signed_commits = false - allow_force_pushes = false - allow_deletions = false -} -``` - -## 🎯 不同场景的推荐配置 - -### 个人项目 (轻量级) - -``` -- ✅ Require status checks (CI must pass) -- ⚠️ Require PR (可选,个人项目可以直接推送) -- ⚠️ Require reviews (可选,个人项目不需要) -``` - -### 小团队项目 (2-5 人) - -``` -- ✅ Require status checks (CI must pass) -- ✅ Require pull request before merging -- ✅ Require 1 approval -- ✅ Require conversation resolution -``` - -### 开源项目 (推荐配置) - -``` -- ✅ Require status checks (CI must pass) -- ✅ Require pull request before merging -- ✅ Require 1-2 approvals -- ✅ Require conversation resolution -- ✅ Require Code Owner reviews -- ⚠️ Allow force pushes for maintainers only -``` - -### 企业项目 (严格) - -``` -- ✅ Require status checks (CI must pass) -- ✅ Require pull request before merging -- ✅ Require 2+ approvals -- ✅ Require conversation resolution -- ✅ Require Code Owner reviews -- ✅ Require signed commits -- ✅ Require linear history -- ✅ Enforce for administrators -``` - -## 📝 CODEOWNERS 文件 (可选) - -创建 `.github/CODEOWNERS` 文件来指定代码所有者: - -``` -# 默认所有者 -* @talkincode - -# 核心服务代码 -/services/ @talkincode - -# 工作流配置 -/.github/workflows/ @talkincode - -# 文档 -*.md @talkincode -``` - -## 🚨 常见问题 - -### Q: 如果我是唯一的维护者,还需要分支保护吗? - -A: 是的!至少启用 "Require status checks",确保 CI 通过才能合并。这可以防止意外破坏主分支。 - -### Q: 分支保护后如何提交代码? - -A: 通过创建 PR: - -```bash -# 1. 创建功能分支 -git checkout -b feature/my-feature - -# 2. 进行修改并提交 -git add . -git commit -m "feat: add new feature" - -# 3. 推送分支 -git push origin feature/my-feature - -# 4. 在 GitHub 创建 PR -# 5. 等待 CI 通过并合并 -``` - -### Q: 紧急修复怎么办? - -A: 即使是紧急修复,也应该: - -1. 创建 hotfix 分支 -2. 快速修复并测试 -3. 创建 PR (可以自己审查) -4. 等待 CI 通过 -5. 合并 - -### Q: 可以临时禁用分支保护吗? - -A: 不推荐,但管理员可以在设置中临时关闭 "Enforce for administrators"。 - -## ✅ 验证配置 - -配置完成后,测试: - -```bash -# 尝试直接推送到 main (应该失败) -git checkout main -git commit --allow-empty -m "test" -git push origin main -# 预期: remote: error: GH006: Protected branch update failed - -# 正确方式:通过 PR -git checkout -b test-branch-protection -git commit --allow-empty -m "test branch protection" -git push origin test-branch-protection -# 然后在 GitHub 创建 PR -``` - -## 📊 推荐的分支策略 - -### Git Flow (推荐用于发布周期的项目) - -``` -main - 生产环境,受保护 -develop - 开发分支,受保护 -feature/* - 功能分支 -hotfix/* - 紧急修复分支 -release/* - 发布分支 -``` - -### GitHub Flow (推荐用于持续部署) - -``` -main - 生产环境,受保护 -feature/* - 功能分支 -fix/* - 修复分支 -``` - -### Trunk-Based (推荐用于小团队) - -``` -main - 主分支,受保护 -feature/* - 短期功能分支 (< 2 天) -``` - -## 🎉 最佳实践 - -1. **始终通过 PR 合并** - 即使是小改动 -2. **保持 PR 小而专注** - 更容易审查 -3. **及时审查 PR** - 不要让 PR 积压 -4. **使用自动化** - 让 CI 做繁重的工作 -5. **编写清晰的 PR 描述** - 使用提供的模板 -6. **要求 CI 通过** - 这是最低要求 -7. **定期更新保护规则** - 随着项目发展调整 - -## 📚 相关资源 - -- [GitHub 分支保护文档](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches) -- [Git Flow 工作流](https://nvie.com/posts/a-successful-git-branching-model/) -- [GitHub Flow](https://guides.github.com/introduction/flow/) -- [Trunk Based Development](https://trunkbaseddevelopment.com/) - ---- - -**快速开始**: 访问 https://github.com/talkincode/hyperliquid-mcp-python/settings/branches 立即配置! 🔒 diff --git a/.github/CHECKLIST.md b/.github/CHECKLIST.md deleted file mode 100644 index 730fa4d..0000000 --- a/.github/CHECKLIST.md +++ /dev/null @@ -1,208 +0,0 @@ -# GitHub 工作流启用检查清单 - -## ✅ 已完成的配置 - -### 核心工作流 - -- [x] **CI 工作流** (`.github/workflows/ci.yml`) - - - 多版本 Python 测试 (3.10-3.13) - - 单元测试执行 - - Black/isort 代码质量检查 - - 包构建验证 - -- [x] **发布工作流** (`.github/workflows/publish.yml`) - - - 自动发布到 PyPI - - 基于 GitHub Release 触发 - - 支持手动触发 - -- [x] **Dependabot** (`.github/dependabot.yml`) - - 自动检查 GitHub Actions 更新 - - 自动检查 Python 依赖更新 - -### 协作模板 - -- [x] **Pull Request 模板** (`.github/pull_request_template.md`) -- [x] **Bug 报告模板** (`.github/ISSUE_TEMPLATE/bug_report.md`) -- [x] **功能请求模板** (`.github/ISSUE_TEMPLATE/feature_request.md`) - -### 文档 - -- [x] **贡献指南** (`CONTRIBUTING.md`) -- [x] **工作流文档** (`.github/WORKFLOWS.md`) -- [x] **设置总结** (`.github/SETUP_SUMMARY.md`) -- [x] **README 徽章** (已添加 4 个状态徽章) -- [x] **Markdown Lint 配置** (`.markdownlint.json`) - -## 🔧 需要手动配置的项目 - -### 1. PyPI Token 配置 (发布到 PyPI 需要) - -**选项 A: API Token (简单)** - -1. 访问 https://pypi.org/manage/account/token/ -2. 创建新的 API token (选择 "Entire account" 或特定项目) -3. 复制 token -4. 在 GitHub 仓库: - - Settings → Secrets and variables → Actions - - 点击 "New repository secret" - - Name: `PYPI_API_TOKEN` - - Value: 粘贴你的 token - - 点击 "Add secret" - -**选项 B: Trusted Publishing (推荐,更安全)** - -1. 在 PyPI 上进入项目设置 -2. 找到 "Publishing" 部分 -3. 添加 GitHub Actions 为 Trusted Publisher: - - Owner: `talkincode` - - Repository: `hyperliquid-mcp-python` - - Workflow: `publish.yml` - - Environment: 留空 -4. 修改 `.github/workflows/publish.yml`: - ```yaml - - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - # 不需要 password,使用 OIDC - ``` - -### 2. 测试工作流 - -**首次运行 CI:** - -```bash -# 提交所有变更 -git add . -git commit -m "feat: enable GitHub workflows with CI/CD" -git push origin main - -# 查看工作流运行状态 -open https://github.com/talkincode/hyperliquid-mcp-python/actions -``` - -**预期结果:** - -- CI 工作流应该自动触发 -- 所有测试应该通过 ✅ -- 代码质量检查应该通过 ✅ -- 包构建应该成功 ✅ - -### 3. 配置分支保护 (强烈推荐) 🔒 - -**为什么需要?** - -- 防止直接推送到主分支 -- 确保 CI 测试通过才能合并 -- 保持代码质量和稳定性 - -**快速配置:** - -1. 访问 https://github.com/talkincode/hyperliquid-mcp-python/settings/branches -2. 点击 "Add branch protection rule" -3. Branch name pattern: `main` -4. 启用以下选项: - - ✅ Require a pull request before merging - - Required approvals: 1 - - ✅ Require status checks to pass before merging - - ✅ Require branches to be up to date - - 添加必需检查: `test (3.10)`, `test (3.11)`, `test (3.12)`, `test (3.13)`, `lint`, `build` - - ✅ Require conversation resolution before merging - - ✅ Do not allow bypassing the above settings -5. 点击 "Create" - -**详细指南:** 查看 `.github/BRANCH_PROTECTION.md` - -### 4. 测试发布流程 (可选) - -**创建测试 Release:** - -```bash -# 1. 更新版本号 (如果需要) -# 编辑 pyproject.toml: version = "0.1.5" - -# 2. 提交变更 -git add pyproject.toml -git commit -m "chore: bump version to 0.1.5" - -# 3. 创建并推送标签 -git tag v0.1.5 -git push origin v0.1.5 - -# 4. 在 GitHub 创建 Release -# 访问: https://github.com/talkincode/hyperliquid-mcp-python/releases/new -# - Tag: v0.1.5 -# - Release title: v0.1.5 -# - Description: 简要说明本次发布的内容 -# - 点击 "Publish release" -``` - -**预期结果:** - -- 发布工作流应该自动触发 -- 包应该构建成功 -- 包应该发布到 PyPI ✅ - -## 📊 验证步骤 - -### 1. 检查 CI 状态 - -```bash -# 在终端中查看最近的工作流运行 -gh run list --limit 5 - -# 或访问网页 -open https://github.com/talkincode/hyperliquid-mcp-python/actions -``` - -### 2. 验证徽章显示 - -- 查看 README.md -- CI 徽章应显示为绿色 (passing) -- PyPI 版本徽章应显示最新版本 - -### 3. 测试 Dependabot - -- 等待 Dependabot 创建第一个更新 PR (通常在启用后 1-7 天内) -- 检查 PR 的格式和标签是否正确 - -## 🚨 常见问题 - -### CI 失败? - -1. 检查测试是否在本地通过: `uv run pytest` -2. 检查代码格式: `uv run black --check .` -3. 检查导入排序: `uv run isort --check-only .` - -### 发布失败? - -1. 确认已配置 `PYPI_API_TOKEN` -2. 确认 token 有效且有发布权限 -3. 检查版本号是否已存在于 PyPI - -### Dependabot 没有创建 PR? - -1. 检查 `.github/dependabot.yml` 配置 -2. 可能需要等待一周 (schedule: weekly) -3. 在仓库的 Insights → Dependency graph → Dependabot 查看状态 - -## 🎯 后续优化建议 - -1. **代码覆盖率**: 添加 Codecov 集成 -2. **性能测试**: 添加基准测试工作流 -3. **安全扫描**: 启用 CodeQL -4. **预提交钩子**: 配置 pre-commit -5. **文档部署**: 自动部署文档到 GitHub Pages - -## 📞 获取帮助 - -如遇问题: - -1. 查看 `.github/WORKFLOWS.md` 详细文档 -2. 查看 GitHub Actions 日志 -3. 参考 [GitHub Actions 文档](https://docs.github.com/actions) -4. 在项目中创建 Issue - ---- - -**快速开始**: 只需配置 PyPI Token 并 push 代码,其他都已自动配置好! 🚀 diff --git a/.github/CODE_QUALITY.md b/.github/CODE_QUALITY.md deleted file mode 100644 index 54a8cbe..0000000 --- a/.github/CODE_QUALITY.md +++ /dev/null @@ -1,285 +0,0 @@ -# 代码质量和自动格式化指南 - -本项目使用多种工具来保证代码质量和一致性。 - -## 🎯 快速开始 - -### 1. 安装 Pre-commit Hooks (推荐) - -这是**最简单的方式**,可以在每次 `git commit` 时自动格式化代码: - -```bash -# 安装 hooks -make pre-commit-install - -# 或直接使用 -uv run pre-commit install -``` - -**安装后,每次提交时会自动:** - -- ✅ 格式化代码 (black) -- ✅ 排序 imports (isort) -- ✅ 删除行尾空格 -- ✅ 检查 YAML/TOML 语法 -- ✅ 运行 ruff linter - -### 2. 手动格式化代码 - -```bash -# 格式化所有代码 -make format - -# 或单独运行 -uv run black . -uv run isort . -``` - -### 3. 检查代码(不修改) - -```bash -# 检查格式但不修改 -make check - -# 或 -uv run black --check . -uv run isort --check-only . -``` - -## 🔧 工具说明 - -### Black - 代码格式化器 - -配置在 `pyproject.toml`: - -```toml -[tool.black] -line-length = 88 -target-version = ['py310', 'py311', 'py312', 'py313'] -``` - -使用: - -```bash -# 格式化所有文件 -uv run black . - -# 检查但不修改 -uv run black --check . - -# 格式化特定文件 -uv run black services/hyperliquid_services.py -``` - -### isort - Import 排序 - -配置在 `pyproject.toml`: - -```toml -[tool.isort] -profile = "black" -line_length = 88 -``` - -使用: - -```bash -# 排序所有文件 -uv run isort . - -# 检查但不修改 -uv run isort --check-only . -``` - -### Ruff - 快速 Linter - -配置在 `pyproject.toml`: - -```toml -[tool.ruff.lint] -select = ["E", "W", "F", "I", "B", "C4", "UP"] -``` - -使用: - -```bash -# 运行 linter -uv run ruff check . - -# 自动修复 -uv run ruff check . --fix -``` - -### Pre-commit - Git Hooks - -配置在 `.pre-commit-config.yaml` - -使用: - -```bash -# 安装 hooks -uv run pre-commit install - -# 手动运行所有文件 -uv run pre-commit run --all-files - -# 更新 hooks 到最新版本 -uv run pre-commit autoupdate - -# 跳过 hooks 提交(不推荐) -git commit --no-verify -m "message" -``` - -## 🤖 自动化流程 - -### GitHub Actions - 自动格式化 - -PR 提交后,会自动运行 `.github/workflows/auto-format.yml`: - -1. 自动格式化代码 -2. 如果有变更,自动提交并推送 -3. 在 PR 中添加评论通知 - -### GitHub Actions - CI 检查 - -PR 必须通过 `.github/workflows/ci.yml` 的所有检查: - -- ✅ `test (3.10)` - Python 3.10 测试 -- ✅ `test (3.11)` - Python 3.11 测试 -- ✅ `test (3.12)` - Python 3.12 测试 -- ✅ `test (3.13)` - Python 3.13 测试 -- ✅ `lint` - 代码质量检查 -- ✅ `build` - 包构建 - -## 📋 开发工作流 - -### 推荐流程 - -```bash -# 1. 安装 pre-commit (只需一次) -make pre-commit-install - -# 2. 开发代码 -# ... 编写代码 ... - -# 3. 提交代码 (会自动格式化) -git add . -git commit -m "feat: add new feature" - -# 4. 如果 pre-commit 修改了文件 -git add . -git commit -m "feat: add new feature" - -# 5. 推送到 GitHub -git push origin feature-branch - -# 6. 创建 PR - CI 会自动检查 -``` - -### 手动流程(如果不使用 pre-commit) - -```bash -# 1. 开发代码 -# ... 编写代码 ... - -# 2. 格式化代码 -make format - -# 3. 检查是否通过 -make check - -# 4. 提交 -git add . -git commit -m "feat: add new feature" -git push -``` - -## 🚨 常见问题 - -### Q: Pre-commit 失败怎么办? - -A: Pre-commit 失败后会自动修复文件,只需重新添加并提交: - -```bash -# 1. pre-commit 运行并修复文件 -git add . - -# 2. 再次提交 -git commit -m "your message" -``` - -### Q: 如何跳过 pre-commit 检查? - -A: 不推荐,但紧急情况下可以: - -```bash -git commit --no-verify -m "emergency fix" -``` - -### Q: CI 失败说代码格式不对? - -A: 运行格式化并重新提交: - -```bash -make format -git add . -git commit -m "style: format code" -git push -``` - -### Q: 如何在 VS Code 中自动格式化? - -A: 安装扩展并配置: - -1. 安装扩展: - - - Black Formatter - - isort - -2. 在 `.vscode/settings.json` 中: - -```json -{ - "python.formatting.provider": "black", - "editor.formatOnSave": true, - "[python]": { - "editor.codeActionsOnSave": { - "source.organizeImports": true - } - } -} -``` - -### Q: 如何更新 pre-commit hooks? - -A: 定期运行: - -```bash -make pre-commit-update -``` - -## 📚 相关资源 - -- [Black 文档](https://black.readthedocs.io/) -- [isort 文档](https://pycqa.github.io/isort/) -- [Ruff 文档](https://docs.astral.sh/ruff/) -- [Pre-commit 文档](https://pre-commit.com/) - -## 🎯 最佳实践 - -1. ✅ **始终使用 pre-commit** - 最简单的方式 -2. ✅ **提交前检查** - `make check` -3. ✅ **保持工具更新** - `make pre-commit-update` -4. ✅ **不要跳过检查** - 除非紧急情况 -5. ✅ **配置 IDE** - 保存时自动格式化 - ---- - -**快速命令参考:** - -```bash -make pre-commit-install # 安装 pre-commit hooks -make format # 格式化代码 -make check # 检查代码 -make pre-commit-all # 运行所有 pre-commit 检查 -``` diff --git a/.github/SETUP_SUMMARY.md b/.github/SETUP_SUMMARY.md deleted file mode 100644 index 13d1cde..0000000 --- a/.github/SETUP_SUMMARY.md +++ /dev/null @@ -1,188 +0,0 @@ -# GitHub 工作流启用总结 - -## 📦 已创建的文件 - -### 工作流配置 - -1. **`.github/workflows/ci.yml`** - - - 持续集成工作流 - - 多版本 Python 测试 (3.10-3.13) - - 代码质量检查 (Black, isort) - - 自动构建包 - -2. **`.github/workflows/publish.yml`** - - - PyPI 发布工作流 - - 基于 GitHub Release 触发 - - 支持手动触发 - -3. **`.github/dependabot.yml`** - - 自动依赖更新 - - 每周检查 GitHub Actions 和 Python 依赖 - -### 模板文件 - -4. **`.github/pull_request_template.md`** - - - PR 标准化模板 - - 包含变更类型、测试、检查清单 - -5. **`.github/ISSUE_TEMPLATE/bug_report.md`** - - - Bug 报告模板 - - 结构化的问题描述 - -6. **`.github/ISSUE_TEMPLATE/feature_request.md`** - - 功能请求模板 - - 清晰的需求描述格式 - -### 文档 - -7. **`CONTRIBUTING.md`** - - - 贡献者指南 - - 开发流程说明 - - 代码规范和测试要求 - -8. **`.github/WORKFLOWS.md`** - - - 工作流配置详细说明 - - 使用指南和最佳实践 - -9. **`.markdownlint.json`** - - Markdown lint 配置 - - 忽略常见样式警告 - -### 更新文件 - -10. **`README.md`** - - 添加状态徽章: - - CI 状态 - - PyPI 版本 - - Python 版本支持 - - MIT 许可证 - -## 🎯 工作流特性 - -### CI 工作流 - -✅ **自动触发**: Push 到 main/develop 或 PR -✅ **多版本测试**: Python 3.10, 3.11, 3.12, 3.13 -✅ **测试套件**: - -- 单元测试 -- 验证器测试 -- 常量测试 - ✅ **代码质量**: -- Black 格式检查 -- isort 导入排序检查 - ✅ **构建验证**: 确保包可以正确构建 - -### 发布工作流 - -✅ **自动发布**: 创建 Release 时自动发布到 PyPI -✅ **手动触发**: 支持 workflow_dispatch -✅ **安全**: 使用 PyPI Trusted Publishing (推荐) - -### Dependabot - -✅ **自动更新**: 每周检查依赖 -✅ **自动 PR**: 发现更新时自动创建 PR -✅ **分类标签**: 自动标记为 dependencies - -## 🚀 下一步操作 - -### 1. 配置 PyPI Token (发布需要) - -```bash -# 方法 A: 使用 PyPI API Token (简单) -# 1. 访问 https://pypi.org/manage/account/token/ -# 2. 创建新 token -# 3. 在 GitHub 仓库添加 Secret: PYPI_API_TOKEN - -# 方法 B: 使用 Trusted Publishing (推荐,更安全) -# 1. 访问 PyPI 项目设置 -# 2. 添加 GitHub Actions 为可信发布者 -# 3. 无需 token -``` - -### 2. 测试工作流 - -```bash -# 推送代码触发 CI -git add . -git commit -m "feat: enable GitHub workflows" -git push origin main - -# 查看工作流运行 -# https://github.com/talkincode/hyperliquid-mcp-python/actions -``` - -### 3. 创建首个 Release - -```bash -# 更新版本号 -# 编辑 pyproject.toml: version = "0.1.5" - -# 提交并创建标签 -git commit -am "chore: bump version to 0.1.5" -git tag v0.1.5 -git push origin v0.1.5 - -# 在 GitHub 创建 Release -# https://github.com/talkincode/hyperliquid-mcp-python/releases/new -``` - -## 📊 工作流徽章 - -已在 README.md 中添加以下徽章: - -- **CI Status**: 显示测试是否通过 -- **PyPI Version**: 显示最新发布版本 -- **Python Versions**: 显示支持的 Python 版本 -- **License**: 显示项目许可证 - -## 🔧 可选优化 - -如果需要,可以考虑添加: - -1. **代码覆盖率**: 集成 Codecov 或 Coveralls -2. **安全扫描**: 添加 CodeQL 或 Snyk -3. **性能测试**: 添加基准测试工作流 -4. **文档部署**: 自动部署文档到 GitHub Pages -5. **Docker 镜像**: 构建并发布 Docker 镜像 - -## 📝 最佳实践 - -1. **保持 CI 快速**: 当前 CI 已优化,通常 < 5 分钟 -2. **使用缓存**: uv 自动处理依赖缓存 -3. **定期更新**: Dependabot 会自动创建更新 PR -4. **及时合并**: 及时审查和合并 Dependabot 的 PR -5. **语义化版本**: 遵循 SemVer 版本规范 - -## ✅ 完成状态 - -- [x] CI 工作流配置 -- [x] 发布工作流配置 -- [x] Dependabot 配置 -- [x] PR 模板 -- [x] Issue 模板 -- [x] 贡献指南 -- [x] 工作流文档 -- [x] README 徽章 -- [ ] 配置 PyPI Token (需要手动操作) -- [ ] 测试首次 CI 运行 -- [ ] 测试首次发布 - -## 🎉 总结 - -精简的 GitHub 工作流已成功启用!主要包括: - -✨ **自动化测试** - 每次提交都会运行完整测试套件 -✨ **代码质量保证** - 自动检查代码格式 -✨ **简化发布流程** - 创建 Release 即可自动发布 -✨ **依赖管理** - Dependabot 自动更新依赖 -✨ **标准化协作** - PR 和 Issue 模板提高协作效率 - -下一步只需配置 PyPI Token 并推送代码,即可看到工作流运行! 🚀 diff --git a/.github/WORKFLOWS.md b/.github/WORKFLOWS.md deleted file mode 100644 index a3e82f6..0000000 --- a/.github/WORKFLOWS.md +++ /dev/null @@ -1,156 +0,0 @@ -# GitHub 工作流配置 - -本项目已启用以下 GitHub Actions 工作流: - -## 📋 工作流列表 - -### 1. CI 工作流 (`.github/workflows/ci.yml`) - -**触发条件:** - -- Push 到 `main` 或 `develop` 分支 -- Pull Request 到 `main` 或 `develop` 分支 - -**功能:** - -- **多版本测试**: 在 Python 3.10, 3.11, 3.12, 3.13 上运行测试 -- **代码质量检查**: 使用 Black 和 isort 检查代码格式 -- **包构建**: 验证包可以成功构建 -- **测试覆盖**: 运行单元测试和验证测试 - -**任务:** - -1. `test` - 运行所有单元测试 -2. `lint` - 代码格式和导入检查 -3. `build` - 构建发布包 - -### 2. 发布工作流 (`.github/workflows/publish.yml`) - -**触发条件:** - -- 创建新的 GitHub Release -- 手动触发 (workflow_dispatch) - -**功能:** - -- 自动构建包 -- 发布到 PyPI - -**配置要求:** -需要在 GitHub 仓库设置中添加以下 Secret: - -- `PYPI_API_TOKEN`: PyPI API token - -### 3. Dependabot (`.github/dependabot.yml`) - -**功能:** - -- 每周自动检查 GitHub Actions 更新 -- 每周自动检查 Python 依赖更新 -- 自动创建 PR 以更新依赖 - -## 🔒 分支保护 - -为确保代码质量,强烈建议启用分支保护。详细配置指南请查看 `.github/BRANCH_PROTECTION.md`。 - -**快速配置:** - -```bash -# 使用提供的脚本一键配置 -./scripts/setup-branch-protection.sh - -# 或手动配置 -# 访问: https://github.com/talkincode/hyperliquid-mcp-python/settings/branches -``` - -**推荐的保护规则:** - -- ✅ 合并前需要 PR -- ✅ 需要 1 人审查批准 -- ✅ 必需通过所有 CI 检查 -- ✅ 合并前需要解决所有对话 -- ✅ 管理员也需遵守规则 - -## 🎯 状态徽章 - -在 README.md 中已添加以下徽章: - -- CI 工作流状态 -- PyPI 版本 -- Python 版本支持 -- 许可证 - -## 📝 模板 - -### Pull Request 模板 - -位于 `.github/pull_request_template.md` - -提供了标准化的 PR 描述格式,包括: - -- 变更描述 -- 变更类型 -- 测试说明 -- 检查清单 - -### Issue 模板 - -位于 `.github/ISSUE_TEMPLATE/` - -提供了两种模板: - -1. **Bug 报告** (`bug_report.md`): 标准化的 bug 报告格式 -2. **功能请求** (`feature_request.md`): 新功能建议格式 - -## 🚀 使用指南 - -### 本地开发 - -1. Fork 并克隆仓库 -2. 安装依赖: `uv sync --all-extras --dev` -3. 创建功能分支: `git checkout -b feature/your-feature` -4. 运行测试: `uv run pytest` -5. 格式化代码: `uv run black . && uv run isort .` -6. 提交并推送 -7. 创建 Pull Request - -### 发布新版本 - -1. 更新 `pyproject.toml` 中的版本号 -2. 提交变更: `git commit -am "chore: bump version to x.x.x"` -3. 创建标签: `git tag vx.x.x` -4. 推送标签: `git push origin vx.x.x` -5. 在 GitHub 上创建 Release -6. 发布工作流将自动运行并发布到 PyPI - -### 配置 PyPI Token - -1. 访问 https://pypi.org/manage/account/token/ -2. 创建新的 API token -3. 在 GitHub 仓库设置中: - - Settings → Secrets and variables → Actions - - 添加新 Secret: `PYPI_API_TOKEN` - -## ⚙️ 工作流优化 - -当前配置是精简模式,包含核心功能: - -- ✅ 自动化测试 -- ✅ 代码质量检查 -- ✅ 自动发布 -- ✅ 依赖更新 - -### 可选增强 - -如需要,可添加: - -- 代码覆盖率报告 (Codecov) -- 安全扫描 (Snyk, Dependabot Security) -- 自动化 Changelog 生成 -- Docker 镜像构建 - -## 📚 参考资源 - -- [GitHub Actions 文档](https://docs.github.com/actions) -- [PyPI 发布指南](https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/) -- [Dependabot 文档](https://docs.github.com/code-security/dependabot) diff --git a/.github/prompts/release.prompt.md b/.github/prompts/release.prompt.md new file mode 100644 index 0000000..efdca53 --- /dev/null +++ b/.github/prompts/release.prompt.md @@ -0,0 +1,181 @@ +--- +mode: agent +--- + +# Release 发布助手 + +你是一个自动化发布助手,帮助用户发布新版本到 PyPI。 + +## 发布流程 + +### 1. 检查当前状态 +- 检查当前分支是否是 `main`,如果不是,询问是否切换 +- 检查工作目录是否干净(无未提交的更改) +- 拉取最新代码 `git pull origin main` + +### 2. 分析版本变更(自动判断) +- 读取 `pyproject.toml` 获取当前版本号 +- 查看自上次标签以来的所有提交记录(使用 `git log`) +- **自动判断版本类型**(按优先级): + - 如果有 `BREAKING CHANGE:` 或 `!:` → 主版本号(major)+1,如 1.2.0 → 2.0.0 + - 如果有 `feat:` → 次版本号(minor)+1,如 1.2.0 → 1.3.0 + - 如果只有 `fix:`, `chore:`, `docs:` 等 → 修订号(patch)+1,如 1.2.0 → 1.2.1 + - 如果无法判断,默认使用 patch +1 +- **自动计算新版本号**,无需用户选择 + +### 3. 更新版本号 +- 在 `pyproject.toml` 中更新 `version = "x.y.z"` +- 显示更改内容让用户确认 + +### 4. 生成 Release Notes +- 基于自上次 release 以来的提交记录生成 Release Notes +- 按类型分组: + - 🚀 新功能 (feat) + - 🐛 Bug 修复 (fix) + - 📝 文档 (docs) + - ♻️ 重构 (refactor) + - ⚡ 性能优化 (perf) + - 🧹 杂项 (chore) +- 包含 Breaking Changes(如果有) +- 显示给用户确认和编辑 + +### 5. 创建发布分支和 PR +```bash +# 创建发布分支 +git checkout -b release/vx.y.z + +# 提交版本更新 +git add pyproject.toml +git commit -m "chore: bump version to x.y.z" + +# 推送分支 +git push -u origin release/vx.y.z +``` + +- 使用 GitHub API 创建 PR 到 main 分支 +- PR 标题:`chore: Release vx.y.z` +- PR 内容:第 4 步生成的 Release Notes +- 等待 CI 检查通过 +- **重要**:提示用户合并 PR 后再继续 + +### 5.5 创建标签(PR 合并后) +**注意:等待 PR 合并到 main 后执行** + +```bash +# 切换回 main 并更新 +git checkout main +git pull origin main + +# 创建并推送标签 +git tag -a vx.y.z -m "Release vx.y.z" +git push origin vx.y.z +``` + +### 6. 创建 GitHub Release +- 使用 GitHub API 创建 Release +- 标签:`vx.y.z` +- 标题:`Release vx.y.z` 或自定义标题 +- 内容:第 4 步生成的 Release Notes +- 发布后,GitHub Actions 会自动触发 PyPI 发布 + +### 7. 验证发布 +- 等待 GitHub Actions 完成(检查 workflow 状态) +- 提供 PyPI 链接:`https://pypi.org/project/hyperliquid-mcp-python/x.y.z/` +- 提供 GitHub Release 链接 + +## 注意事项 + +1. **安全检查**: + - 确认所有测试通过(检查 CI 状态) + - 确认版本号未在 PyPI 上使用过 + - 确认用户有推送权限 + +2. **错误处理**: + - 如果任何步骤失败,提供清晰的错误信息 + - 如果已经打了标签但 Release 失败,说明如何删除标签重试 + +3. **可选功能**: + - 询问是否需要 pre-release(测试版本) + - 询问是否同时更新文档 + +## 示例对话 + +**用户**:`/release` + +**助手**: +``` +🚀 开始发布流程... + +✅ 当前分支: main +✅ 工作目录干净 +✅ 已拉取最新代码 + +📦 当前版本: 1.2.3 + +📝 分析自上次发布以来的提交: + - feat: 添加新的交易工具 (3 commits) + - fix: 修复订单簿数据解析 (2 commits) + - docs: 更新 README (1 commit) + +🎯 自动判断版本号: 1.3.0 (minor - 因为有新功能 feat) + +继续发布?(y/n) +(如需自定义版本号,请输入版本号,如: 1.4.0) +``` + +**用户**:`1` + +**助手**: +``` +✅ 使用版本号 1.3.0 + +📝 生成的 Release Notes: + +## 🚀 新功能 +- 添加新的交易工具 (#123) +- 支持批量订单操作 (#125) + +## 🐛 Bug 修复 +- 修复订单簿数据解析错误 (#124) +- 修复余额显示问题 (#126) + +## 📝 文档 +- 更新 README 添加使用示例 + +确认发布?(y/n) +``` + +**用户**:`y` + +**助手**: +``` +🔄 正在发布... + +✅ 更新版本号到 1.3.0 +✅ 提交更改 +✅ 创建标签 v1.3.0 +✅ 推送到 GitHub +✅ 创建 GitHub Release + +🎉 发布成功! + +📦 PyPI: https://pypi.org/project/hyperliquid-mcp-python/1.3.0/ +📄 Release: https://github.com/talkincode/hyperliquid-mcp-python/releases/tag/v1.3.0 + +⏳ GitHub Actions 正在构建和发布... + 查看进度: https://github.com/talkincode/hyperliquid-mcp-python/actions +``` + +## 快速发布 + +### 自动版本号(推荐) +**用户**:`/release` +**助手**:自动分析提交历史,判断版本类型,计算新版本号 + +### 指定版本号 +**用户**:`/release 1.3.0` +**助手**:直接使用指定的 1.3.0 版本号 + +### 完全自动化(无确认) +**用户**:`/release --auto` +**助手**:自动判断版本号并直接发布,无需任何确认(适用于 CI/CD) diff --git a/COMPLETION_REPORT.md b/COMPLETION_REPORT.md deleted file mode 100644 index 68f217f..0000000 --- a/COMPLETION_REPORT.md +++ /dev/null @@ -1,230 +0,0 @@ -# HyperLiquid MCP 优化任务 - 完成报告 - -**执行时间**: 2025-01-27 -**状态**: ✅ 全部完成 -**测试结果**: 26/26 通过 (100%) - ---- - -## 📊 执行总结 - -### ✅ 阶段 1: 核心安全修复 - 已完成 - -#### 任务 1.1: 修复 account_address 回退逻辑 ✅ -**文件**: `services/hyperliquid_services.py` (第 50-52 行) -- ✅ 修改为 `self.account_address = account_address or self.wallet.address` -- ✅ 添加了地址掩码日志输出 -- ✅ 移除了旧的 `print` 语句 - -#### 任务 1.2: 创建 OCO 分组常量 ✅ -**文件**: `services/constants.py` (新建) -- ✅ 定义 `OCO_GROUP_NEW_POSITION = "normalTpSl"` -- ✅ 定义 `OCO_GROUP_EXISTING_POSITION = "positionTpSl"` -- ✅ 定义订单类型常量 -- ✅ 定义滑点和地址掩码配置 - -#### 任务 1.3: 修复 place_bracket_order OCO 分组 ✅ -**文件**: `services/hyperliquid_services.py` (第 14-21 行 & 第 340 行) -- ✅ 导入常量 -- ✅ 使用 `OCO_GROUP_NEW_POSITION` 替换硬编码字符串 -- ✅ 返回值中也使用常量 - -#### 任务 1.4: 修复 set_position_tpsl 未定义变量问题 ✅ -**文件**: `services/hyperliquid_services.py` (第 753-764 行) -- ✅ 直接使用自定义方法 `_bulk_orders_with_grouping` -- ✅ 使用 `OCO_GROUP_EXISTING_POSITION` 常量 -- ✅ 修复了可能的 `UnboundLocalError` - ---- - -### ✅ 阶段 2: 输入验证层 - 已完成 - -#### 任务 2.1: 创建验证器模块 ✅ -**文件**: `services/validators.py` (新建) -- ✅ `ValidationError` 异常类 -- ✅ `validate_coin()` - 币种验证 -- ✅ `validate_side()` - 订单方向验证 -- ✅ `validate_size()` - 订单大小验证(强调代币数量) -- ✅ `validate_price()` - 价格验证 -- ✅ `validate_order_inputs()` - 综合验证 - -#### 任务 2.2: 集成验证器到工具函数 ✅ -**文件**: `main.py` -- ✅ 导入验证器 (第 12 行) -- ✅ `place_limit_order` 集成验证 (第 148-166 行) -- ✅ `market_open_position` 集成验证 (第 189-206 行) -- ✅ `place_bracket_order` 集成验证 (第 261-285 行) -- ✅ `set_take_profit_stop_loss` 集成验证 (第 436-462 行) - -**改进**: -- 所有工具都返回统一的错误格式 `{"success": false, "error": "...", "error_code": "VALIDATION_ERROR"}` -- 在参数传递到服务层之前就进行验证 -- 提供清晰的错误消息 - ---- - -### ✅ 阶段 3: 最小测试覆盖 - 已完成 - -#### 任务 3.1: 创建测试目录结构 ✅ -``` -tests/ -├── __init__.py -├── conftest.py -├── unit/ -│ ├── __init__.py -│ ├── test_validators.py (16 个测试) -│ └── test_constants.py (4 个测试) -└── integration/ - ├── __init__.py - ├── test_oco_grouping.py (2 个测试) - └── test_account_address.py (4 个测试) -``` - -#### 任务 3.2-3.4: 编写测试 ✅ -- ✅ **16 个验证器单元测试** - 覆盖所有验证函数 -- ✅ **4 个常量测试** - 验证常量值正确 -- ✅ **2 个 OCO 分组测试** - 验证 bracket 和 position TP/SL 使用正确分组 -- ✅ **4 个账户地址回退测试** - 验证回退逻辑 - -#### 任务 3.5: 配置 pytest ✅ -**文件**: `pyproject.toml` & `tests/conftest.py` -- ✅ 添加 `pytest-asyncio` 依赖 -- ✅ 配置测试路径和选项 -- ✅ 配置异步模式 - ---- - -## 🧪 测试结果 - -```bash -$ uv run pytest tests/ -v -=============================== 26 passed in 0.34s =============================== - -✅ tests/integration/test_account_address.py::test_account_address_fallback_to_wallet -✅ tests/integration/test_account_address.py::test_account_address_uses_provided -✅ tests/integration/test_account_address.py::test_account_address_not_none -✅ tests/integration/test_oco_grouping.py::test_bracket_order_uses_correct_grouping -✅ tests/integration/test_oco_grouping.py::test_set_position_tpsl_uses_correct_grouping -✅ tests/unit/test_constants.py::test_oco_group_constants -✅ tests/unit/test_constants.py::test_order_type_constants -✅ tests/unit/test_constants.py::test_slippage_constants -✅ tests/unit/test_constants.py::test_address_mask_constants -✅ tests/unit/test_validators.py::test_validate_size_zero -✅ tests/unit/test_validators.py::test_validate_size_negative -✅ tests/unit/test_validators.py::test_validate_size_valid -✅ tests/unit/test_validators.py::test_validate_side_invalid -✅ tests/unit/test_validators.py::test_validate_side_valid -✅ tests/unit/test_validators.py::test_validate_coin_empty -✅ tests/unit/test_validators.py::test_validate_coin_none -✅ tests/unit/test_validators.py::test_validate_coin_valid -✅ tests/unit/test_validators.py::test_validate_price_zero -✅ tests/unit/test_validators.py::test_validate_price_negative -✅ tests/unit/test_validators.py::test_validate_price_valid -✅ tests/unit/test_validators.py::test_validate_order_inputs_valid -✅ tests/unit/test_validators.py::test_validate_order_inputs_no_price -✅ tests/unit/test_validators.py::test_validate_order_inputs_invalid_coin -✅ tests/unit/test_validators.py::test_validate_side_invalid -✅ tests/unit/test_validators.py::test_validate_order_inputs_invalid_size -✅ tests/unit/test_validators.py::test_validate_order_inputs_invalid_price -``` - ---- - -## 📝 文件变更汇总 - -### 新建文件 (5个) -1. `services/constants.py` - 常量定义 -2. `services/validators.py` - 输入验证器 -3. `tests/conftest.py` - pytest 配置 -4. `tests/unit/test_validators.py` - 验证器测试 -5. `tests/unit/test_constants.py` - 常量测试 -6. `tests/integration/test_oco_grouping.py` - OCO 分组测试 -7. `tests/integration/test_account_address.py` - 账户地址测试 - -### 修改文件 (3个) -1. `services/hyperliquid_services.py` - - 导入常量 - - 修复 account_address 回退 - - 修复 place_bracket_order 分组 - - 修复 set_position_tpsl 未定义变量 - -2. `main.py` - - 导入验证器 - - 4 个工具函数集成输入验证 - -3. `pyproject.toml` - - 添加 pytest-asyncio 依赖 - - 添加 pytest 配置 - ---- - -## 🎯 关键改进 - -### 安全性提升 -- ✅ 修复了 `account_address=None` 时的潜在崩溃 -- ✅ 修复了 `set_position_tpsl` 中的未定义变量错误 -- ✅ 所有订单输入现在都经过验证 - -### 代码质量提升 -- ✅ 消除了魔法字符串,使用常量 -- ✅ 统一的错误处理和返回格式 -- ✅ 清晰的验证错误消息 - -### 可维护性提升 -- ✅ 26 个自动化测试覆盖关键功能 -- ✅ 测试套件运行快速(0.34 秒) -- ✅ 易于扩展的验证器架构 - ---- - -## ✨ 测试覆盖的关键场景 - -### 输入验证 -- ✅ 空币种、负价格、零大小被拒绝 -- ✅ 非法订单方向("long"/"short")被拒绝 -- ✅ 提供清晰的错误消息 - -### OCO 分组 -- ✅ 新仓位使用 `normalTpSl` -- ✅ 现有仓位使用 `positionTpSl` - -### 账户初始化 -- ✅ `account_address=None` 回退到 `wallet.address` -- ✅ 提供地址时使用提供的地址 -- ✅ 永远不会出现 `None` 地址 - ---- - -## 🚀 下一步建议 - -虽然 MVP 已完成,但以下是可选的增强方向: - -1. **测试覆盖率扩展** - - 为更多服务方法添加单元测试 - - 端到端集成测试(需要测试网密钥) - -2. **日志改进** - - 结构化 JSON 日志 - - 日志级别配置 - -3. **文档更新** - - 在 README 中记录新的验证器 - - API 文档生成 - -4. **CI/CD** - - GitHub Actions 自动测试 - - 代码覆盖率报告 - ---- - -## 📌 总结 - -**目标**: 快速修复最严重的 bug 并建立最小测试覆盖 -**结果**: ✅ 超额完成 - -- 修复了 4 个 P0 级别的严重 bug -- 添加了完整的输入验证层 -- 建立了 26 个自动化测试(100% 通过率) -- 所有代码都经过验证和测试 - -**项目现在处于稳定且可测试的状态!** 🎉 diff --git a/EXAMPLES.md b/EXAMPLES.md deleted file mode 100644 index 67ff739..0000000 --- a/EXAMPLES.md +++ /dev/null @@ -1,1057 +0,0 @@ -# HyperLiquid MCP 详细使用示例 - -本文档提供所有 MCP 工具的详细使用示例和最佳实践,所有示例均基于实际的 API 方法。 - -## 重要说明 - -⚠️ **所有示例中的 `size` 参数都是代币数量,不是美元金额!** - -- ✅ 正确:`size=0.1` 表示 0.1 个 BTC -- ❌ 错误:`size=1000` 误认为是 $1000(实际是 1000 个 BTC) - -💡 如需使用美元金额,请使用 `calculate_token_amount_from_dollars` 工具先转换。 - -## 目录 - -- [账户管理](#账户管理) -- [市场数据查询](#市场数据查询) -- [开仓交易](#开仓交易) -- [仓位管理](#仓位管理) -- [订单管理](#订单管理) -- [工具函数](#工具函数) -- [完整交易流程](#完整交易流程) - ---- - -## 账户管理 - -### 1. 获取账户余额 - -**工具名称**:`get_account_balance` - -```python -# 查询账户余额和保证金信息 -result = await get_account_balance() - -# 返回示例 -{ - "success": True, - "data": { - "marginSummary": { - "accountValue": "10000.00", # 账户总价值 - "totalMarginUsed": "2000.00", # 已用保证金 - "totalNtlPos": "5000.00", # 总名义持仓 - "totalRawUsd": "8000.00" # 可用余额 - }, - "assetPositions": [...] - }, - "account_address": "0x..." -} -``` - -**使用场景**: -- 交易前检查账户余额 -- 计算可开仓位大小 -- 监控保证金使用率 - ---- - -### 2. 查看持仓 - -```python -# 获取所有开仓 -positions = get_open_positions() - -# 返回示例 -{ - "success": true, - "positions": [ - { - "coin": "BTC", - "size": "0.5", # 仓位大小(正数做多,负数做空) - "entry_price": "45000.00", # 开仓均价 - "unrealized_pnl": "500.00", # 未实现盈亏 - "return_on_equity": "0.05", # 收益率 5% - "margin_used": "2250.00" # 使用保证金 - }, - { - "coin": "ETH", - "size": "-2.0", # 负数表示做空 - "entry_price": "3000.00", - "unrealized_pnl": "-100.00", - "return_on_equity": "-0.02", - "margin_used": "3000.00" - } - ], - "total_positions": 2 -} -``` - -**使用场景**: -- 查看当前持仓状态 -- 计算总盈亏 -- 决定是否需要调仓 - ---- - -### 3. 查看未成交订单 - -```python -# 获取所有挂单 -orders = get_open_orders() - -# 返回示例 -{ - "success": true, - "orders": [ - { - "order_id": 12345, - "coin": "BTC", - "side": "buy", # buy 或 sell - "size": "0.1", - "limit_price": "44000.00", - "reduce_only": false, - "order_type": "limit", - "timestamp": 1698765432000, - "cloid": "0x1234..." # 客户端订单ID(如有) - } - ], - "total_orders": 1 -} -``` - ---- - -### 4. 账户总览 - -```python -# 一次获取完整账户信息 -summary = get_account_summary() - -# 返回示例 -{ - "success": true, - "summary": { - "balance": {...}, # 余额信息 - "positions": [...], # 持仓列表 - "orders": [...], # 挂单列表 - "total_positions": 2, - "total_orders": 3 - } -} -``` - -**使用场景**: -- 快速了解账户全貌 -- 生成账户报告 -- 交易前全面检查 - ---- - -## 市场数据查询 - -### 1. 获取市场行情 - -```python -# 查询 BTC 市场数据 -market_data = get_market_data("BTC") - -# 返回示例 -{ - "success": true, - "market_data": { - "coin": "BTC", - "mid_price": "45500.00", # 中间价 - "best_bid": "45499.50", # 最佳买价 - "best_ask": "45500.50", # 最佳卖价 - "bid_size": "2.5", # 买单量 - "ask_size": "1.8", # 卖单量 - "max_leverage": 50, # 最大杠杆 - "only_isolated": false, # 是否仅支持逐仓 - "timestamp": 1698765432000 - } -} -``` - -**使用场景**: -- 获取实时价格 -- 计算买卖价差 -- 确定下单价格 - ---- - -### 2. 获取订单簿 - -```python -# 获取 ETH 订单簿(深度 10) -orderbook = get_orderbook("ETH", depth=10) - -# 返回示例 -{ - "success": true, - "orderbook": { - "coin": "ETH", - "bids": [ # 买单(按价格降序) - {"px": "3000.00", "sz": "5.2"}, - {"px": "2999.50", "sz": "3.1"}, - ... - ], - "asks": [ # 卖单(按价格升序) - {"px": "3000.50", "sz": "4.8"}, - {"px": "3001.00", "sz": "6.3"}, - ... - ], - "timestamp": 1698765432000 - } -} -``` - -**使用场景**: -- 分析市场深度 -- 寻找支撑位/阻力位 -- 大单滑点估算 - ---- - -### 3. 查询资金费率 - -```python -# 获取 SOL 最近 7 天资金费率 -funding = get_funding_history("SOL", days=7) - -# 返回示例 -{ - "success": true, - "funding_history": [ - { - "time": 1698700800000, - "fundingRate": "0.0001", # 0.01% 资金费率 - "premium": "0.00008" - }, - ... - ], - "coin": "SOL", - "days": 7 -} -``` - -**使用场景**: -- 评估持仓成本 -- 选择持仓时机 -- 套利机会分析 - ---- - -## 开仓交易 - -### 1. 市价开仓(最简单) - -```python -# 示例 1: 市价做多 0.1 BTC -result = market_open_position( - coin="BTC", - side="buy", # "buy" 做多,"sell" 做空 - size=0.1 # 0.1 个 BTC(不是美元金额!) -) - -# 示例 2: 市价做空 1 ETH -result = market_open_position( - coin="ETH", - side="sell", # 做空 - size=1.0 -) - -# 返回示例 -{ - "success": true, - "action": "market_open_position", - "order_result": { - "status": "ok", - "response": { - "type": "order", - "data": { - "statuses": [ - { - "filled": { - "totalSz": "0.1", - "avgPx": "45500.00" - } - } - ] - } - } - }, - "position_details": { - "coin": "BTC", - "side": "long", - "size": "0.1", - "order_type": "market" - } -} -``` - -**重要提示**: -- ✅ `size=0.1` 表示 0.1 个 BTC -- ❌ `size=1000` 不是 $1000,而是 1000 个 BTC! - ---- - -### 2. 美元金额开仓(推荐) - -```python -# 第 1 步:将美元转换为代币数量 -calc = await calculate_token_amount_from_dollars("SOL", 100.0) # $100 - -# 返回示例 -{ - "success": True, - "coin": "SOL", - "dollar_amount": 100.0, - "current_price": 150.0, - "token_amount": 0.66666667, # $100 ÷ $150 = 0.667 SOL - "calculation": "$100.0 ÷ $150.0 = 0.66666667 SOL" -} - -# 第 2 步:使用计算出的代币数量开仓 -result = await market_open_position( - coin="SOL", - side="buy", - size=calc["token_amount"] # 使用计算出的代币数量 -) -``` - ---- - -### 3. 限价开仓 - -```python -# 限价单:在 $44000 买入 0.1 BTC -result = place_limit_order( - coin="BTC", - side="buy", - size=0.1, - price=44000.0, - reduce_only=False, # False=可开新仓 - client_order_id="0x1234..." # 可选:自定义订单ID -) - -# 返回示例 -{ - "success": true, - "order_result": {...}, - "order_details": { - "coin": "BTC", - "side": "BUY", - "size": 0.1, - "limit_price": 44000.0, - "order_type": {"limit": {"tif": "Gtc"}}, - "reduce_only": false - } -} -``` - -**订单类型说明**: -- `Gtc` (Good Till Cancel): 一直有效直到成交或取消 -- `Ioc` (Immediate Or Cancel): 立即成交否则取消 -- `Alo` (Add Liquidity Only): 只做 Maker - ---- - -### 4. 括号订单(开仓 + 止盈止损) - -```python -# 一键开仓并设置止盈止损 -result = place_bracket_order( - coin="BTC", - side="buy", - size=0.1, - entry_price=45000.0, # 入场价 - take_profit_price=47000.0, # 止盈价(+4.4%) - stop_loss_price=43000.0 # 止损价(-4.4%) -) - -# 返回示例 -{ - "success": true, - "bulk_result": { - "status": "ok", - "response": {...} - }, - "order_details": { - "coin": "BTC", - "side": "BUY", - "size": 0.1, - "entry_price": 45000.0, - "take_profit_price": 47000.0, - "stop_loss_price": 43000.0, - "grouping": "normalTpSl" # OCO 分组 - } -} -``` - -**OCO 行为**: -- 止盈和止损互斥 -- 触发一个,另一个自动取消 -- 适合新开仓位 - ---- - -## 仓位管理 - -### 1. 为现有仓位设置止盈止损 - -```python -# 场景:已有 BTC 多仓,现在设置止盈止损 - -# 方式 1:同时设置止盈和止损 -result = set_take_profit_stop_loss( - coin="BTC", - take_profit_price=47000.0, - stop_loss_price=43000.0 - # position_size 会自动检测 -) - -# 方式 2:只设置止盈 -result = set_take_profit("BTC", 47000.0) - -# 方式 3:只设置止损 -result = set_stop_loss("BTC", 43000.0) - -# 返回示例 -{ - "success": true, - "bulk_result": {...}, - "position_details": { - "coin": "BTC", - "position_size": 0.5, # 自动检测到的仓位大小 - "is_long": true, # 多仓 - "take_profit_price": 47000.0, - "stop_loss_price": 43000.0, - "grouping": "positionTpSl" # 现有仓位的 OCO 分组 - } -} -``` - -**注意事项**: -- 必须先有仓位才能设置 -- 自动检测仓位大小和方向 -- 支持多次修改止盈止损 - ---- - -### 2. 市价平仓 - -```python -# 平掉所有 BTC 仓位 -result = market_close_position("BTC") - -# 返回示例 -{ - "success": true, - "action": "market_close_position", - "order_result": {...}, - "order_details": { - "coin": "BTC", - "original_side": "long", # 原仓位方向 - "original_size": "0.5", # 原仓位大小 - "side": "sell", # 平仓方向(做多平空,做空平多) - "reduce_only": true - } -} -``` - -**使用场景**: -- 快速止损 -- 获利了结 -- 紧急平仓 - ---- - -### 3. 部分平仓 - -```python -# ⚠️ market_close_position 会平掉全部仓位 -# 部分平仓需要用 place_limit_order + reduce_only=True - -# 示例:平掉 50% 的 BTC 仓位 - -# 步骤 1: 获取当前仓位信息 -positions = await get_open_positions() -btc_position = [p for p in positions["positions"] if p["coin"] == "BTC"][0] -position_size = abs(float(btc_position["size"])) -is_long = float(btc_position["size"]) > 0 - -# 步骤 2: 获取当前价格 -market_data = await get_market_data("BTC") -current_price = float(market_data["market_data"]["mid_price"]) - -# 步骤 3: 使用限价单平掉一半 -result = await place_limit_order( - coin="BTC", - side="sell" if is_long else "buy", # 反向 - size=position_size * 0.5, # 平 50% - price=current_price * 0.999, # 稍微激进的价格 - reduce_only=True # 重要:只减仓 -) -``` - ---- - -### 4. 调整杠杆 - -```python -# 设置 BTC 为 10 倍全仓杠杆 -result = update_leverage( - coin="BTC", - leverage=10, - cross_margin=True # True=全仓,False=逐仓 -) - -# 设置 ETH 为 5 倍逐仓杠杆 -result = update_leverage( - coin="ETH", - leverage=5, - cross_margin=False -) - -# 返回示例 -{ - "success": true, - "leverage_result": {...}, - "leverage_update": { - "coin": "BTC", - "leverage": 10, - "cross_margin": true - } -} -``` - -**注意事项**: -- 有持仓时调整杠杆可能受限 -- 先平仓再调整更安全 - ---- - -## 订单管理 - -### 1. 取消单个订单 - -```python -# 按订单 ID 取消 -result = cancel_order("BTC", order_id=12345) - -# 按客户端订单 ID 取消 -result = cancel_order_by_client_id( - "BTC", - "0x1234567890abcdef1234567890abcdef" -) - -# 返回示例 -{ - "success": true, - "cancel_result": {...}, - "cancelled_order": { - "coin": "BTC", - "order_id": 12345 - } -} -``` - ---- - -### 2. 批量取消订单 - -```python -# 取消 BTC 的所有挂单 -result = cancel_all_orders("BTC") - -# 取消所有币种的所有挂单 -result = cancel_all_orders() - -# 返回示例 -{ - "success": true, - "cancelled_orders": 5, - "failed_cancellations": 0, - "results": [...] -} -``` - ---- - -### 3. 修改订单 - -```python -# 修改订单价格和数量 -result = modify_order( - coin="BTC", - order_id=12345, - new_size=0.2, # 新数量 - new_price=44500.0 # 新价格 -) - -# 返回示例 -{ - "success": true, - "modify_result": {...}, - "modified_order": { - "coin": "BTC", - "order_id": 12345, - "new_size": "0.2", - "new_price": "44500.0" - } -} -``` - ---- - -## 工具函数 - -### 1. calculate_token_amount_from_dollars - 美元转代币数量 - -这是最常用的辅助工具,用于将美元金额转换为代币数量。 - -```python -# 转换 $100 为 SOL 代币数量 -calc = await calculate_token_amount_from_dollars( - coin="SOL", - dollar_amount=100.0 -) - -# 返回示例 -{ - "success": True, - "coin": "SOL", - "dollar_amount": 100.0, - "current_price": 150.0, - "token_amount": 0.66666667, # $100 ÷ $150 = 0.667 SOL - "calculation": "$100.0 ÷ $150.0 = 0.66666667 SOL" -} -``` - -**组合使用示例**: -```python -# 步骤 1: 转换美元为代币数量 -calc = await calculate_token_amount_from_dollars("BTC", 500.0) - -# 步骤 2: 使用转换后的数量开仓 -if calc["success"]: - result = await market_open_position( - coin="BTC", - side="buy", - size=calc["token_amount"] - ) -``` - ---- - -### 2. close_position - 关闭仓位(辅助函数) - -这是对 `market_close_position` 的封装,支持百分比参数。 - -```python -# 关闭 100% 仓位 -result = await close_position( - coin="BTC", - percentage=100.0 -) - -# ⚠️ 注意:不支持部分平仓 -result = await close_position(coin="BTC", percentage=50.0) -# 会返回错误: -# "Partial position closure (50%) not supported with market orders." -``` - -**部分平仓需要使用 place_limit_order**: -```python -# 获取仓位信息 -positions = await get_open_positions() -btc_pos = next(p for p in positions["positions"] if p["coin"] == "BTC") -position_size = abs(float(btc_pos["size"])) -is_long = float(btc_pos["size"]) > 0 - -# 获取当前价格 -market_data = await get_market_data("BTC") -current_price = float(market_data["market_data"]["mid_price"]) - -# 平掉 50% -result = await place_limit_order( - coin="BTC", - side="sell" if is_long else "buy", - size=position_size * 0.5, - price=current_price * 0.999, - reduce_only=True -) -``` - ---- - -## 完整交易流程示例 - -### 示例 1: 基于美元金额开仓并设置止盈止损 - -```python -# 步骤 1: 转换美元为代币数量 -calc = await calculate_token_amount_from_dollars("BTC", 200.0) - -if not calc["success"]: - print(f"转换失败: {calc.get('error')}") -else: - token_amount = calc["token_amount"] - entry_price = calc["current_price"] - - # 步骤 2: 计算止盈止损价格(止盈 5%,止损 3%) - tp_price = entry_price * 1.05 # 做多,止盈 +5% - sl_price = entry_price * 0.97 # 做多,止损 -3% - - # 步骤 3: 开仓 - open_result = await market_open_position( - coin="BTC", - side="buy", - size=token_amount - ) - - if not open_result["success"]: - print(f"开仓失败: {open_result.get('error')}") - else: - # 步骤 4: 设置止盈止损 - tpsl_result = await set_take_profit_stop_loss( - coin="BTC", - take_profit_price=tp_price, - stop_loss_price=sl_price - ) - - print(f"✅ 交易完成:") - print(f" 投资: $200") - print(f" 数量: {token_amount} BTC") - print(f" 入场价: ${entry_price}") - print(f" 止盈: ${tp_price} (+5%)") - print(f" 止损: ${sl_price} (-3%)") -``` - ---- - -### 示例 2: 风险管理开仓 - -```python -# 目标: 用账户的 2% 风险做多 BTC,止损 5% - -# 步骤 1: 获取账户余额 -balance = await get_account_balance() -account_value = float(balance["data"]["marginSummary"]["accountValue"]) - -# 步骤 2: 计算风险金额和仓位大小 -risk_percent = 0.02 # 2% 风险 -stop_loss_percent = 0.05 # 5% 止损 -risk_amount = account_value * risk_percent - -# 获取当前价格 -market_data = await get_market_data("BTC") -current_price = float(market_data["market_data"]["mid_price"]) - -# 计算仓位大小 -# 风险金额 = 仓位价值 × 止损百分比 -position_value = risk_amount / stop_loss_percent -position_size = position_value / current_price - -# 步骤 3: 开仓 -open_result = await market_open_position( - coin="BTC", - side="buy", - size=position_size -) - -# 步骤 4: 设置止损 -stop_price = current_price * (1 - stop_loss_percent) -sl_result = await set_stop_loss("BTC", stop_price) - -print(f"✅ 风险管理开仓完成:") -print(f" 账户价值: ${account_value}") -print(f" 最大风险: ${risk_amount} ({risk_percent*100}%)") -print(f" 仓位大小: {position_size} BTC") -print(f" 止损价格: ${stop_price}") -``` - ---- - -### 示例 3: 带错误处理的安全交易 - -```python -# 步骤 1: 检查账户余额 -balance = await get_account_balance() -if not balance["success"]: - print(f"获取余额失败: {balance.get('error')}") -else: - account_value = float(balance["data"]["marginSummary"]["accountValue"]) - dollar_amount = 100.0 - - # 安全检查: 不超过账户 90% - if dollar_amount > account_value * 0.9: - print("交易金额过大,超过账户 90%") - else: - # 步骤 2: 转换美元为代币数量 - calc = await calculate_token_amount_from_dollars("BTC", dollar_amount) - if not calc["success"]: - print(f"金额转换失败: {calc.get('error')}") - else: - # 步骤 3: 验证市场数据 - market_data = await get_market_data("BTC") - if not market_data["success"]: - print("获取市场数据失败") - else: - # 步骤 4: 开仓 - result = await market_open_position( - coin="BTC", - side="buy", - size=calc["token_amount"] - ) - - if not result["success"]: - print(f"开仓失败: {result.get('error')}") - else: - # 步骤 5: 设置 5% 止损 - current_price = float(market_data["market_data"]["mid_price"]) - stop_price = current_price * 0.95 - - sl_result = await set_stop_loss("BTC", stop_price) - - print(f"✅ 交易成功:") - print(f" 投资: ${dollar_amount}") - print(f" 数量: {calc['token_amount']} BTC") - print(f" 入场价: ${calc['current_price']}") - print(f" 止损: ${stop_price}") -``` - ---- - -## 常见问题 - -### Q1: 为什么我的订单没有成交? - -```python -# 检查未成交订单并对比市场价格 -orders = await get_open_orders() - -for order in orders["orders"]: - # 获取当前市价 - market = await get_market_data(order['coin']) - current_price = float(market["market_data"]["mid_price"]) - order_price = float(order['limit_price']) - - print(f"币种: {order['coin']}") - print(f"订单价格: ${order_price}") - print(f"当前市价: ${current_price}") - print(f"价差: ${abs(current_price - order_price):.2f}") -``` - ---- - -### Q2: 如何查看交易历史? - -```python -# 获取最近 30 天交易记录 -history = await get_trade_history(days=30) - -if history["success"]: - for trade in history["trades"]: - side_text = "买入" if trade['side'] == "B" else "卖出" - print(f"{trade['time']}: {side_text} {trade['size']} {trade['coin']} @ ${trade['price']}") - print(f" 手续费: ${trade['fee']}") -``` - ---- - -### Q3: 如何在测试网和主网之间切换? - -**方法 1: 环境变量** -```bash -# 测试网 -export HYPERLIQUID_TESTNET=true - -# 主网 -export HYPERLIQUID_TESTNET=false -``` - -**方法 2: .env 文件** -``` -HYPERLIQUID_TESTNET=true -``` - -**方法 3: config.json** -```json -{ - "private_key": "your_key", - "testnet": true, - "account_address": "your_address" -} -``` - ---- - -### Q4: 为什么止盈止损没有互斥? - -确保使用正确的方法: - -- **新仓位**: 使用 `place_bracket_order()` → 使用 `normalTpSl` 分组 -- **现有仓位**: 使用 `set_take_profit_stop_loss()` → 使用 `positionTpSl` 分组 - -两者都会实现 OCO(One-Cancels-Other)行为。 - ---- - -### Q5: 如何部分平仓? - -`market_close_position()` 会平掉所有仓位。部分平仓需要使用限价单: - -```python -# 获取当前仓位 -positions = await get_open_positions() -btc_pos = next(p for p in positions["positions"] if p["coin"] == "BTC") -position_size = abs(float(btc_pos["size"])) -is_long = float(btc_pos["size"]) > 0 - -# 获取当前价格 -market_data = await get_market_data("BTC") -current_price = float(market_data["market_data"]["mid_price"]) - -# 平掉 50% - 使用限价单 + reduce_only -result = await place_limit_order( - coin="BTC", - side="sell" if is_long else "buy", - size=position_size * 0.5, - price=current_price * 0.999, # 稍微激进的价格 - reduce_only=True -) -``` - ---- - -## 性能优化建议 - -### 1. 使用账户总览减少 API 调用 - -```python -# ❌ 不推荐: 多次调用 -balance = await get_account_balance() -positions = await get_open_positions() -orders = await get_open_orders() - -# ✅ 推荐: 一次获取所有信息 -summary = await get_account_summary() -# summary 包含 balance, positions, orders -``` - ---- - -### 2. 并发获取多个币种数据 - -```python -import asyncio - -# 并发获取 BTC、ETH、SOL 的市场数据 -tasks = [ - get_market_data("BTC"), - get_market_data("ETH"), - get_market_data("SOL") -] -results = await asyncio.gather(*tasks) - -# 访问结果 -btc_data, eth_data, sol_data = results -print(f"BTC 价格: {btc_data['market_data']['mid_price']}") -print(f"ETH 价格: {eth_data['market_data']['mid_price']}") -print(f"SOL 价格: {sol_data['market_data']['mid_price']}") -``` - ---- - -## 总结 - -### 核心 MCP 工具列表 - -**账户管理工具**: -- `get_account_balance()` - 获取余额和保证金信息 -- `get_open_positions()` - 查看所有持仓 -- `get_open_orders()` - 查看所有未成交订单 -- `get_account_summary()` - 获取账户完整信息 -- `get_trade_history(days)` - 获取交易历史 - -**市场数据工具**: -- `get_market_data(coin)` - 获取实时行情 -- `get_orderbook(coin, depth)` - 获取订单簿 -- `get_funding_history(coin, days)` - 查询资金费率 - -**交易工具**: -- `market_open_position(coin, side, size)` - 市价开仓 ⭐ -- `market_close_position(coin)` - 市价平仓 -- `place_limit_order(coin, side, size, price, reduce_only)` - 限价订单 -- `place_bracket_order(coin, side, size, entry_price, tp_price, sl_price)` - 括号订单(新仓位) - -**订单管理工具**: -- `cancel_order(coin, order_id)` - 取消订单 -- `cancel_order_by_client_id(coin, client_order_id)` - 按客户端ID取消 -- `cancel_all_orders(coin)` - 批量取消订单 -- `modify_order(coin, order_id, new_size, new_price)` - 修改订单 - -**仓位管理工具**: -- `set_take_profit_stop_loss(coin, tp_price, sl_price)` - 设置止盈止损(现有仓位)⭐ -- `set_take_profit(coin, tp_price)` - 只设置止盈 -- `set_stop_loss(coin, sl_price)` - 只设置止损 -- `update_leverage(coin, leverage, cross_margin)` - 调整杠杆 -- `transfer_between_spot_and_perp(amount, to_perp)` - 资金划转 - -**工具函数**: -- `calculate_token_amount_from_dollars(coin, dollar_amount)` - 美元转代币数量 ⭐ -- `close_position(coin, percentage)` - 关闭仓位(辅助函数) - ---- - -### 关键要点 - -1. ✅ **size 参数是代币数量**,不是美元金额 -2. ✅ 使用 `calculate_token_amount_from_dollars()` 进行美元转换 -3. ✅ 新仓位用 `place_bracket_order()`,现有仓位用 `set_take_profit_stop_loss()` -4. ✅ 市价开仓用 `market_open_position()`,市价平仓用 `market_close_position()` -5. ✅ 所有工具都是异步的,需要使用 `await` -6. ✅ 所有操作都有标准化的 `{"success": bool, ...}` 返回格式 - ---- - -### 安全提示 - -- 🔒 **始终在测试网先测试**策略和代码 -- 🔒 **设置合理的止损**保护资金安全 -- 🔒 **不要投入超过你能承受损失的资金** -- 🔒 **使用 API 钱包**而非主钱包私钥 -- 🔒 **定期检查持仓和风险敞口** -- 🔒 **验证所有计算结果**再下单 - ---- - -### 快速参考 - -**开仓流程**: -```python -# 1. 转换美元 -calc = await calculate_token_amount_from_dollars("BTC", 100.0) -# 2. 开仓 -result = await market_open_position("BTC", "buy", calc["token_amount"]) -# 3. 设置止盈止损 -await set_take_profit_stop_loss("BTC", tp_price=50000, sl_price=40000) -``` - -**查询流程**: -```python -# 获取完整账户信息 -summary = await get_account_summary() -# 获取市场数据 -market = await get_market_data("BTC") -``` - -**平仓流程**: -```python -# 全部平仓 -await market_close_position("BTC") -# 部分平仓 - 使用限价单 + reduce_only=True -await place_limit_order("BTC", "sell", 0.5, price, reduce_only=True) -``` diff --git a/MAKEFILE_GUIDE.md b/MAKEFILE_GUIDE.md deleted file mode 100644 index f8815c7..0000000 --- a/MAKEFILE_GUIDE.md +++ /dev/null @@ -1,159 +0,0 @@ -# Makefile 使用指南 - -## 🚀 快速开始 - -```bash -# 1. 安装依赖 -make install - -# 2. 查看配置 -make config - -# 3. 快速验证 -make test-quick - -# 4. 运行服务器 -make run-http -``` - -## 📋 所有命令 - -### 开发命令 - -| 命令 | 说明 | -|------|------| -| `make install` | 安装依赖(uv sync) | -| `make dev` | 开发模式安装 | -| `make run-http` | 启动 HTTP 服务器 (http://127.0.0.1:8080) | -| `make run-stdio` | 启动 stdio 服务器(用于 MCP 客户端) | -| `make config` | 查看当前配置(隐藏私钥) | -| `make logs` | 查看日志文件 | - -### 测试命令 - -| 命令 | 说明 | -|------|------| -| `make test-all` | 运行所有只读测试 ⭐ | -| `make test-quick` | 快速验证(连接+余额+地址) | -| `make test-connection` | 基础连接测试 | -| `make test-account` | 账户信息测试 | -| `make test-balance` | 账户余额检查(现货+合约) | -| `make test-market` | 市场数据测试 | -| `make test-orderbook` | 订单簿测试 | -| `make test-funding` | 资金费率历史测试 | -| `make test-calculator` | 价格计算器测试 | -| `make test-address` | 地址验证测试 | -| `make test-interactive` | 交互式测试工具 | -| `make list-tests` | 列出所有可用测试脚本 | - -### 代码质量 - -| 命令 | 说明 | -|------|------| -| `make format` | 格式化代码(black + isort) | -| `make check` | 检查代码但不修改 | -| `make lint` | 运行代码检查 | -| `make test` | 运行单元测试 | - -### 构建和发布 - -| 命令 | 说明 | -|------|------| -| `make clean` | 清理构建文件 | -| `make build` | 构建发布包 | -| `make publish` | 发布到 PyPI | -| `make test-pypi` | 发布到测试 PyPI | -| `make all` | clean + build | -| `make release` | clean + build + publish | - -### 文档和帮助 - -| 命令 | 说明 | -|------|------| -| `make help` | 显示所有可用命令 | -| `make test-help` | 显示测试快速参考 | -| `make docs` | 显示完整 README | -| `make test-docs` | 显示测试文档 | -| `make list-tests` | 列出所有测试脚本 | - -## 🎯 常用工作流 - -### 首次配置 - -```bash -# 1. 克隆仓库 -git clone https://github.com/jamiesun/hyperliquid-mcp.git -cd hyperliquid-mcp - -# 2. 安装依赖 -make install - -# 3. 配置环境变量 -cp .env.example .env -# 编辑 .env 文件,填入你的配置 - -# 4. 验证配置 -make test-quick - -# 5. 运行所有测试 -make test-all -``` - -### 日常开发 - -```bash -# 查看配置 -make config - -# 测试连接 -make test-connection - -# 启动服务器 -make run-http - -# 查看日志 -make logs -``` - -### 测试新功能 - -```bash -# 测试市场数据 -make test-market - -# 测试账户信息 -make test-account - -# 交互式测试 -make test-interactive -``` - -### 发布新版本 - -```bash -# 清理 -make clean - -# 构建 -make build - -# 发布到测试 PyPI -make test-pypi - -# 发布到正式 PyPI -make publish -``` - -## 💡 提示 - -- 所有测试命令都是**只读**的,不会修改账户状态 -- 使用 `make test-quick` 可以快速验证配置是否正确 -- `make test-all` 会运行所有测试,适合全面检查 -- `make config` 会隐藏私钥,可以安全地查看配置 -- 首次使用建议在测试网环境下进行 (`HYPERLIQUID_TESTNET=true`) - -## 🔗 相关文档 - -- [主 README](../README.md) -- [测试脚本文档](test_scripts/README.md) -- [测试快速参考](test_scripts/QUICK_REFERENCE.md) diff --git a/SETUP_AUTO_FORMAT.md b/SETUP_AUTO_FORMAT.md deleted file mode 100644 index 22fb836..0000000 --- a/SETUP_AUTO_FORMAT.md +++ /dev/null @@ -1,129 +0,0 @@ -# 🚀 自动代码格式化 - 快速设置指南 - -## 一次性设置 (推荐) - -```bash -# 1. 安装 pre-commit hooks -make pre-commit-install - -# 完成! 现在每次 git commit 都会自动格式化代码 -``` - -## 它做了什么? - -安装后,**每次 `git commit` 时会自动:** - -✅ 使用 black 格式化 Python 代码 -✅ 使用 isort 排序 imports -✅ 删除行尾空格 -✅ 修复文件结尾换行 -✅ 检查 YAML/TOML 语法 -✅ 运行 ruff linter - -## 提交流程示例 - -```bash -# 1. 修改代码 -vim main.py - -# 2. 正常提交 (pre-commit 会自动运行) -git add main.py -git commit -m "feat: add new feature" - -# 如果 pre-commit 修复了格式,你会看到: -# black....................................Failed -# - hook id: black -# - files were modified by this hook -# -# 只需重新添加并提交: -git add main.py -git commit -m "feat: add new feature" - -# 3. 推送 -git push -``` - -## GitHub Actions 自动格式化 - -PR 提交后,如果代码格式不对: - -1. **自动格式化 workflow** 会运行 -2. 自动修复并提交到你的 PR 分支 -3. 在 PR 中添加评论: "✨ Code has been automatically formatted" - -**你不需要做任何事!** 机器人会自动修复。 - -## 手动格式化 (可选) - -如果你想手动格式化: - -```bash -# 格式化所有文件 -make format - -# 检查格式 (不修改) -make check - -# 运行所有 pre-commit 检查 -make pre-commit-all -``` - -## VS Code 集成 (可选) - -在 VS Code 中保存时自动格式化: - -1. 安装扩展: - - - **Black Formatter** (ms-python.black-formatter) - - **isort** (ms-python.isort) - -2. 在项目中创建 `.vscode/settings.json`: - -```json -{ - "python.formatting.provider": "black", - "editor.formatOnSave": true, - "[python]": { - "editor.defaultFormatter": "ms-python.black-formatter", - "editor.codeActionsOnSave": { - "source.organizeImports": true - } - } -} -``` - -## 常见问题 - -### Q: 如何跳过 pre-commit? - -不推荐,但紧急时可以: - -```bash -git commit --no-verify -m "emergency fix" -``` - -### Q: Pre-commit 太慢怎么办? - -只检查修改的文件: - -```bash -# pre-commit 默认只检查 staged 的文件 -# 如果想检查所有文件: -uv run pre-commit run --all-files -``` - -### Q: 如何更新 hooks? - -```bash -make pre-commit-update -``` - -## 更多信息 - -- 📖 完整文档: `.github/CODE_QUALITY.md` -- 🔧 配置文件: `.pre-commit-config.yaml` -- ⚙️ 工具配置: `pyproject.toml` - ---- - -**记住: 只需运行一次 `make pre-commit-install`,之后一切自动化!** ✨ diff --git a/TASK.md b/TASK.md deleted file mode 100644 index 462ecf9..0000000 --- a/TASK.md +++ /dev/null @@ -1,562 +0,0 @@ -# HyperLiquid MCP 优化任务计划 - -## 📋 MVP 优化方案 (1-2天完成) - -本计划专注于最高优先级的安全和功能修复,采用最小可行方案快速提升代码质量。 - ---- - -## 🎯 阶段 1: 核心安全修复 (4-6小时) - -### ✅ 任务 1.1: 修复 account_address 回退逻辑 -**优先级**: 🔴 P0 - 严重 -**文件**: `services/hyperliquid_services.py` -**问题**: 当未提供 `account_address` 时可能传递 `None` 导致运行时错误 - -**修改内容**: -```python -# 第 48-53 行修改 -# 原代码: -self.account_address = account_address -print(self.account_address) - -# 修改为: -self.account_address = account_address or self.wallet.address -self.logger.info( - f"Account initialized: {self.account_address[:6]}...{self.account_address[-4:]}" -) -``` - -**验证**: -- [ ] 运行服务初始化,不提供 `account_address` 参数 -- [ ] 检查日志输出是否包含掩码后的地址 -- [ ] 确认 `self.account_address` 不为 `None` - ---- - -### ✅ 任务 1.2: 创建 OCO 分组常量 -**优先级**: 🔴 P0 - 严重 -**文件**: `services/constants.py` (新建) - -**创建内容**: -```python -"""HyperLiquid MCP 常量定义""" - -# OCO 订单分组类型 -OCO_GROUP_NEW_POSITION = "normalTpSl" # 新仓位的括号订单 -OCO_GROUP_EXISTING_POSITION = "positionTpSl" # 现有仓位的止盈止损 - -# 订单类型常量 -ORDER_TYPE_LIMIT_GTC = {"limit": {"tif": "Gtc"}} -ORDER_TYPE_LIMIT_IOC = {"limit": {"tif": "Ioc"}} - -# 滑点配置 -DEFAULT_SLIPPAGE = 0.001 # 0.1% -AGGRESSIVE_SLIPPAGE = 0.5 # 50% - -# 地址掩码配置 -ADDRESS_PREFIX_LEN = 6 -ADDRESS_SUFFIX_LEN = 4 -``` - -**验证**: -- [ ] 文件创建成功 -- [ ] 可以成功导入常量 - ---- - -### ✅ 任务 1.3: 修复 place_bracket_order OCO 分组 -**优先级**: 🔴 P0 - 严重 -**文件**: `services/hyperliquid_services.py` - -**修改位置 1** - 导入常量 (第 1 行后添加): -```python -from .constants import ( - OCO_GROUP_NEW_POSITION, - OCO_GROUP_EXISTING_POSITION, - ORDER_TYPE_LIMIT_GTC, - ADDRESS_PREFIX_LEN, - ADDRESS_SUFFIX_LEN -) -``` - -**修改位置 2** - `place_bracket_order` 方法 (约第 334 行): -```python -# 原代码: -bulk_result = self._bulk_orders_with_grouping(order_requests, grouping="normalTpsl") - -# 修改为: -bulk_result = self._bulk_orders_with_grouping( - order_requests, - grouping=OCO_GROUP_NEW_POSITION -) -``` - -**修改位置 3** - 返回值 (约第 345 行): -```python -# 原代码: -"grouping": "normalTpSl" - -# 修改为: -"grouping": OCO_GROUP_NEW_POSITION -``` - -**验证**: -- [ ] 代码编译通过 -- [ ] 运行 `place_bracket_order` 测试 -- [ ] 检查日志确认分组参数为 `normalTpSl` - ---- - -### ✅ 任务 1.4: 修复 set_position_tpsl 未定义变量问题 -**优先级**: 🔴 P0 - 严重 -**文件**: `services/hyperliquid_services.py` - -**修改位置** - `set_position_tpsl` 方法 (约第 737-750 行): -```python -# 原代码: -try: - # First, let's try the standard bulk_orders approach - bulk_result = self.exchange.bulk_orders(order_requests) - self.logger.info(f"Standard bulk_orders result: {bulk_result}") -except Exception as e: - self.logger.error(f"Standard bulk_orders failed with exception: {e}") - # Fall back to custom method - -# 修改为: -try: - # 直接使用自定义方法确保分组正确 - bulk_result = self._bulk_orders_with_grouping( - order_requests, - grouping=OCO_GROUP_EXISTING_POSITION - ) - self.logger.info(f"Position TP/SL set successfully: {bulk_result}") -except Exception as e: - self.logger.error( - f"Failed to set position TP/SL for {coin}: {e}", - exc_info=True - ) - return { - "success": False, - "error": f"Failed to submit OCO TP/SL orders: {str(e)}", - "coin": coin - } -``` - -**修改位置 2** - 返回值中的分组 (约第 758 行): -```python -# 原代码: -"grouping": "positionTpSl" - -# 修改为: -"grouping": OCO_GROUP_EXISTING_POSITION -``` - -**验证**: -- [ ] 代码编译通过 -- [ ] 模拟测试设置止盈止损 -- [ ] 确认异常情况下不会出现 `UnboundLocalError` - ---- - -## 🎯 阶段 2: 输入验证层 (3-4小时) - -### ✅ 任务 2.1: 创建验证器模块 -**优先级**: 🔴 P0 - 严重 -**文件**: `services/validators.py` (新建) - -**创建内容**: -```python -"""输入验证工具""" -from typing import Optional - -class ValidationError(ValueError): - """验证错误""" - pass - -def validate_coin(coin: str) -> None: - """验证币种参数""" - if not coin or not isinstance(coin, str): - raise ValidationError("coin must be non-empty string") - if not coin.replace("-", "").replace("_", "").isalnum(): - raise ValidationError(f"invalid coin format: {coin}") - -def validate_side(side: str, is_buy: Optional[bool] = None) -> bool: - """验证订单方向 - - Returns: - bool: True for buy, False for sell - """ - if is_buy is not None: - return is_buy - - side_lower = side.lower().strip() - if side_lower not in ("buy", "sell"): - raise ValidationError( - f"side must be 'buy' or 'sell', got: '{side}'" - ) - return side_lower == "buy" - -def validate_size(size: float, min_size: float = 0.0) -> None: - """验证订单大小(代币数量,非美元金额)""" - if not isinstance(size, (int, float)): - raise ValidationError( - f"size must be numeric, got: {type(size).__name__}" - ) - if size <= min_size: - raise ValidationError( - f"size must be > {min_size} (token amount, not dollar value), got: {size}" - ) - -def validate_price(price: float) -> None: - """验证价格""" - if not isinstance(price, (int, float)): - raise ValidationError( - f"price must be numeric, got: {type(price).__name__}" - ) - if price <= 0: - raise ValidationError(f"price must be > 0, got: {price}") - -def validate_order_inputs( - coin: str, - side: str, - size: float, - price: Optional[float] = None -) -> dict: - """综合验证订单输入 - - Returns: - dict: {"coin": str, "is_buy": bool, "size": float, "price": float (optional)} - """ - validate_coin(coin) - is_buy = validate_side(side) - validate_size(size) - - result = { - "coin": coin, - "is_buy": is_buy, - "size": float(size) - } - - if price is not None: - validate_price(price) - result["price"] = float(price) - - return result -``` - -**验证**: -- [ ] 文件创建成功 -- [ ] 导入测试通过 - ---- - -### ✅ 任务 2.2: 集成验证器到工具函数 -**优先级**: 🔴 P0 - 严重 -**文件**: `main.py` - -**修改位置 1** - 导入 (第 1 行后添加): -```python -from services.validators import validate_order_inputs, ValidationError -``` - -**修改位置 2** - `place_limit_order` 工具 (约第 97 行): -```python -@mcp.tool -async def place_limit_order( - coin: str, - side: str, - size: float, - price: float, - reduce_only: bool = False, - client_order_id: Optional[str] = None -) -> Dict[str, Any]: - """...""" - initialize_service() - - try: - # 验证输入 - validated = validate_order_inputs(coin, side, size, price) - - return await hyperliquid_service.place_order( - coin=validated["coin"], - is_buy=validated["is_buy"], - sz=validated["size"], - limit_px=validated["price"], - reduce_only=reduce_only, - cloid=client_order_id - ) - except ValidationError as e: - return { - "success": False, - "error": f"Invalid input: {str(e)}", - "error_code": "VALIDATION_ERROR" - } -``` - -**类似修改** - 应用到以下工具: -- [ ] `market_open_position` (约第 136 行) -- [ ] `place_bracket_order` (约第 165 行) -- [ ] `set_take_profit_stop_loss` (约第 441 行) - -**验证**: -- [ ] 传入非法参数测试 (size=0, side="invalid", coin="") -- [ ] 检查返回错误格式包含 `error_code` - ---- - -## 🎯 阶段 3: 最小测试覆盖 (3-4小时) - -### ✅ 任务 3.1: 创建测试目录结构 -**优先级**: 🟡 P1 - 重要 - -**创建目录**: -``` -tests/ -├── __init__.py -├── conftest.py -├── unit/ -│ ├── __init__.py -│ ├── test_validators.py -│ └── test_constants.py -└── integration/ - ├── __init__.py - ├── test_oco_grouping.py - └── test_account_address.py -``` - -**验证**: -- [ ] 目录创建成功 -- [ ] `__init__.py` 文件存在 - ---- - -### ✅ 任务 3.2: 编写验证器单元测试 -**优先级**: 🟡 P1 - 重要 -**文件**: `tests/unit/test_validators.py` - -**测试内容** (关键测试): -```python -"""验证器测试""" -import pytest -from services.validators import ( - validate_coin, validate_side, validate_size, - validate_price, ValidationError -) - -def test_validate_size_zero(): - """测试 size=0 抛出错误""" - with pytest.raises(ValidationError, match="must be >"): - validate_size(0) - -def test_validate_size_negative(): - """测试负数 size 抛出错误""" - with pytest.raises(ValidationError, match="must be >"): - validate_size(-1) - -def test_validate_side_invalid(): - """测试非法 side 抛出错误""" - with pytest.raises(ValidationError, match="must be 'buy' or 'sell'"): - validate_side("long") - -def test_validate_coin_empty(): - """测试空币种抛出错误""" - with pytest.raises(ValidationError, match="non-empty"): - validate_coin("") -``` - -**验证**: -- [ ] `pytest tests/unit/test_validators.py -v` 通过 - ---- - -### ✅ 任务 3.3: 编写 OCO 分组集成测试 -**优先级**: 🟡 P1 - 重要 -**文件**: `tests/integration/test_oco_grouping.py` - -**测试内容**: -```python -"""OCO 分组测试""" -import pytest -from unittest.mock import MagicMock, patch -from services.hyperliquid_services import HyperliquidServices -from services.constants import OCO_GROUP_NEW_POSITION, OCO_GROUP_EXISTING_POSITION - -@pytest.fixture -def mock_service(): - """创建 mock 服务实例""" - with patch('services.hyperliquid_services.Info'), \ - patch('services.hyperliquid_services.Exchange'), \ - patch('services.hyperliquid_services.Account'): - service = HyperliquidServices( - private_key="0x" + "1" * 64, - testnet=True, - account_address="0xTEST" - ) - return service - -@pytest.mark.asyncio -async def test_bracket_order_uses_correct_grouping(mock_service, monkeypatch): - """测试 place_bracket_order 使用 normalTpSl 分组""" - captured_grouping = None - - def mock_bulk_orders(order_requests, grouping="na"): - nonlocal captured_grouping - captured_grouping = grouping - return {"status": "ok"} - - monkeypatch.setattr( - mock_service, - "_bulk_orders_with_grouping", - mock_bulk_orders - ) - - await mock_service.place_bracket_order( - coin="BTC", - is_buy=True, - sz=0.1, - limit_px=45000, - take_profit_px=47000, - stop_loss_px=43000 - ) - - assert captured_grouping == OCO_GROUP_NEW_POSITION -``` - -**验证**: -- [ ] `pytest tests/integration/test_oco_grouping.py -v` 通过 - ---- - -### ✅ 任务 3.4: 编写 account_address 回退测试 -**优先级**: 🟡 P1 - 重要 -**文件**: `tests/integration/test_account_address.py` - -**测试内容**: -```python -"""账户地址回退测试""" -import pytest -from unittest.mock import patch, MagicMock -from services.hyperliquid_services import HyperliquidServices - -@pytest.mark.asyncio -async def test_account_address_fallback_to_wallet(): - """测试未提供 account_address 时回退到 wallet.address""" - with patch('services.hyperliquid_services.Info'), \ - patch('services.hyperliquid_services.Exchange'), \ - patch('services.hyperliquid_services.Account') as mock_account_class: - - # Mock wallet - mock_wallet = MagicMock() - mock_wallet.address = "0xWALLET_ADDRESS_12345" - mock_account_class.from_key.return_value = mock_wallet - - # 不提供 account_address - service = HyperliquidServices( - private_key="0x" + "1" * 64, - testnet=True, - account_address=None # 关键:传入 None - ) - - # 应该回退到 wallet.address - assert service.account_address == "0xWALLET_ADDRESS_12345" - assert service.account_address is not None -``` - -**验证**: -- [ ] `pytest tests/integration/test_account_address.py -v` 通过 - ---- - -### ✅ 任务 3.5: 配置 pytest -**优先级**: 🟡 P1 - 重要 -**文件**: `tests/conftest.py` - -**创建内容**: -```python -"""pytest 配置""" -import pytest -import sys -from pathlib import Path - -# 添加项目根目录到 Python 路径 -project_root = Path(__file__).parent.parent -sys.path.insert(0, str(project_root)) -``` - -**文件**: `pyproject.toml` (添加配置) - -**添加内容**: -```toml -[tool.pytest.ini_options] -testpaths = ["tests"] -python_files = ["test_*.py"] -python_classes = ["Test*"] -python_functions = ["test_*"] -addopts = "-v --tb=short" -``` - -**验证**: -- [ ] `uv run pytest tests/ -v` 运行所有测试 - ---- - -## 📝 完成标准 - -### 阶段 1 完成标准: -- [x] `account_address` 回退逻辑修复 -- [x] 常量文件创建并导入成功 -- [x] `place_bracket_order` 使用常量 -- [x] `set_position_tpsl` 无未定义变量错误 -- [x] 日志输出地址已掩码 - -### 阶段 2 完成标准: -- [x] 验证器模块创建 -- [x] 至少 4 个工具集成验证器 -- [x] 非法输入返回 `VALIDATION_ERROR` - -### 阶段 3 完成标准: -- [x] 测试目录结构创建 -- [x] 验证器单元测试 100% 通过 -- [x] OCO 分组测试通过 -- [x] account_address 回退测试通过 -- [x] `pytest tests/ -v` 全绿 - ---- - -## 🚀 执行顺序 - -1. **先做阶段 1** (最高优先级,解决严重 bug) -2. **再做阶段 2** (防止新 bug 引入) -3. **最后做阶段 3** (锁定改进成果) - -每完成一个任务立即验证,确保通过后再进行下一个。 - ---- - -## ⏱️ 预估时间 - -| 阶段 | 预计时间 | 累计时间 | -|------|---------|---------| -| 阶段 1 | 4-6 小时 | 4-6 小时 | -| 阶段 2 | 3-4 小时 | 7-10 小时 | -| 阶段 3 | 3-4 小时 | 10-14 小时 | - -**总计**: 10-14 小时 (约 1.5-2 个工作日) - ---- - -## 📞 后续可选增强 (不在 MVP 范围) - -- [ ] 异步 SDK 包装 (asyncio.to_thread) -- [ ] 结构化日志 (JSON 格式) -- [ ] 响应格式 Pydantic 模型 -- [ ] CI/CD GitHub Actions -- [ ] 测试覆盖率 > 60% - -**建议**: 完成 MVP 后评估实际需求再决定是否实施。 - ---- - -**状态更新**: 📋 计划已创建,待开始执行 -**最后更新**: 2025-01-27 diff --git a/verify_completion.py b/test_scripts/verify_completion.py similarity index 100% rename from verify_completion.py rename to test_scripts/verify_completion.py